Summary description for Dictionary
示例#1
1
		void ServerConsole()
		{
			var stringMatch = new Regex(@"\""(?<text>.*?)\""|(?<text>\w+)", RegexOptions.Compiled);
			var commands = new Dictionary<string, Action<string[]>>()
			{
				["shutdown"] = this.Shutdown,
				["quit"] = this.Shutdown,
				["save"] = this.Save,
			};
			while(true)
			{
				string line = Console.ReadLine();
				var matches = stringMatch.Matches(line);
				var command = matches.Cast<Match>().Take(1).Select(x => x.Groups["text"].Value).First().ToLower();
				var args = matches.Cast<Match>().Skip(1).Select(x => x.Groups["text"].Value).ToArray();
				if(commands.ContainsKey(command))
				{
					commands[command](args);
				}
				else
				{
					Console.WriteLine("Command ´{0}´ not found.", command);
				}
			}
		}
示例#2
1
        public static void Main(string[] args)
        {
            Dictionary<string, Action> options = new Dictionary<string, Action>()
            {
                { "interfaces", PrintNetworkInterfaces },
                { "interfaceproperties", PrintNetworkInterfaceProperties },
                { "interfacestatistics", PrintNetworkInterfaceStatistics },
                { "ipv4", PrintIpv4Statistics },
                { "ipv6", PrintIpv6Statistics },
                { "icmp4", PrintIcmp4Statistics },
                { "icmp6", PrintIcmp6Statistics },
                { "udp4", PrintUdp4Statistics },
                { "udp6", PrintUdp6Statistics },
                { "tcp4", PrintTcp4Statistics },
                { "tcp6", PrintTcp6Statistics },
                { "connections", PrintSocketConnections },
                { "networkchange", NetworkChangeTest },
                { "ipglobal", PrintIPGlobals }
            };

            string selection = (args?.Length >= 1) ? args[0] : null;
            if (selection == null || !options.Keys.Contains(selection))
            {
                Console.WriteLine("Options: " + Environment.NewLine + string.Join(Environment.NewLine, options.Keys.Select(s => $"* {s}")));
            }
            else
            {
                options[selection]();
            }
        }
示例#3
1
 public string InvokeOutputMethod(string method, string param)
 {
     Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() {
     {"IsChecked",()=>IsChecked()?"1":"0"}
     };
     return dictMethod[method]();
 }
        /// <summary>
        /// Initialize the QvFacebookConnection.
        /// </summary>
        public override void Init()
        {
            QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, "Init()");

            // Log in to facebook
            LoginToFacebook();

            MTables = new List<QvxTable>();

            // Create all supported tables
            var tableDictionary = new Dictionary<FacebookMetadataTag, Func<FacebookMetadataTag, QvxTable>>
                {
                    { FacebookMetadataTag.friends, x => CreatePersonsTable(x) },
                    { FacebookMetadataTag.family, x => CreatePersonsTable(x) },
                    { FacebookMetadataTag.movies, x => CreateEntertainmentTable(x) },
                    { FacebookMetadataTag.television, x => CreateEntertainmentTable(x) },
                    { FacebookMetadataTag.likes, x => CreateEntertainmentTable(x) },
                    { FacebookMetadataTag.books, x => CreateEntertainmentTable(x) },
                    { FacebookMetadataTag.music, x => CreateEntertainmentTable(x) },
                    { FacebookMetadataTag.games, x => CreateEntertainmentTable(x) },
                };

            if (tableDictionary.Keys.Count != Enum.GetNames(typeof(FacebookMetadataTag)).Length)
            {
                QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Warning, "Init() - Mismatch between the number of supported metadata tags and tables");
            }

            foreach (var key in tableDictionary.Keys)
            {
                MTables.Add(tableDictionary[key](key));
            }
        }
示例#5
1
        public void Run(IBus bus, TextWriter w)
        {
            c.Add(bus.Subscribe<MessageA>(onMessageA));
            c.Add(bus.Subscribe<MessageB>(onMessageB));
            c.Add(bus.Subscribe<MessageC>(onMessageC));

            var r = new Random();
            var dict = new Dictionary<int, Func<object>>
                           {
                               {0, () => new MessageA()},
                               {1, () => new MessageB()},
                               {2, () => new MessageC()},
                           };
            int count = 0;
            var sw = Stopwatch.StartNew();
            while (count < 100000)
            {
                bus.Publish(dict[r.Next(0, 3)]());
                count++;
            }

            w.WriteLine("Through {0}", sw.ElapsedMilliseconds);

            count = 0;
            while (count < 10)
            {
                w.WriteLine("From MsgA:{0}({1}), B:{2}({3}), C:{4}({5})", aCount, MessageA.Count, bCount,
                            MessageB.Count, cCount, MessageC.Count);
                Thread.Sleep(1000);
                count++;
            }
        }
    public void FireStateEvent(Dictionary<int, StateListenerEvent> vDic,
	                           int vStateType,
	                           object vObj)
    {
        if(vDic.ContainsKey(vStateType))
            vDic[vStateType](vObj);
    }
示例#7
1
 public string InvokeOutputMethod(string method, string param)
 {
     Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() {
     {"GetCellText",()=>GetCellText(Convert.ToInt32(param.Split('|')[0]),Convert.ToInt32(param.Split('|')[1]))}
     };
     return dictMethod[method]();
 }
示例#8
1
        public void Configuration(IAppBuilder app)
        {
            app.Use(async (ctx, next) =>
            {
                var actions = new Dictionary<string, Func<IAsyncDocumentSession, Task>>
                {
                    {"GET", async session =>
                    {
                        var url = await session.LoadAsync<Url>(ctx.Request.Path.Value.Substring(1));
                        if (url != null)
                        {
                            ctx.Response.StatusCode = (int) HttpStatusCode.MovedPermanently;
                            ctx.Response.Headers["Location"] = url.Location;
                        }
                        else ctx.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    }},
                    {"POST", async session =>
                    {
                        var random = new Random();
                        var hash = string.Join("", Enumerable.Range(0, 7).Select(_ => Chars[random.Next(Chars.Length)]));

                        await session.StoreAsync(new Url {Id = hash, Location = ctx.Request.Query["path"]});
                        await session.SaveChangesAsync();

                        ctx.Response.StatusCode = (int)HttpStatusCode.Created;
                        await ctx.Response.WriteAsync(hash);
                    }}
                };

                using (var session = DocumentStore.OpenAsyncSession())
                    await actions[ctx.Request.Method](session);
            });
        }
示例#9
1
 public string InvokeOutputMethod(string method, string param)
 {
     Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() {
     {"GetText",()=>GetText()}
     };
     return dictMethod[method]();
 }
示例#10
1
        public void Run(IBus bus, TextWriter w)
        {
            _c.Add(bus.Subscribe<MessageA>(OnMessageA));
            _c.Add(bus.Subscribe<MessageB>(OnMessageB));
            _c.Add(bus.Subscribe<MessageC>(OnMessageC));

            var r = new Random();
            var dict = new Dictionary<int, Func<object>>
                           {
                               {0, () => new MessageA()},
                               {1, () => new MessageB()},
                               {2, () => new MessageC()},
                           };
            int count = 0;
            var sw = Stopwatch.StartNew();
            while (count < 100000)
            {
                bus.Publish(dict[r.Next(0, 3)]());
                count++;
            }

            w.WriteLine("Through {0}", sw.ElapsedMilliseconds);

            while (_aCount != MessageA.Count && _bCount != MessageB.Count && _cCount != MessageC.Count)
            {
                WriteInfo(w);
                Thread.Sleep(1000);
            }
            WriteInfo(w);
        }
示例#11
1
    public static void ClientHandler(TcpClient client) {
        var d = new Dictionary<string, ProcessCommand>() {
            { "cat", CatFile },
            { "clx", CalcClx },
            { "erf", CalcErf },
            { "sz", FileSize },
            { "info", GetInfo }
        };

        while (client.Connected) {
            using (var streamReader = new StreamReader(client.GetStream()))
            using (var streamWriter = new StreamWriter(client.GetStream())) {
                var cmd = streamReader.ReadLine().Split(" ".ToCharArray(), 2);

                try {
                    d[cmd[0]](cmd[1], streamWriter);
                }
                catch {
                    streamWriter.WriteLine("Error :(");
                }
                streamWriter.Flush();
            }
        }
        client.Close();
    }
示例#12
1
        static void Main(string[] args)
        {
            var names = Regex.Split(Console.ReadLine(), "\\s+").ToList();
            var predicates = new Dictionary<string, Func<string, string, bool>>
            {
                { "StartsWith", (name, substring) => name.StartsWith(substring) },
                { "EndsWith", (name, substring) => name.EndsWith(substring) },
                { "Length", (name, length) => name.Length.ToString().Equals(length) }
            };

            string command;
            while ((command = Console.ReadLine()) != "Party!")
            {
                if (names.Count == 0)
                {
                    break;
                }

                var parameters = Regex.Split(command, "\\s+");

                var action = parameters[0];
                var condition = parameters[1];
                var conditionOperator = parameters[2];

                var filteredNames = new List<string>();
                foreach (string name in names)
                {
                    if (predicates[condition](name, conditionOperator))
                    {
                        switch (action)
                        {
                            case "Double":
                                filteredNames.Add(name);
                                filteredNames.Add(name);
                                break;
                            case "Remove":
                                // Not adding jack.
                                break;
                            default:
                                throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        filteredNames.Add(name);
                    }
                }

                names = filteredNames.ToList();
            }

            if (names.Count != 0)
            {
                Console.WriteLine($"{string.Join(", ", names)} are going to the party!");
            }
            else
            {
                Console.WriteLine("Nobody is going to the party!");
            }
        }
示例#13
1
        public static RuleRewriter Create(Type type, ISettings settings, Func<SemanticModel> semanticModel)
        {
            // A dictionary of all recognised constructor parameters.
            Dictionary<Type, Func<object>> parameterTypes = new Dictionary<Type, Func<object>>
            {
                { typeof(ISettings), () => settings },
                { typeof(SemanticModel), semanticModel },
            };

            // Get a list of the type's constructors together with the constructor parameters types,
            // ordered by number of parameters descending.
            var ctors = (from c in type.GetConstructors()
                         select new
                         {
                             ConstructorInfo = c,
                             Parameters = c.GetParameters()
                         }).OrderByDescending(x => x.Parameters.Length).ToArray();

            // Get the first constructor in which we recognise all parameter types.
            var ctor = ctors.FirstOrDefault(x => x.Parameters.All(p => parameterTypes.Keys.Contains(p.ParameterType)));

            object[] parameters = ctor.Parameters.Select(x => parameterTypes[x.ParameterType]()).ToArray();

            return (RuleRewriter)ctor.ConstructorInfo.Invoke(parameters);
        }
示例#14
1
        public static void FromFile(string csvPath, string jsonPath, Dictionary<string, string> propertyMapper, Dictionary<string, Func<string, dynamic>> customValueMappers, Func<Dictionary<string, dynamic>, bool> excludeEntryPredicate)
        {
            string[] lines = File.ReadAllLines(csvPath);
            if (lines.Length == 0)
            {
                return;
            }

            string[] properties = ParseProperties(lines[0], propertyMapper);

            List<Dictionary<string, dynamic>> jsonPayload = new List<Dictionary<string, dynamic>>(lines.Length - 1);

            foreach (string line in lines.Skip(1))
            {
                Dictionary<string, dynamic> entry = new Dictionary<string, dynamic>();

                int propertyIndex = 0;
                foreach (string value in CleanCsvEntry(SplitCsvLine(line)))
                {
                    string property = properties[propertyIndex];
                    entry[property] = customValueMappers.ContainsKey(property) ? customValueMappers[property](value) : ParseValue(value);
                    propertyIndex++;
                }

                if (excludeEntryPredicate != null && excludeEntryPredicate(entry))
                {
                    continue;
                }

                jsonPayload.Add(entry);
            }

            File.WriteAllText(jsonPath, JsonConvert.SerializeObject(jsonPayload, Formatting.Indented));
        }
        //private void PrepareLiveDataVector()
        //{
        //    if ((model == (StaticString.beforeBlank + Database.GetText("QM125T-8H", "QingQi"))) ||
        //        (model == (StaticString.beforeBlank + Database.GetText("QM250GY", "QingQi"))) ||
        //        (model == (StaticString.beforeBlank + Database.GetText("QM250T", "QingQi"))))
        //    {
        //        Manager.LiveDataVector = Database.GetLiveData("Synerject");
        //    }
        //    else if ((model == (StaticString.beforeBlank + Database.GetText("QM200GY-F", "QingQi"))) ||
        //        (model == (StaticString.beforeBlank + Database.GetText("QM200-3D", "QingQi"))) ||
        //        (model == (StaticString.beforeBlank + Database.GetText("QM200J-3L", "QingQi"))))
        //    {
        //        Manager.LiveDataVector = Database.GetLiveData("Mikuni");
        //    }
        //    else
        //    {
        //        Manager.LiveDataVector = Database.GetLiveData("Visteon");
        //    }
        //}

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Create your application here
            Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);
            List<string> arrays = new List<string>();
            arrays.Add(StaticString.beforeBlank + Database.GetText("Dynamic Data Stream", "System"));
            arrays.Add(StaticString.beforeBlank + Database.GetText("Static Data Stream", "System"));

            funcs = new Dictionary<string, Func>();
            
            funcs.Add(Database.GetText("Dynamic Data Stream", "System"), () => 
            {
                //PrepareLiveDataVector();
                Intent intent = new Intent(this, typeof(DataStreamActivity));
                intent.PutExtra("Model", model);
                StartActivity(intent);
            });
            funcs.Add(Database.GetText("Static Data Stream", "System"), () => 
            {
                //PrepareLiveDataVector();
                Intent intent = new Intent(this, typeof(StaticDataStreamActivity));
                intent.PutExtra("Model", model);
                StartActivity(intent);
            });

            ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, arrays);

            ListView.ItemClick += (sender, e) => 
            {
                string test = ((TextView)e.View).Text;
                funcs[test.TrimStart(' ')]();
            };
        }
 public AutoRedirectTests()
 {
     var responders = new Dictionary<string, Action<IOwinContext>>
     {
         { "/redirect-absolute-302", context =>
             {
                 context.Response.StatusCode = 302;
                 context.Response.ReasonPhrase = "Found";
                 context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
             }
         },
         { "/redirect-relative", context =>
             {
                 context.Response.StatusCode = 302;
                 context.Response.ReasonPhrase = "Found";
                 context.Response.Headers.Add("Location", new [] { "redirect" });
             }
         },
         { "/redirect-absolute-301", context =>
             {
                 context.Response.StatusCode = 301;
                 context.Response.ReasonPhrase = "Moved Permanently";
                 context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
             }
         },                
         { "/redirect-absolute-303", context =>
             {
                 context.Response.StatusCode = 303;
                 context.Response.ReasonPhrase = "See Other";
                 context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
             }
         },
         { "/redirect-absolute-307", context =>
             {
                 context.Response.StatusCode = 307;
                 context.Response.ReasonPhrase = "Temporary Redirect";
                 context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
             }
         },
         { "/redirect-loop", context =>
             {
                 context.Response.StatusCode = 302;
                 context.Response.ReasonPhrase = "Found";
                 context.Response.Headers.Add("Location", new[] { "http://localhost/redirect-loop" });
             }
         },
         { "/redirect", context => context.Response.StatusCode = 200 }
     };
     AppFunc appFunc = env =>
     {
         var context = new OwinContext(env);
         responders[context.Request.Path.Value](context);
         return Task.FromResult((object)null);
     };
     _handler = new OwinHttpMessageHandler(appFunc)
     {
         AllowAutoRedirect = true
     };
 }
示例#17
1
        public void InvokeMethod(string method, string param)
        {
            Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() {
            {"Select",()=>Select(param)}
            };

            dictMethod[method]();
        }
示例#18
1
        public void InvokeMethod(string method, string param)
        {
            Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() {
            {"ClickCell",()=>ClickCell(Convert.ToInt32(param.Split('|')[0]),Convert.ToInt32(param.Split('|')[1]),Convert.ToInt32(param.Split('|')[2]))}
            };

            dictMethod[method]();
        }
示例#19
1
 public static void UnitTest_Action()
 {
     Dictionary<short, Action> dic = new Dictionary<short, Action>();
     //short k = 0;
     //dic[k] = () => { Logger.Log("0"); };
     dic[(short)0] = () => { Logger.Log("0"); };
     dic[(short)0]();
 }
示例#20
1
        public void InvokeMethod(string method, string param)
        {
            Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() {
            {"Click",()=>Click()}
            };

            dictMethod[method]();
        }
示例#21
0
        public void InvokeMethod(string method, string param)
        {
            Dictionary<string, Action> dictMethod = new Dictionary<string, Action>() {
            {"Change",()=>Change(param=="0"?false:true)}
            };

            dictMethod[method]();
        }
示例#22
0
文件: N696.cs 项目: TinkerWorX/Bridge
        public static void TestUseCase()
        {
            var namedCallbacks = new Dictionary<string, Speak>();
            namedCallbacks.Add("Shout", message => message.Length);
            namedCallbacks.Add("Whisper", message => message.Length);

            Assert.AreEqual(namedCallbacks["Shout"]("HELLO!"), 6, "Bridge696 HELLO!");
            Assert.AreEqual(namedCallbacks["Whisper"]("HELLO"), 5, "Bridge696 HELLO");
        }
示例#23
0
fpv(Y a){try{
Action J=()=>{FormBorderStyle=(FormBorderStyle)(T=4-(X)(WindowState=2-WindowState)*2);BackColor=T!=0?Color.White:Color.Black;},j=()=>K("FPV by kasthack v 0.9.1.\r\nKeys:\r\nD/S/v/>/Num6/Num2/Space - next photo;\r\nA/W/^/</Num8/Num4 - previous photo;\r\nHome/H - first pic in folder\r\nEnd/E - last pic\r\nF11/Alt+Enter - fullscreen;\r\nEsc - exit fullscreen;\r\nEsc-Esc/Q - exit FPV;\r\nF1/?- show this message.","FPV:Help",0,64),k=()=>{if(K("Do U really want to delete"+G[B]+"?","Deleting",4,32)==6)try{File.Delete(G[B]);I(0);}catch{}},g=()=>A=true,h=()=>I(1),i=()=>I(-1),l=()=>I((B=0)-1),m=()=>I(B=0);
H=new Dictionary<X,Action>{{68,h},{83,h},{40,h},{39,h},{98,h},{102,h},{32,h},{65,i},{87,i},{38,i},{37,i},{104,i},{100,i},{36,m},{72,m},{35,l},{69,l},{112,j},{191,j},{46,k},{81,Application.Exit},{82,()=>I(E.Next())},{27,()=>H[(X)WindowState==2?122:81]()},{122,()=>H[-1]()},{13,()=>{if(!A)I(1);else H[-1]();}},{-1,J},{262144,g},{18,g},{111,j}};
Controls.Add(F=new PictureBox{BorderStyle=0});F.SizeMode+=4;F.Dock+=5;F.MouseDoubleClick+=(x,y)=>J();
KeyUp+=(_,e)=>A&=!((T=(X)e.KeyCode)==65||T==18);
KeyDown+=(c,b)=>{if(H.TryGetValue((X)b.KeyCode,out i))i();};
MouseWheel+=(_,e)=>I(e.Delta>0?-1:1);
G=Directory.GetFiles(D=(V=Path.GetDirectoryName(a))==""?".":V);}
catch{H[111]();T=9;return;}
B=Array.IndexOf(G,a);I(0);}}
示例#24
0
文件: gtest-280.cs 项目: nobled/mono
        public static void Main (string[] args) {
                Dictionary<string, TestDel> dict = new Dictionary<string,
TestDel> ();

                dict["a"] = delegate (int b) {
                        return b;
                };

                System.Console.WriteLine (dict["a"] (2));
        }
示例#25
0
 public static object Dispatch(StageParams config, Dictionary<string, StageAction> mapping)
 {
     string[] subMapping = config.map.Split(new char[] { ':' }, 2);
     
     config.map = subMapping[1];
     
     string key = subMapping[0];
     
     if (mapping.ContainsKey(key)) return mapping[key](config);
     
     throw new Exception("Unknow mapping key: " + key);
 }
示例#26
0
    private void CreateBrowser()
    {
        //Создаем массив обработчиков доступных для вызова из js
        handlers = new Dictionary<string, Action<NameValueCollection>>
        {
            { "callfromjs", nv => CallJs("showMessage", new object[] { nv["msg"] + " Ответ из С#" }) }
        };

        browser = new WebView ();

        browser.NavigationRequested += (sender, args) =>
        {
            var url = new Uri(args.Request.Uri);
            if (url.Scheme != "mp")
            {
                //mp - myprotocol.
                //Обрабатываем вызовы только нашего специального протокола.
                //Переходы по обычным ссылкам работают как и прежде
                return;
            }

            var parameters = System.Web.HttpUtility.ParseQueryString(url.Query);

            handlers[url.Host.ToLower()](parameters);

            //Отменяем переход по ссылке
            browser.StopLoading();
        };

        browser.LoadHtmlString (@"
                <html>
                    <head></head>
                    <body id=body>
                        <h1>Интерфейс</h1>
                        <button id=btn>Вызвать C#</button>
                        <p id=msg></p>

                        <script>
                            function buttonClick() {
                                window.location.href = 'mp://callFromJs?msg=Сообщение из js.';
                            }
                            function showMessage(msg) {
                                document.getElementById('msg').innerHTML = msg;
                            }

                            document.getElementById('btn').onclick = buttonClick;
                        </script>
                    </body>
                </html>
            ", null);

        this.Add (browser);
    }
示例#27
0
        public TileSet Load(char[,] level, Dictionary<char,Func<Point, Tile>> map)
        {
            var height = level.GetHeight() + 1;
            var width = level.GetWidth() + 1;

            var tileSet = from y in Enumerable.Range(0, height)
                          from x in Enumerable.Range(0, width)
                          let tiles = map[level[x, y]](new Point(x, y))
                          where tiles != null
                          select tiles;

            return new TileSet(tileSet);
        }
示例#28
0
 static void Main(string[] args)
 {
     // DO NOT TRY TO UNDERSTAND THIS CODE
     // THE TEACHER IS JUST SHOWING OFF
     Dictionary<Tuple<bool, bool>, Func<int, string>> dict = new Dictionary<Tuple<bool, bool>, Func<int, string>>
     {
         { Tuple.Create(false, false), i => i.ToString()},
         { Tuple.Create(true, false), _ => "Fizz"},
         { Tuple.Create(false, true), _ => "Buzz"},
         { Tuple.Create(true, true), _ => "FizzBuzz"}
     };
     Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(dict[Tuple.Create(i % 3 == 0, i % 5 == 0)](i)));
 }
        public ActionResult Show(string digits)
        {
            var selectedOption = digits;
            var optionActions = new Dictionary<string, Func<TwiMLResult>>()
            {
                {"1", ReturnInstructions},
                {"2", Planets}
            };

            return optionActions.ContainsKey(selectedOption) ?
                optionActions[selectedOption]() :
                RedirectWelcome();
        }
示例#30
0
        /// <summary></summary>
        public static string TransformText(string value, TextTransformationOption option)
        {
            if (value.Length > 0)
            {
                var dictionary = new Dictionary<TextTransformationOption, Func<string, string>>();
                dictionary.Add(TextTransformationOption.CamelCase, ToCamel);
                dictionary.Add(TextTransformationOption.PascalCase, ToPascal);
                dictionary.Add(TextTransformationOption.Underscored, ToUnderscored);

                value = dictionary[option](value);
            }

            return value;
        }
示例#31
0
        private static bool BuildWorkers(
            IEnumerable <string> workerTypes,
            BuildEnvironment buildEnvironment,
            IEnumerable <BuildTarget> buildTargetFilter = null,
            ScriptingImplementation?scriptingBackend    = null)
        {
            var activeBuildTarget      = EditorUserBuildSettings.activeBuildTarget;
            var activeBuildTargetGroup = BuildPipeline.GetBuildTargetGroup(activeBuildTarget);

            if (BuildConfig.GetInstance() == null)
            {
                const string errorMessage =
                    "Could not find an instance of the SpatialOS Build Configuration.\n\nPlease create one via Assets > Create > SpatialOS > SpatialOS Build Configuration.\n\nIf you already have an instance of the SpatialOS Build Configuration in your project, please open it in the Unity Inspector to force the asset to load and retry the build.";

                if (Application.isEditor)
                {
                    EditorApplication.delayCall += () =>
                    {
                        EditorUtility.DisplayDialog("Could not find SpatialOS Build Configuration",
                                                    errorMessage,
                                                    "OK");
                    };
                }

                Debug.LogError(errorMessage);
                return(false);
            }

            try
            {
                LocalLaunch.BuildConfig();

                var workerResults = new Dictionary <string, bool>();
                foreach (var wantedWorkerType in workerTypes)
                {
                    var result = BuildWorkerForEnvironment(wantedWorkerType, buildEnvironment, buildTargetFilter, scriptingBackend);
                    workerResults[wantedWorkerType] = result;
                }

                var missingWorkerTypes   = string.Join(" ", workerResults.Keys.Where(k => !workerResults[k]));
                var completedWorkerTypes = string.Join(" ", workerResults.Keys.Where(k => workerResults[k]));

                if (missingWorkerTypes.Length > 0)
                {
                    Debug.LogWarning(
                        $"Completed build for {buildEnvironment} target.\n"
                        + $"Completed builds for: {completedWorkerTypes}\n"
                        + $"Skipped builds for: {missingWorkerTypes}. See above for more information.");
                    return(false);
                }
                else
                {
                    Debug.Log($"Completed build for {buildEnvironment} target.");
                    return(true);
                }
            }
            catch (Exception e)
            {
                throw new BuildFailedException(e);
            }
            finally
            {
                EditorUserBuildSettings.SwitchActiveBuildTarget(activeBuildTargetGroup, activeBuildTarget);
            }
        }
示例#32
0
 public KatalogGier(SerializationInfo info, StreamingContext context)
 {
     slownikKatalogu = (Dictionary <string, string>)info.GetValue("slownik katalogu", typeof(Dictionary <string, string>));
 }
示例#33
0
 public JSONPatch(object model)
 {
     propsJson = JsonConvert.DeserializeObject <Dictionary <string, object> >(model.ToString());
 }
示例#34
0
 /// <summary>
 /// Creates a navigation resource expression
 /// </summary>
 /// <param name="type">the return type of the expression</param>
 /// <param name="source">the source expression</param>
 /// <param name="memberExpression">property member name</param>
 /// <param name="resourceType">the element type of the resource</param>
 /// <param name="expandPaths">expand paths for resource set</param>
 /// <param name="countOption">count query option for the resource</param>
 /// <param name="customQueryOptions">custom query options for resource</param>
 /// <param name="projection">the projection expression</param>
 /// <param name="resourceTypeAs">TypeAs type</param>
 /// <param name="uriVersion">version of the Uri from the expand and projection paths</param>
 internal QueryableResourceExpression(Type type, Expression source, Expression memberExpression, Type resourceType, List <string> expandPaths, CountOption countOption, Dictionary <ConstantExpression, ConstantExpression> customQueryOptions, ProjectionQueryOptionExpression projection, Type resourceTypeAs, Version uriVersion)
     : this(type, source, memberExpression, resourceType, expandPaths, countOption, customQueryOptions, projection, resourceTypeAs, uriVersion, null, null, null, false)
 {
 }
 /// <summary>
 /// For internal usage only. DO NOT USE IT.
 /// </summary>
 public override void ToMap(Dictionary <string, string> map, string prefix)
 {
     this.SetParamSimple(map, prefix + "VocabId", this.VocabId);
     this.SetParamSimple(map, prefix + "WordWeightStr", this.WordWeightStr);
     this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
 }
 public TipoLavorazione(int ID, string Descrizione)
 {
     this.Opzioni = null;
     this.ID = ID;
     this.Descrizione = Descrizione;
 }
示例#37
0
 public static Dictionary<string, By> ToLocators(this Dictionary<string, string> xpaths) =>
     xpaths.ToDictionary(p => p.Key, p => By.XPath(p.Value));
示例#38
0
        /// <summary>
        /// Load editor settings from a configuration file.
        /// </summary>
        /// <param name="documentType">The document type of the file being edited.</param>
        public void LoadSettings(DocumentType documentType)
        {
            string scintillaConfig = Path.Combine(
                applicationManager.QuickSharpHome,
                Constants.CONFIG_DIR_NAME);

            /*
             * Look for theme specific sub-folder.
             */

            string themePath = applicationManager.
                GetSelectedThemeProviderKey();

            if (!String.IsNullOrEmpty(themePath))
            {
                string themeConfig = Path.Combine(
                    scintillaConfig, themePath);

                if (Directory.Exists(themeConfig))
                    scintillaConfig = themeConfig;
            }

            /*
             * Update scintilla if the location exists.
             */
            
            if (Directory.Exists(scintillaConfig))
                scintilla.ConfigurationManager.CustomLocation =
                    scintillaConfig;

            /*
             * Apply any lexer aliases.
             */

            Dictionary<String, String> lexerAliasMap =
                documentManager.LexerAliasMap;

            foreach (string alias in lexerAliasMap.Keys)
                if (!scintilla.Lexing.LexerLanguageMap.ContainsKey(alias))
                    scintilla.Lexing.LexerLanguageMap.Add(
                        alias, lexerAliasMap[alias]);

            /*
             * Language will be requested language or default.
             */

            string language = documentManager.GetDocumentLanguage(documentType);
            scintilla.ConfigurationManager.Language = language;

            /*
             * Set config from external files and internal settings.
             */

            scintilla.ConfigurationManager.IsUserEnabled = true;
            scintilla.UseFont = false;

            if (_settingsManager.OverrideConfigFiles)
            { 
                // Line numbers
                scintilla.Margins.Margin0.Type = MarginType.Number;
                scintilla.Margins.Margin0.Width = _settingsManager.LineNumberMarginSize;
                
                // Bookmarks
                scintilla.NativeInterface.SendMessageDirect(
                    ScintillaNet.Constants.SCI_MARKERDEFINE,
                        Constants.BOOKMARK_MARKER,
                        ScintillaNet.Constants.SC_MARK_SMALLRECT);
                scintilla.NativeInterface.SendMessageDirect(
                    ScintillaNet.Constants.SCI_MARKERSETFORE,
                        Constants.BOOKMARK_MARKER, 0);
                scintilla.NativeInterface.SendMessageDirect(
                    ScintillaNet.Constants.SCI_MARKERSETBACK,
                    Constants.BOOKMARK_MARKER, GetColor(Color.LightGreen));

                scintilla.Margins.Margin1.Type = MarginType.Symbol;
                scintilla.Margins.Margin1.Width = 8;

                // Folding
                scintilla.Margins.Margin2.Type = MarginType.Symbol;
                scintilla.Margins.Margin2.Width = 16;

                // Not used
                scintilla.Margins.Margin3.Width = 0;
                scintilla.Margins.Margin3.Type = MarginType.Back;

                scintilla.Indentation.ShowGuides =
                    _settingsManager.ShowIndentationGuides;
                scintilla.Indentation.TabWidth = _settingsManager.TabSize;
                scintilla.Indentation.UseTabs = _settingsManager.UseTabs;
                scintilla.Indentation.BackspaceUnindents =
                    _settingsManager.BackspaceUnindents;

                scintilla.Folding.IsEnabled = _settingsManager.ShowFolding;
                scintilla.Folding.Flags = _settingsManager.Flags;
                scintilla.Folding.MarkerScheme = _settingsManager.MarkerScheme;

                string fontName = Fonts.ValidateFontName(_settingsManager.FontName);
                float fontSize = Fonts.ValidateFontSize(_settingsManager.FontSize);
                scintilla.Font = new Font(fontName, fontSize);
                scintilla.UseFont = true;
            }

            /*
             * Global settings (not covered by config files)
             */

            scintilla.IsBraceMatching = _settingsManager.MatchBraces;
            scintilla.LineWrap.Mode = _settingsManager.WordWrap
                ? WrapMode.Word : WrapMode.None;

            scintilla.Printing.PageSettings.ColorMode = 
                _settingsManager.PrintingColorMode;
        }
示例#39
0
 public PowerGame()
 {
     Entities     = new Dictionary <int, PowerEntity>();
     PowerHistory = new Queue <PowerHistoryEntry>();
 }
        private void ExportQRCodes(object sender, EventArgs e)
        {
            SaveFile SAV     = C_SAV.SAV;
            var      boxdata = SAV.BoxData;

            if (boxdata == null)
            {
                WinFormsUtil.Alert("Box Data is null");
            }
            int ctr = 0;
            Dictionary <string, Image> qrcodes = new Dictionary <string, Image>();

            foreach (PKM pk in boxdata)
            {
                if (pk.Species == 0 || !pk.Valid || (pk.Box - 1) != C_SAV.Box.CurrentBox)
                {
                    continue;
                }
                ctr++;
                Image qr;
                switch (pk.Format)
                {
                case 7:
                    qr = QR.GenerateQRCode7((PK7)pk);
                    break;

                default:
                    if (pk.Format == 6 && !QR6Notified)     // users should not be using QR6 injection
                    {
                        WinFormsUtil.Alert(MsgQRDeprecated, MsgQRAlternative);
                        QR6Notified = true;
                    }
                    qr = QR.GetQRImage(pk.EncryptedBoxData, QR.GetQRServer(pk.Format));
                    break;
                }
                if (qr == null)
                {
                    continue;
                }
                var sprite = dragout.Image;
                var la     = new LegalityAnalysis(pk, C_SAV.SAV.Personal);
                if (la.Parsed && pk.Species != 0)
                {
                    var img = la.Valid ? Resources.valid : Resources.warn;
                    sprite = ImageUtil.LayerImage(sprite, img, 24, 0, 1);
                }
                string[] r     = pk.QRText;
                string   refer = "PKHeX Auto Legality Mod";
                qrcodes.Add(Util.CleanFileName(pk.FileName), RefreshImage(qr, sprite, r[0], r[1], r[2], $"{refer} ({pk.GetType().Name})"));
            }
            if (!Directory.Exists(Path.Combine(WorkingDirectory, "qrcodes")))
            {
                Directory.CreateDirectory(Path.Combine(WorkingDirectory, "qrcodes"));
            }
            int counter = 0;

            foreach (KeyValuePair <string, Image> qrcode in qrcodes)
            {
                Console.WriteLine(counter);
                counter++;
                qrcode.Value.Save(Path.Combine(WorkingDirectory, "qrcodes", qrcode.Key + ".png"));
            }
        }
示例#41
0
 public void LoadPriceHistory(CurrencyPairOption currencyPair, Dictionary <DateTime, BarItem> priceBars)
 {
     throw new NotImplementedException();
 }
示例#42
0
 public override IEnumerator DoAction(Dictionary<Condition, object> npcState)
 {
     base.DoAction(npcState);
     yield return CreateSword();
 }
示例#43
0
 public PageElements(IWebDriver driver, Dictionary<string, string> xpaths):
     this(driver, xpaths.ToLocators())
 {}
 public TipoLavorazione()
 {
     this.Opzioni = new Dictionary<int, string>();
 }
示例#45
0
 public PageElements(IWebDriver driver, Dictionary<string, By> locators)
 {
     this.driver = driver;
     this.locators = locators;
 }
示例#46
0
        /*
         * overidden method to access saveMap, which contains all the entities that will be saved
         * saveMap allows you to modifed & pass new entites back to the front-end
         *
         * if you query it from the session, you must include it in saveMap back to the client
         * the UI will update automatically
         */
        private void AfterSaveEntities(Dictionary <Type, List <EntityInfo> > saveMap, List <KeyMapping> keyMappings)
        {
            var requestToChange = saveMap
                                  .Where(p => p.Key.IsAssignableFrom(typeof(Request)))
                                  .Select(p => p.Value)
                                  .FirstOrDefault();
            var smToChange = saveMap
                             .Where(p => p.Key.IsAssignableFrom(typeof(SourceMaterial)))
                             .Select(p => p.Value.Where(x => x.EntityState == EntityState.Added).ToList())
                             .FirstOrDefault();

            if (requestToChange != null)
            {
                var rq = ((Request)requestToChange.First().Entity);
                if (rq.RequestTemplateId != null)
                {
                    bool selectedTemplateChangedValue = false;
                    var  selectedTemplateChanged      = requestToChange.First().UnmappedValuesMap.SingleOrDefault(x => x.Key == "SelectedTemplateChanged");
                    // only if true, if false or null don't create jobs
                    if (!string.IsNullOrEmpty(selectedTemplateChanged.Key) && (bool.TryParse(selectedTemplateChanged.Value.ToString(), out selectedTemplateChangedValue) && selectedTemplateChangedValue))
                    {
                        _requestBL.CreateJobsBasedOnRequestTemplate(rq);
                        var sms = Session.Query <SourceMaterial>().Where(x => x.RequestId == rq.Id).Where(x => !x.Jobs.Any()).ToList();
                        foreach (var sm in sms)
                        {
                            if (!CheckForObjectTypeInSaveMap(sm, saveMap))
                            {
                                sm.UpdateDate = DateTime.UtcNow;
                                saveMap.AddCustomEntity <SourceMaterial>(sm, this);
                            }
                        }
                    }
                }
            }
            else if (smToChange != null && smToChange.Count > 0)
            {
                var rq = Session.Query <Request>().SingleOrDefault(x => x.Id == ((SourceMaterial)smToChange.First().Entity).RequestId);

                if (rq.RequestTemplateId != null)
                {
                    _requestBL.CreateJobsBasedOnRequestTemplate(rq);
                }
            }

            // upload file to filemanagement service when a new file is saved
            var physicalFiles = saveMap
                                .Where(p => p.Key.IsAssignableFrom(typeof(PhysicalFile)))
                                .Select(p => p.Value)
                                .FirstOrDefault();

            if (physicalFiles != null)
            {
                foreach (var physicalFile in physicalFiles)
                {
                    if (physicalFile.EntityState == EntityState.Added)
                    {
                        // see TFS 11203
                        var file = Session.Load <PhysicalFile>(((PhysicalFile)physicalFile.Entity).Id);

                        // call external storage service
                        StoreFileResponse resp = null;
                        Helper.UseWcfService <IFileManagement>("FileManagement", null, null, p =>
                        {
                            try
                            {
                                // Copying from a physical file (case we use a template with references they must be cloned)
                                if (file.ExternalStorageFileId == null)
                                {
                                    var filePath = Path.Combine(ConfigurationManager.AppSettings["UploadFolder"], file.PhysicalPath);
                                    // Reads data from the client temp folder
                                    var fileBytes = File.ReadAllBytes(filePath);
                                    resp          = p.StoreFile(new StoreFileRequest()
                                    {
                                        FileData  = fileBytes,
                                        FileName  = file.FileName,
                                        Anonymize = true
                                    });
                                    // check embedded only if it's a sourcematerial
                                    if (file.MaterialClassification.Code != "CREF" && new EmbeddedFileBL().IsEmbedded(filePath, file.FileName))
                                    {
                                        file.IsEmbedded = true;
                                    }
                                }
                                else
                                {
                                    resp = p.CloneFile(new CloneFileRequest()
                                    {
                                        ExternalStorageFileId = file.ExternalStorageFileId.Value, FileName = file.FileName
                                    });
                                }
                            }
                            catch (FaultException <FileIOFault> ex)
                            {
                                if (ex.Detail.FaultType == FileIOFault.FaultTypes.UnableToStoreError)
                                {
                                    // Display an error if an upload issue happened
                                    // find temp key in keymappings
                                    var tempKey     = keyMappings.Where(key => (Guid)key.RealValue == file.Id).Select(key => key.TempValue);
                                    var entityError = new EntityError
                                    {
                                        ErrorName      = "Store file",
                                        ErrorMessage   = ex.Detail.ErrorMessage,
                                        EntityTypeName = file.GetType().FullName,
                                        PropertyName   = "FileName",
                                        KeyValues      = tempKey.ToArray()
                                    };
                                    throw new EntityErrorsException("Error saving file", new List <EntityError>()
                                    {
                                        entityError
                                    });
                                }
                            }
                        });
                        file.ExternalStorageFileId = resp.FileId;
                        Session.Save(file);
                    }
                }
            }

            var entityInfos = saveMap
                              .Where(p => p.Key.IsAssignableFrom(typeof(Request)))
                              .Select(p => p.Value)
                              .FirstOrDefault();

            if (entityInfos != null)
            {
                foreach (var entityInfo in entityInfos)
                {
                    // initialize workflow or send email only if the status of the request has changed
                    if (entityInfo.OriginalValuesMap.ContainsKey("StatusId"))
                    {
                        Request request = (Request)entityInfo.Entity;
                        if (request.Status.Code == "MTS" && request.RequestType.Code == "RST001")
                        {
                            this.SendMarkedToSendEmail(request);
                        }

                        Status oldStatus = Session.Query <Status>().First(x => x.Id == Guid.Parse(entityInfo.OriginalValuesMap["StatusId"].ToString()));

                        if (request.Status.Code == "DRAF" && request.RequestType.Code == "RST001" && oldStatus.Code == Status.Codes.MTS)
                        {
                            this.SendBackToDraftEmail(request);
                        }

                        if (request.Status.Code == "NEW" && request.RequestType.Code == "RST003")
                        {
                            WorkflowInitializer.Initialize(request, "AsaDefaultFlow", this.Session);
                        }
                        else if (request.Status.Code == "NEW" && request.RequestType.Code == "RST001")
                        {
                            WorkflowInitializer.Initialize(request, "EcdtDefaultFlow", this.Session);
                        }
                    }
                }
            }

            AfterSaveSourceMaterial(saveMap);
            AfterSaveJob(saveMap);


            Session.Flush();
        }
示例#47
0
        /// <summary>
        /// Creates a navigation resource expression
        /// </summary>
        /// <param name="type">the return type of the expression</param>
        /// <param name="source">the source expression</param>
        /// <param name="memberExpression">property member name</param>
        /// <param name="resourceType">the element type of the resource</param>
        /// <param name="expandPaths">expand paths for resource set</param>
        /// <param name="countOption">count query option for the resource</param>
        /// <param name="customQueryOptions">custom query options for resource</param>
        /// <param name="projection">the projection expression</param>
        /// <param name="resourceTypeAs">TypeAs type</param>
        /// <param name="uriVersion">version of the Uri from the expand and projection paths</param>
        /// <param name="operationName">name of function</param>
        /// <param name="operationParameters">parameters' names and values of function</param>
        /// <param name="operationReturnType">return type of function</param>
        /// <param name="isAction">action flag</param>
        internal QueryableResourceExpression(Type type, Expression source, Expression memberExpression, Type resourceType, List <string> expandPaths, CountOption countOption, Dictionary <ConstantExpression, ConstantExpression> customQueryOptions, ProjectionQueryOptionExpression projection, Type resourceTypeAs, Version uriVersion, string operationName, Dictionary <string, string> operationParameters, Type operationReturnType, bool isAction)
            : base(source, type, expandPaths, countOption, customQueryOptions, projection, resourceTypeAs, uriVersion, operationName, operationParameters, operationReturnType, isAction)
        {
            Debug.Assert(type != null, "type != null");
            Debug.Assert(resourceType != null, "resourceType != null");
            Debug.Assert(
                (source == null && memberExpression is ConstantExpression) ||
                (source != null && memberExpression is MemberExpression) ||
                (memberExpression == null),
                "source is null with constant entity set name, or not null with member expression, or memberExpression is null for function import.");

            this.member                = memberExpression;
            this.resourceType          = resourceType;
            this.sequenceQueryOptions  = new List <QueryOptionExpression>();
            this.keyPredicateConjuncts = new List <Expression>();
        }
示例#48
0
        private Dictionary <Type, List <EntityInfo> > BeforeSaveEntities(Dictionary <Type, List <EntityInfo> > saveMap)
        {
            #region JobPricing
            List <EntityInfo> entityInfos = saveMap.Where(e => e.Key == typeof(JobPricing)).Select(e => e.Value).FirstOrDefault();
            if (entityInfos != null)
            {
                foreach (EntityInfo entityInfo in entityInfos)
                {
                    JobPricing jobPricing = (JobPricing)(entityInfo.Entity);

                    // single query without lazy loading
                    var temp = (from p in Session.Query <JobTranslation>()
                                where p.Id == jobPricing.JobId
                                select new { JobTranslation = p, p.SourceMaterial.Request }).FirstOrDefault();

                    if (temp != null)
                    {
                        if (!CheckForObjectTypeInSaveMap(temp.JobTranslation, saveMap))
                        {
                            temp.JobTranslation.UpdateDate = DateTime.UtcNow;
                            saveMap.AddCustomEntity(temp.JobTranslation, this);
                        }

                        if (!saveMap.Any(e => e.Key == typeof(Request)))
                        {
                            temp.Request.UpdateDate = DateTime.UtcNow;
                            saveMap.AddCustomEntity(temp.Request, this);
                        }
                    }
                }
            }
            #endregion

            #region JobMaterial
            entityInfos = saveMap.Where(e => e.Key == typeof(JobMaterial)).Select(e => e.Value).FirstOrDefault();
            if (entityInfos != null)
            {
                foreach (EntityInfo entityInfo in entityInfos)
                {
                    JobMaterial jobMaterial = (JobMaterial)(entityInfo.Entity);

                    if (!saveMap.Any(e => e.Key.IsSubclassOf(typeof(Job)) && e.Value.Any(f => ((Job)f.Entity).Id == jobMaterial.JobId)))
                    {
                        // single query without lazy loading
                        var temp = (from p in Session.Query <Job>()
                                    where p.Id == jobMaterial.JobId
                                    select new { Job = p, Request = p.SourceMaterial.Request }).FirstOrDefault();

                        if (temp != null)
                        {
                            temp.Job.UpdateDate = DateTime.UtcNow;
                            saveMap.AddCustomEntity(temp.Job, this);

                            if (!saveMap.Any(e => e.Key == typeof(Request)))
                            {
                                temp.Request.UpdateDate = DateTime.UtcNow;
                                saveMap.AddCustomEntity(temp.Request, this);
                            }
                        }
                    }
                }
            }
            #endregion

            #region Reference
            entityInfos = saveMap.Where(e => e.Key == typeof(Reference)).Select(e => e.Value).FirstOrDefault();
            if (entityInfos != null)
            {
                foreach (EntityInfo entityInfo in entityInfos)
                {
                    Reference reference = (Reference)(entityInfo.Entity);
                    Request   request   = saveMap.Where(e => e.Key == typeof(Request)).SelectMany(e => e.Value).Select(c => (Request)c.Entity).FirstOrDefault();

                    if (request != null)
                    {
                        request.UpdateDate = DateTime.UtcNow;
                    }
                    else
                    {
                        // single query without lazy loading
                        request = (from p in Session.Query <Request>()
                                   where p.ReferenceSet.Id == reference.ReferenceSetId
                                   select p).FirstOrDefault();
                        if (request != null)
                        {
                            request.UpdateDate = DateTime.UtcNow;
                            saveMap.AddCustomEntity(request, this);
                        }
                    }
                }
            }
            #endregion

            #region JobComment
            entityInfos = saveMap.Where(e => e.Key == typeof(JobComment)).Select(e => e.Value).FirstOrDefault();
            if (entityInfos != null)
            {
                foreach (EntityInfo entityInfo in entityInfos)
                {
                    JobComment jobComment = (JobComment)(entityInfo.Entity);

                    // single query without lazy loading
                    var temp = (from p in Session.Query <Job>()
                                where p.Id == jobComment.JobId
                                select new { Job = p, Request = p.SourceMaterial.Request }).First();

                    temp.Job.UpdateDate = DateTime.UtcNow;
                    saveMap.AddCustomEntity(temp.Job, this);

                    if (!saveMap.Any(e => e.Key == typeof(Request)))
                    {
                        temp.Request.UpdateDate = DateTime.UtcNow;
                        saveMap.AddCustomEntity(temp.Request, this);
                    }
                }
            }
            #endregion

            #region Job
            entityInfos = saveMap.Where(e => e.Key.IsSubclassOf(typeof(Job))).Select(e => e.Value).FirstOrDefault();
            if (entityInfos != null)
            {
                foreach (EntityInfo entityInfo in entityInfos)
                {
                    if (!saveMap.Any(e => e.Key == typeof(Request)))
                    {
                        Request request = GetQuery <SourceMaterial>().Where(e => e.Id == ((Job)entityInfo.Entity).SourceMaterialId).Select(e => e.Request).FirstOrDefault();
                        if (request == null)
                        {
                            Guid?requestId = saveMap.Where(e => e.Key == typeof(SourceMaterial))
                                             .SelectMany(e => e.Value)
                                             .Select(x => (SourceMaterial)x.Entity)
                                             .Where(x => x.Id == ((Job)entityInfo.Entity).SourceMaterialId)
                                             .Select(x => x.RequestId)
                                             .SingleOrDefault();

                            if (requestId.HasValue)
                            {
                                request = GetQuery <Request>().FirstOrDefault(e => e.Id == requestId);
                            }
                        }
                        saveMap.AddCustomEntity(request, this);
                    }
                }
            }
            #endregion

            #region Material
            entityInfos = saveMap.Where(e => e.Key == typeof(Material) || e.Key.IsSubclassOf(typeof(Material))).Select(e => e.Value).FirstOrDefault();
            if (entityInfos != null)
            {
                // Update 'UploadedBy' field only for new entities
                foreach (EntityInfo entityInfo in entityInfos.Where(e => e.EntityState == EntityState.Added))
                {
                    Material material = (Material)entityInfo.Entity;
                    if (string.IsNullOrEmpty(material.UploadedBy))
                    {
                        material.UploadedBy = material.CreatedBy;
                    }
                    if (!material.UploaderType.HasValue)
                    {
                        material.UploaderType = UploaderType.Other;
                    }
                }
            }
            #endregion

            var tmp = saveMap.Where(p => p.Key.IsSubclassOf(typeof(Job)))
                      .Select(p => p.Value.Where(x => x.EntityState == EntityState.Deleted).ToList())
                      .FirstOrDefault();
            var jobs = tmp == null ? null : tmp.Select(x => (Job)x.Entity).ToList();

            var requestToChange = saveMap
                                  .Where(p => p.Key.IsAssignableFrom(typeof(Request)))
                                  .Select(p => p.Value)
                                  .FirstOrDefault();
            var smToChange = saveMap
                             .Where(p => p.Key.IsAssignableFrom(typeof(SourceMaterial)))
                             .Select(p => p.Value.Where(x => x.EntityState == EntityState.Added).ToList())
                             .FirstOrDefault();

            if (requestToChange != null)
            {
                var rq = ((Request)requestToChange.First().Entity);
                List <SourceMaterial> sms = new List <SourceMaterial>();
                sms = Session.Query <SourceMaterial>().Where(x => x.RequestId == rq.Id).Where(x => !x.Jobs.Any()).Distinct().ToList();
                if (jobs != null)
                {
                    foreach (var job in jobs)
                    {
                        sms.AddRange(Session.Query <SourceMaterial>().Where(x => x.RequestId == rq.Id).Where(v => v.Jobs.Contains(job)).Distinct().ToList());
                    }
                }

                if (rq.RequestTemplateId != null)
                {
                    foreach (var sm in sms)
                    {
                        if (!CheckForObjectTypeInSaveMap(sm, saveMap))
                        {
                            sm.UpdateDate = DateTime.UtcNow;
                            saveMap.AddCustomEntity <SourceMaterial>(sm, this);
                        }
                    }
                }
            }

            Session.Clear();
            return(saveMap);
        }
示例#49
0
        /// <summary>
        /// Creates a navigation resource expression
        /// </summary>
        /// <param name="expressionType">The expression type.</param>
        /// <param name="type">the return type of the expression</param>
        /// <param name="source">the source expression</param>
        /// <param name="memberExpression">property member name</param>
        /// <param name="resourceType">the element type of the resource</param>
        /// <param name="expandPaths">expand paths for resource set</param>
        /// <param name="countOption">count query option for the resource</param>
        /// <param name="customQueryOptions">custom query options for resource</param>
        /// <param name="projection">the projection expression</param>
        /// <param name="resourceTypeAs">TypeAs type</param>
        /// <param name="uriVersion">version of the Uri from the expand and projection paths</param>
        /// <returns>The navigation resource expression.</returns>
        internal static QueryableResourceExpression CreateNavigationResourceExpression(ExpressionType expressionType, Type type, Expression source, Expression memberExpression, Type resourceType, List <string> expandPaths, CountOption countOption, Dictionary <ConstantExpression, ConstantExpression> customQueryOptions, ProjectionQueryOptionExpression projection, Type resourceTypeAs, Version uriVersion)
        {
            Debug.Assert(
                expressionType == (ExpressionType)ResourceExpressionType.RootResourceSet || expressionType == (ExpressionType)ResourceExpressionType.ResourceNavigationProperty || expressionType == (ExpressionType)ResourceExpressionType.RootSingleResource,
                "Expression type is not one of following: RootResourceSet, ResourceNavigationProperty, RootSingleResource.");

            if (expressionType == (ExpressionType)ResourceExpressionType.RootResourceSet || expressionType == (ExpressionType)ResourceExpressionType.ResourceNavigationProperty)
            {
                return(new ResourceSetExpression(type, source, memberExpression, resourceType, expandPaths, countOption, customQueryOptions, projection, resourceTypeAs, uriVersion));
            }

            if (expressionType == (ExpressionType)ResourceExpressionType.RootSingleResource)
            {
                return(new SingletonResourceExpression(type, source, memberExpression, resourceType, expandPaths, countOption, customQueryOptions, projection, resourceTypeAs, uriVersion));
            }

            return(null);
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var orderTotal    = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
            var testMode      = _payGatePaymentSettings.TestMode;
            var encryptionKey = "";
            var initiated     = false;

            using (var client = new WebClient())
            {
                var initiateData = new NameValueCollection();
                if (testMode)
                {
                    initiateData["PAYGATE_ID"] = "10011072130";
                    encryptionKey = "secret";
                    this.defaultLogger.Information("Using test mode");
                }
                else
                {
                    initiateData["PAYGATE_ID"] = _payGatePaymentSettings.PayGateID;
                    encryptionKey = _payGatePaymentSettings.EncryptionKey;
                }
                initiateData["REFERENCE"] = postProcessPaymentRequest.Order.Id.ToString();
                initiateData["AMOUNT"]    = (Convert.ToDouble(orderTotal) * 100).ToString();
                initiateData["CURRENCY"]  = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                var storeLocation = _webHelper.GetStoreLocation(false);
                if (_payGatePaymentSettings.UseSSL)
                {
                    storeLocation = storeLocation.Replace("http://", "https://");
                }
                initiateData["RETURN_URL"]       = storeLocation + "Plugins/PaymentPayGate/PayGateReturnHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                initiateData["TRANSACTION_DATE"] = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now).ToString();
                initiateData["LOCALE"]           = "en-za";
                initiateData["COUNTRY"]          = postProcessPaymentRequest.Order.BillingAddress.Country.ThreeLetterIsoCode;
                initiateData["EMAIL"]            = postProcessPaymentRequest.Order.BillingAddress.Email;
                if (_payGatePaymentSettings.EnableIpn)
                {
                    initiateData["NOTIFY_URL"] = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayGate/PayGateNotifyHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                }
                initiateData["USER1"] = postProcessPaymentRequest.Order.Id.ToString();
                initiateData["USER3"] = "nopcommerce-v4.2.0";

                string initiateValues = string.Join("", initiateData.AllKeys.Select(key => initiateData[key]));

                initiateData["CHECKSUM"] = new PayGateHelper().CalculateMD5Hash(initiateValues + encryptionKey);

                var    cnt = 0;
                byte[] initiateResponse;
                while (!initiated && cnt < 5)
                {
                    initiateResponse = client.UploadValues("https://secure.paygate.co.za/payweb3/initiate.trans", "POST", initiateData);
                    var str = Encoding.UTF8.GetString(initiateResponse);
                    this.defaultLogger.Information("Initiate response: " + Encoding.UTF8.GetString(initiateResponse) + " cnt=" + cnt);
                    dictionaryResponse = Encoding.Default.GetString(initiateResponse)
                                         .Split('&')
                                         .Select(p => p.Split('='))
                                         .ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);
                    if (dictionaryResponse.Count == 4 && dictionaryResponse.ContainsKey("PAY_REQUEST_ID"))
                    {
                        this.defaultLogger.Information("PAYGATE_ID = " + dictionaryResponse["PAYGATE_ID"]);
                        this.defaultLogger.Information("PAY_REQUEST_ID = " + dictionaryResponse["PAY_REQUEST_ID"]);
                        this.defaultLogger.Information("REFERENCE = " + dictionaryResponse["REFERENCE"]);
                        this.defaultLogger.Information("CHECKSUM = " + dictionaryResponse["CHECKSUM"]);
                        initiated = true;
                    }
                    cnt++;
                }

                // Redirect to payment portal
                if (initiated)
                {
                    _webHelper.IsPostBeingDone = true;
                    try
                    {
                        this.defaultLogger.Information("Is initiated");
                        var sb           = new StringBuilder();
                        var Url          = "https://secure.paygate.co.za/payweb3/process.trans";
                        var payRequestId = dictionaryResponse["PAY_REQUEST_ID"];
                        var checksum     = dictionaryResponse["CHECKSUM"];
                        sb.Append("<html><head></head>");
                        sb.Append("<body>");
                        sb.Append("<form id=\"PayGate_Form\" method=\"post\" action=\"" + Url + "\" >");
                        sb.Append("<input type=\"hidden\" name=\"PAY_REQUEST_ID\" value=\"" + payRequestId + "\" >");
                        sb.Append("<input type=\"hidden\" name=\"CHECKSUM\" value=\"" + checksum + "\" >");
                        sb.Append("<script>document.getElementById('PayGate_Form').submit();</script>");
                        sb.Append("</form></body></html>");

                        var response = _httpContextAccessor.HttpContext.Response;
                        var data     = Encoding.UTF8.GetBytes(sb.ToString());
                        response.ContentType   = "text/html; charset=utf-8";
                        response.ContentLength = data.Length;
                        response.Body.Write(data, 0, data.Length);
                        response.Body.Flush();
                        response.Body.Close();
                    }
                    catch (Exception e)
                    {
                        this.defaultLogger.Error("Failed to POST: " + e.Message);
                    }
                }
                else
                {
                    this.defaultLogger.Error("Failed to get initiate response from Paygate after 5 attempts");
                }
            }
        }
示例#51
0
 private bool CheckForObjectTypeInSaveMap <T>(T value, Dictionary <Type, List <EntityInfo> > saveMap) where T : BaseEntity
 {
     return(saveMap.Any(x => x.Key == typeof(T) && x.Value.Any(y => ((T)y.Entity).Id == value.Id)));
 }
        public override async Task ExecuteAsync()
        {
            var accessToken = await GetAccessTokenAsync();

            // Get all the accounts entries
            const string accountsUrl = "https://api.aweber.com/1.0/accounts";
            var accounts = await GetCollectionAsync<Account>(accessToken, accountsUrl);
            var accountUrl = accounts.First().SelfLink;

            // Get all the list entries for the first account
            var listsUrl = accounts.First().ListsCollectionLink;
            var lists = await GetCollectionAsync<List>(accessToken, listsUrl);

            // Find out if a subscriber exists on the first list
            var email = "*****@*****.**";
            var subscriberParams = new Dictionary<string, string>
            {
                {"email", email},
                {"ws.op", "find"}
            };
            var subscribersUrl = lists.First().SubscribersCollectionLink;
            var findUrl = string.Format("{0}?{1}", subscribersUrl, subscriberParams.ToUrlParams());
            var foundSubscribers = await GetCollectionAsync<Subscriber>(accessToken, findUrl);
            Console.WriteJson("Found subscribers", foundSubscribers);

            var subscriber = foundSubscribers.FirstOrDefault();
            string subscriberUrl;
            if (subscriber?.SelfLink != null)
            {
                // update subscriber if they are on the first list
                var updateSubscriber = new UpdateSubscriber
                {
                    CustomFields = new Dictionary<string, string> {{"awesomeness", "really awesome"}},
                    Tags = new Dictionary<string, IList<string>> {{"add", new List<string> {"prospect"}}},
                    Status = "subscribed"
                };
                subscriberUrl = subscriber.SelfLink;
                subscriber = await UpdateAsync<UpdateSubscriber, Subscriber>(updateSubscriber, accessToken, subscriberUrl);
                Console.WriteJson("Updated Subscriber", subscriber);
            }
            else
            {
                // add the subscriber if they are not already on the first list
                var addSubscriber = new AddSubscriber
                {
                    Email = email,
                    CustomFields = new Dictionary<string, string> {{"awesomeness", "somewhat"}},
                    Tags = new List<string> {"prospect"}
                };
                subscriberUrl = (await CreateAsync(addSubscriber, accessToken, subscribersUrl)).AbsoluteUri;
                subscriber = await GetAsync<Subscriber>(accessToken, subscriberUrl);
                Console.WriteJson("Created Subscriber", subscriber);
            }

            // get the activity for the subscriber
            var activityParams = new Dictionary<string, string>
            {
                {"ws.op", "getActivity"}
            };
            var activityUrl = string.Format("{0}?{1}", subscriberUrl, activityParams.ToUrlParams());
            var activity = await GetAsync<Activity>(accessToken, activityUrl);
            Console.WriteJson("Subscriber Activity", activity);

            // delete the subscriber; this can only be performed on confirmed subscribers
            // or a 405 Method Not Allowed will be returned
            if (subscriber.Status == "subscribed")
            {
                await DeleteAsync(accessToken, subscriberUrl);
                Console.WriteResponse(ConsoleColor.Green, "Deleted subscriber with email: {0}", email);
            }
        }
示例#53
0
        /// <summary>
        /// Gets the list of annotations for a component for given time range
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group. The name is case insensitive.
        /// </param>
        /// <param name='resourceName'>
        /// The name of the Application Insights component resource.
        /// </param>
        /// <param name='start'>
        /// The start time to query from for annotations, cannot be older than 90 days
        /// from current date.
        /// </param>
        /// <param name='end'>
        /// The end time to query for annotations.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="AnnotationErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <IEnumerable <Annotation> > > ListWithHttpMessagesAsync(string resourceGroupName, string resourceName, string start, string end, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (resourceGroupName.Length > 90)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
                }
                if (resourceGroupName.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
                }
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (Client.SubscriptionId != null)
            {
                if (Client.SubscriptionId.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1);
                }
            }
            if (resourceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceName");
            }
            if (start == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "start");
            }
            if (end == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "end");
            }
            string apiVersion = "2015-05-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("resourceName", resourceName);
                tracingParameters.Add("start", start);
                tracingParameters.Add("end", end);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/Annotations").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (start != null)
            {
                _queryParameters.Add(string.Format("start={0}", System.Uri.EscapeDataString(start)));
            }
            if (end != null)
            {
                _queryParameters.Add(string.Format("end={0}", System.Uri.EscapeDataString(end)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new AnnotationErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    AnnotationError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <AnnotationError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <IEnumerable <Annotation> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page1 <Annotation> >(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#54
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="obj">The object.</param>
 /// <param name="errors">The errors.</param>
 public ValidateHelper(T obj, Dictionary <string, string> errors)
 {
     RegisterEvent(obj);
     Register(errors);
 }
示例#55
0
        /// <summary>Create instance of MANIFEST.MF file reader</summary>
        /// <param name="payload">MANIFEST.MF file contents</param>
        public MfFile(Byte[] payload)
        {
            if (payload == null || payload.Length == 0)
            {
                throw new ArgumentNullException("payload");
            }


            String[] lines = Encoding.UTF8.GetString(payload).Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            this._fileHash = new Dictionary <String, HashWithType>();
            for (Int32 loop = 0; loop < lines.Length; loop++)
            {
                String line = lines[loop];
                String key, value;
                if (!MfFile.SplitToKeyValue(lines[loop], out key, out value))
                {
                    continue;
                }

                switch (key)
                {
                case "Manifest-Version":
                    this._version = value;
                    break;

                case "Built-By":
                    this._builtBy = value;
                    break;

                case "Created-By":
                    this._createdBy = value;
                    break;

                case "Name":
                    loop++;
                    String  key1, value1;
                    Boolean isSplitted = MfFile.SplitToKeyValue(lines[loop], out key1, out value1);
                    if (!isSplitted)
                    {
                        if (lines[loop - 1].Length == 70)
                        {                        //Если строка больше 70 символов, то содержимое переносится на следующую строку
                            value     += lines[loop].Trim();
                            isSplitted = MfFile.SplitToKeyValue(lines[loop + 1], out key1, out value1);
                            if (isSplitted)
                            {
                                loop++;
                            }
                        }
                        if (!isSplitted)
                        {
                            continue;
                        }
                    }

                    switch (key1)
                    {
                    case "SHA-256-Digest":
                        this._fileHash.Add(value, new HashWithType()
                        {
                            Type = HashType.Sha256, Hash = value1,
                        });
                        break;

                    case "SHA1-Digest":
                        this._fileHash.Add(value, new HashWithType()
                        {
                            Type = HashType.Sha1, Hash = value1,
                        });
                        break;
                    }
                    break;
                }
            }
        }
示例#56
0
 /// <summary>
 /// 如果是IDataErrorInfo接口,注册错误字典
 /// </summary>
 /// <param name="dataErrors">错误字典</param>
 /// <returns>ValidateHelper{`0}.</returns>
 public ValidateHelper <T> Register(Dictionary <string, string> dataErrors)
 {
     dErrors = dataErrors;
     return(this);
 }
示例#57
0
 /// <summary>
 /// Instantiates a new MessageRuleItemRequestBuilderPatchRequestConfiguration and sets the default values.
 /// </summary>
 public MessageRuleItemRequestBuilderPatchRequestConfiguration()
 {
     Options = new List <IRequestOption>();
     Headers = new Dictionary <string, string>();
 }
示例#58
0
 /// <summary>
 /// For internal usage only. DO NOT USE IT.
 /// </summary>
 internal override void ToMap(Dictionary <string, string> map, string prefix)
 {
     this.SetParamSimple(map, prefix + "MerchantId", this.MerchantId);
     this.SetParamSimple(map, prefix + "TransactionId", this.TransactionId);
     this.SetParamSimple(map, prefix + "Status", this.Status);
 }
        private void btnCollectDirectory_Click(object sender, EventArgs e)
        {
            //Get the DictFile
            string[] reads = File.ReadAllLines(tbPicPath.Text + "\\Translate.txt");
            Dictionary <string, string> mapName = new Dictionary <string, string>();

            foreach (string r in reads)
            {
                string[] ss = r.Split('|');
                mapName[ss[0]] = ss[1];
            }

            DirectoryInfo info = new DirectoryInfo(tbPicPath.Text + "_processed");

            DirectoryInfo[] dirs = info.GetDirectories();
            Dictionary <int, PicCategory> mapDir = new Dictionary <int, PicCategory>();

            foreach (DirectoryInfo inf in dirs)
            {
                string[] ss = inf.Name.Split('_');

                PicCategory c = new PicCategory();
                c.ID     = Int32.Parse(ss[1]);
                c.SortID = Int32.Parse(ss[2]);
                c.EName  = ss[0];
                if (mapName.ContainsKey(ss[0]))
                {
                    c.CName = mapName[ss[0]];
                }
                else
                {
                    c.CName = c.EName;
                }
                c.SrcPath        = inf.FullName;
                mapDir[c.SortID] = c;
            }

            string sNewPath = tbPicPath.Text + "_Output";

            Directory.CreateDirectory(sNewPath);

            string sJson = "[";

            //Change the order!
            int iMaxSortID = mapDir.Count;


            for (int iCur = 0; iCur < iMaxSortID; iCur++)
            {
                PicCategory c        = mapDir[iCur];
                string      sCatPath = sNewPath + "\\" + c.ID;
                Directory.CreateDirectory(sCatPath);

                FileInfo[] fileNames = new DirectoryInfo(c.SrcPath).GetFiles();
                int        iCnt      = (fileNames.Length - 1) / 2;

                sJson += "{c:" + c.ID + ",n:'" + c.CName.Replace("\'", "\\\'") + "',max:" + iCnt.ToString() + "},";

                foreach (FileInfo fInfo in fileNames)
                {
                    if (fInfo.Name == "category.gif")
                    {
                        Bitmap bm = Bitmap.FromFile(fInfo.FullName) as Bitmap;
                        bm.Save(sCatPath + "\\category.png", ImageFormat.Png);
                    }
                    else
                    {
                        fInfo.CopyTo(sCatPath + "\\" + fInfo.Name);
                    }
                }
            }

            sJson  = sJson.Substring(0, sJson.Length - 1);
            sJson += "]";

            File.WriteAllText(sNewPath + "\\Category.txt", sJson);
        }
 public static void RemoveDualBuffs(IReadOnlyList<AbstractBuffEvent> buffsPerDst, Dictionary<long, List<AbstractBuffEvent>> buffsByID, SkillData skillData)
 {
     var duals = new HashSet<long>
     {
         FireDual,
         WaterDual,
         AirDual,
         EarthDual,
     };
     var toClean = new HashSet<long>();
     foreach (AbstractBuffEvent c in buffsPerDst.Where(x => duals.Contains(x.BuffID)))
     {
         toClean.Add(c.BuffID);
         c.Invalidate(skillData);
     }
     foreach (long buffID in toClean)
     {
         buffsByID[buffID].RemoveAll(x => x.BuffID == NoBuff);
     }
 }