Example #1
0
        public void NotifyChangedText()
        {
            var propDict = new Dictionary<string, string>();

            JsonObject jso = new JsonObject();
            jso.PropertyChanged += (obj, e) => { propDict.Add(e.PropertyName, ""); };

            dynamic djso = jso;

            Assert.IsFalse(propDict.ContainsKey("Name"));
            djso.Name = "JP";
            Assert.IsTrue(propDict.ContainsKey("Name"));
            propDict.Clear();

            Assert.IsFalse(propDict.ContainsKey("Name"));
            djso["Name"] = "JP";
            Assert.IsTrue(propDict.ContainsKey("Name"));
            propDict.Clear();

            djso.RemoveAll();
            Assert.IsFalse(propDict.ContainsKey("Name"));
            djso.Add("Name", "JP");
            Assert.IsTrue(propDict.ContainsKey("Name"));
            propDict.Clear();
        }
        void CollectViews()
        {
            var view = android_ass.GetType ("Android.Views.View");
            var animation = android_ass.GetType ("Android.Views.Animations.Animation");
            var layoutparams = android_ass.GetType ("Android.Views.ViewGroup+LayoutParams");
            targets.Add (view);
            var d = new Dictionary<Type,bool> ();
            foreach (var ass in asses)
                foreach (var t in ass.GetTypes ())
                    CheckIfTypeIsTarget (view, d, t);
            views.AddRange (from e in d where e.Value select e.Key);
            targets.AddRange (views);
            d.Clear ();

            targets.Add (animation);
            foreach (var ass in asses)
                foreach (var t in ass.GetTypes ())
                    CheckIfTypeIsTarget (animation, d, t);
            anims.AddRange (from e in d where e.Value select e.Key);
            targets.AddRange (anims);
            d.Clear ();

            layparams.Add (layoutparams);
            foreach (var ass in asses)
                foreach (var t in ass.GetTypes ())
                    CheckIfTypeIsTarget (layoutparams, d, t);
            layparams.AddRange (from e in d where e.Value select e.Key);
            targets.AddRange (layparams);
            d.Clear ();

            GenerateCode ();
        }
		/// <summary>
		/// Do the specified input and output.
		/// </summary>
		/// <param name="input">Input.</param>
		/// <param name="output">Output.</param>
        public void Do(BlockingCollection<ISkeleton> input, Action<IEnumerable<Result>> fireNewCommand)
        {
            var data = new Dictionary<JointType, InputVector>();
            foreach (var skeleton in input.GetConsumingEnumerable())
            {
                foreach (var joint in skeleton.Joints)
                {
                    if (!data.ContainsKey(joint.JointType))
                    {
                        data.Add(joint.JointType, new InputVector());
                    }
                    data[joint.JointType].Stream.Add(joint.Point);
                }
                if (data.First().Value.Stream.Count < 5)
                {
                    continue;
                }
                var results = Recognizer.Recognize(data);
                try
                {
                    fireNewCommand(results);
                }
                catch (Exception)
                {
                    if (data.First().Value.Stream.Count > 40)
                    {
                        data.Clear();
                    }
                    continue;
                }
                data.Clear();
            }
        }
    /// <summary>
    /// Метод удаляет лист заказа вместе с горячей статистикой
    /// </summary>
    /// <param name="orderNum">Номер листа заказа</param>
    public static void deleteOrder(string orderNum)
    {
        Dictionary<string, string> Dict = new Dictionary<string, string>();
            Dict.Add("ORDER_NUM", orderNum);

            SQLOracle.delete("delete from USP_HOT_STATS where ORDER_NUM = :ORDER_NUM", Dict);
            Dict.Clear();

            if (!AssemblyOrders.isProject(orderNum))
            {
                int id = _ASSEMBLIES.getId_OrderNum(orderNum);
                Dict.Add("ID", id.ToString());
                SQLOracle.delete("delete from USP_ASSEMBLIES where ID = :ID", Dict);
                SQLOracle.delete("delete from USP_ASSEMBLY_ELEMENTS where ASSEMBLY_ID = :ID", Dict);
                Dict.Clear();
            }

            if (isTZ(orderNum))
            {
                string idDoc = getTZId(orderNum);
                Dict.Add("ID_DOC", idDoc);

                string cmdUpdate = "update USP_TZ_DATA set UTV = 1, HP_KOL_EDEN = null where ID_DOC = :ID_DOC";
                SQLOracle.update(cmdUpdate, Dict);

                cmdUpdate = "update USP_TZ_DATA_TP set OBOZN_KOMP = NULL, NAIM_KOMP = NULL, KOL = null where ID_DOC = :ID_DOC";
                SQLOracle.update(cmdUpdate, Dict);
            }

            Dict.Clear();
            Dict.Add("ORDER_NUM", orderNum);
            SQLOracle.delete("delete from USP_ASSEMBLY_ORDERS where NUM = :ORDER_NUM", Dict);
    }
Example #5
0
        public void StringProperties()
        {
            IDictionary<string, object> dict = new Dictionary<string, object>();

            dict["intprop"] = 1;
            string json = JSON.ToJSON(dict);
            Assert.AreEqual("{\"intprop\":1}",json);

            dict.Clear();
            dict["stringprop"] = "foo";
            json = JSON.ToJSON(dict);
            Assert.AreEqual("{\"stringprop\":\"foo\"}", json);

            dict.Clear();
            dict["arrayprop"] = new int[] { 1, 2, 3 };
            json = JSON.ToJSON(dict);
            Assert.AreEqual("{\"arrayprop\":[1,2,3]}", json);
            
            dict.Clear();
            dict["1"] = "bar";
            json = JSON.ToJSON(dict);
            Assert.AreEqual("{\"1\":\"bar\"}", json);

            dict.Clear();
            dict["false"] = "foobar";
            json = JSON.ToJSON(dict);
            Assert.AreEqual("{\"false\":\"foobar\"}", json);
        }
        private static void Main(string[] args)
        {
            var connector = Credentials.MyConnector();
              var paramlist = new Dictionary<string, string>
              {
            {"account", "test"},
            {"tablename", "sdktest1"},
            {"fileurl", "http://maplarge-data.s3.amazonaws.com/TwitterS3.zip"}
              };

              //CREATE TABLE SYNCHRONOUS (NO WEB CALL)
              //MapLargeConnector.NO_WEB_CALLS = true;
              var response = connector.InvokeAPIRequest("CreateTableSynchronous", paramlist);
              Console.WriteLine(response);
              MapLargeConnector.NO_WEB_CALLS = false;

              //RETRIEVE REMOTE USER AUTH TOKEN
              response = connector.GetRemoteAuthToken(Credentials.UserName, Credentials.Password, "255.255.255.255");
              Console.WriteLine(response);

              //LIST GROUPS
              paramlist.Clear();
              paramlist.Add("account", "test");
              response = connector.InvokeAPIRequestPost("ListGroups", paramlist);
              Console.WriteLine(response);

              //CREATE TABLE WITH FILES SYNCHRONOUS
              paramlist.Clear();
              paramlist.Add("account", "test");
              paramlist.Add("tablename", "sdktest2");
              response = connector.InvokeAPIRequestPost("CreateTableWithFilesSynchronous",
            paramlist,
            new[] {@"C:\MapLarge\Small.csv"});
              Console.WriteLine(response);
        }
Example #7
0
            public bool IsValidSudoku(char[,] board)
            {
                IDictionary<char, bool> dic = new Dictionary<char, bool> ();

                for (int i = 0; i < board.GetLength (0); ++i) {
                    // row
                    dic.Clear();
                    for (int j = 0; j < board.GetLength (1); ++j) {
                        if (board [i, j] == '.') {
                            continue;
                        }
                        if (dic.ContainsKey (board [i, j])) {
                            return false;
                        } else {
                            dic[board[i, j]] = true;
                        }
                    }

                    // col
                    dic.Clear();
                    for (int j = 0; j < board.GetLength (1); ++j) {
                        if (board [j, i] == '.') {
                            continue;
                        }
                        if (dic.ContainsKey (board [j, i])) {
                            return false;
                        } else {
                            dic[board[j, i]] = true;
                        }
                    }
                }

                // part
                for (int i = 0; i < board.GetLength (0); i += 3) {
                    for (int j = 0; j < board.GetLength (1); j += 3) {
                        dic.Clear ();
                        for (int ii = 0; ii < 3; ++ii) {
                            for (int jj = 0; jj < 3; ++jj) {
                                char c = board [i + ii, j + jj];
                                if (c == '.') {
                                    continue;
                                }

                                if (dic.ContainsKey (c)) {
                                    return false;
                                } else {
                                    dic[c] = true;
                                }
                            }
                        }
                    }
                }

                return true;
            }
Example #8
0
        public static void Run()
        {
            Console.WriteLine("Running test configured with App.config.");

            using (WorkflowRuntimeManager manager = new WorkflowRuntimeManager(new WorkflowRuntime("WorkflowRuntime")))
            {
                manager.MessageEvent += delegate(object sender, WorkflowLogEventArgs e)
                {
                    Console.WriteLine(e.Message);
                };
                
                manager.WorkflowRuntime.StartRuntime();

                Dictionary<string, object> wfArguments = new Dictionary<string, object>();
                //wfArguments.Add("InputString", "1");
                ManagedWorkflowInstance instance1 = manager.StartWorkflow(@"C:\Documents and Settings\Administrator\Desktop\Pro WF\chapter 17\WorkflowDesignerApp\bin\Debug\Test.xoml", @"C:\Documents and Settings\Administrator\Desktop\Pro WF\chapter 17\WorkflowDesignerApp\bin\Debug\Test.rules", wfArguments);
                //ManagedWorkflowInstance instance1 = manager.StartWorkflow(typeof(Workflow1), wfArguments);
                //instance1.WorkflowInstance.Terminate("Manual Termination");

                wfArguments.Clear();
                wfArguments.Add("InputString", "2");
                ManagedWorkflowInstance instance2 = manager.StartWorkflow(typeof(Workflow1), wfArguments);
                instance2.WorkflowInstance.Suspend("Manual Suspension");
                instance2.WorkflowInstance.Resume();

                wfArguments.Clear();
                wfArguments.Add("InputString", "3");
                manager.StartWorkflow(typeof(Workflow1), wfArguments);
                
                manager.WaitAll(15000);

                foreach (ManagedWorkflowInstance managedInstance in manager.Workflows.Values)
                {
                    if (managedInstance.Outputs.ContainsKey("Result"))
                    {
                        Console.WriteLine(managedInstance.Outputs["Result"]);
                    }
                    if (managedInstance.Exception != null)
                    {
                        Console.WriteLine("{0} - Exception: {1}", managedInstance.Id, managedInstance.Exception.Message);
                    }
                    if (managedInstance.ReasonSuspended.Length > 0)
                    {
                        Console.WriteLine("{0} - Suspended: {1}", managedInstance.Id, managedInstance.ReasonSuspended);
                    }
                }
                manager.ClearAllWorkflows();
            }
        }
Example #9
0
		/// <summary>
		/// replace every <include/> node in the document with the nodes that it references
		/// </summary>
		/// <param name="dom"></param>=
		public void ProcessDom(string parentPath, XmlDocument dom)
		{
			Dictionary<string, XmlDocument> cachedDoms = new Dictionary<string, XmlDocument>();
			cachedDoms.Add(parentPath, dom);
			ProcessDom(cachedDoms, null, dom);
			cachedDoms.Clear();
		}
        private void GetTests()
        {
            methods = methods ?? new LinkedList<MethodInfo>();
            methods.Clear();
            status = status ?? new Dictionary<MethodInfo, Status>();
            status.Clear();
            toggleGroup = toggleGroup ?? new Dictionary<string, bool>();

            var bindingFlags = BindingFlags.Public;
            bindingFlags |= BindingFlags.Static;
            bindingFlags |= BindingFlags.DeclaredOnly;

            Type[] typelist = GetTypesInNamespace("Exodrifter.ExpressionParser.Test");
            for (int i = 0; i < typelist.Length; i++) {
                foreach (var method in typelist[i].GetMethods(bindingFlags)) {
                    if (0 == method.GetParameters().Length) {
                        methods.AddLast(method);
                        status.Add(method, Status.UNKNOWN);

                        if (!toggleGroup.ContainsKey(method.DeclaringType.Name)) {
                            toggleGroup[method.DeclaringType.Name] = false;
                        }
                    }
                }
            }
        }
        public void Bind(MapperGenerator.Library.Model.TemplateSource.FileModel model, Dictionary<TreeNode, object> templateFileModelMap, TreeView treeFileTemplateModel)
        {
            treeFileTemplateModel.Nodes.Clear();

            templateFileModelMap.Clear();
            var fileNode = new TreeNode("File");
            templateFileModelMap.Add(fileNode, model);

            foreach (var ns in model.Namespaces)
            {
                var nsNode = new TreeNode(ns.Name.PascalCase);
                templateFileModelMap.Add(nsNode, ns);

                foreach (var cs in ns.Entities)
                {
                    var csNode = new TreeNode(cs.Name.PascalCase);
                    templateFileModelMap.Add(csNode, cs);

                    foreach (var ps in cs.Properties)
                    {
                        var psNode = new TreeNode(ps.Name.PascalCase);
                        templateFileModelMap.Add(psNode, ps);

                        csNode.Nodes.Add(psNode);
                    }

                    nsNode.Nodes.Add(csNode);
                }

                fileNode.Nodes.Add(nsNode);
            }
            treeFileTemplateModel.Nodes.Add(fileNode);
            treeFileTemplateModel.SelectedNode = fileNode;
            treeFileTemplateModel.ExpandAll();
        }
Example #12
0
        public void WritePdb(SymbolData symData)
        {
            m_docWriters = new Dictionary<int, ISymbolDocumentWriter>();

            ImageDebugDirectory debugDirectory;
            byte[] debugInfo = null;
            // Rather than use the emitter here, we are just careful enough to emit pdb metadata that
            // matches what is already in the assembly image.
            object emitter = null;

            // We must be careful to close the writer before updating the debug headers.  The writer has an
            // open file handle on the assembly we want to update.
            m_writer = SymbolAccess.GetWriterForFile(m_symFormat, m_outputAssembly, ref emitter);

            // We don't actually need the emitter in managed code at all, so release the CLR reference on it
            Marshal.FinalReleaseComObject(emitter);

            try
            {
                WriteEntryPoint(symData.entryPointToken);
                WriteFiles(symData.sourceFiles);
                WriteMethods(symData.methods);
                debugInfo = m_writer.GetDebugInfo(out debugDirectory);
            }
            finally
            {
                m_writer.Close();
                ((IDisposable)m_writer).Dispose();
                m_writer = null;
                m_docWriters.Clear();
            }

            UpdatePEDebugHeaders(debugInfo);
        }
        static void GetQuaries(string consoleInput)
        {
            Dictionary<string, List<string>> result = new Dictionary<string,List<string>>();

            string pattern = @"(?:\w+)(?:[\%\d\+])*=(?:[\%20|\+])*(([\w\d]*)(?:\%20|\+)*)*(?=[\n\b\&]|$)";
            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(consoleInput);

            foreach(Match match in matches)
            {
                string filteredQuery = FilterQuery(match.Value);
                string key = GetKey(filteredQuery).Trim();
                string values = GetValues(filteredQuery).Trim();

                if (!result.ContainsKey(key))
                    result.Add(key, new List<string>());

                result[key].Add(values);

            }

            PrintQueries(result);

            Console.WriteLine();

            result.Clear();
        }
        private void setupDeck(List<CardDB.cardIDEnum> cardsPlayed, List<CardDB.Card> deckGuessed, Dictionary<CardDB.cardIDEnum, int> knownCards)
        {
            deckGuessed.Clear();
            knownCards.Clear();
            foreach (CardDB.cardIDEnum crdidnm in cardsPlayed)
            {
                if (crdidnm == CardDB.cardIDEnum.GAME_005) continue; //(im sure, he has no coins in his deck :D)
                if (knownCards.ContainsKey(crdidnm))
                {
                    knownCards[crdidnm]++;
                }
                else 
                {
                    if (CardDB.Instance.getCardDataFromID(crdidnm).rarity == 5)
                    {
                        //you cant own rare ones more than once!
                        knownCards.Add(crdidnm, 2);
                        continue;
                    }
                    knownCards.Add(crdidnm, 1);
                }
            }

            foreach (KeyValuePair<CardDB.cardIDEnum, int> kvp in knownCards)
            {
                if (kvp.Value == 1) deckGuessed.Add(CardDB.Instance.getCardDataFromID(kvp.Key));
            }
        }
Example #15
0
 //Given s string, Find max size of a sub-string, in which no duplicate chars present.
 public int MaxSubString(string str)
 {
     int max = 0;
     int count = 0;
     int current = 0;
     Dictionary<char, int> result = new Dictionary<char, int>();
     while (current!=str.Length)
     {
         if (result.ContainsKey(str[current]))
         {
             if (count > max)
             {
                 max = count;
             }
             count = 0;
             result.Clear();
             str = str.Substring(current+1);
             current = 0;
         }
         else
         {
             result.Add(str[current], 1);
             count++;
             current++;
         }
     }
     if (count > max) max = count;
     return max;
 }
        public void TestMostCommon()
        {
            var largest = new Dictionary<string, int>();

            // Init a dictionary to store quantities of people of varying nationalities.
            Dictionary<string, int> dict = _dictionary;
            int max = dict.Values.Max();

            foreach (var kvp in dict)
            {
                if (max == kvp.Value)
                    largest.Add(kvp.Key, kvp.Value);
            }

            Assert.AreEqual(42, max);
            Assert.Contains("b", largest.Keys);
            Assert.Contains("d", largest.Keys);
            largest.Clear();

            largest = dict.Where(kvp => max == kvp.Value).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            Assert.AreEqual(42, max);
            Assert.Contains("b", largest.Keys);
            Assert.Contains("d", largest.Keys);
        }
 public static bool IsmorphicString(string s, string t)
 {
     //"egg" "add" return true;
     //"foo" "bar" return false;
     //"paper" "title" return false;
     Dictionary<char, char> dic = new Dictionary<char, char>();
     StringBuilder sb1 = new StringBuilder();
     StringBuilder sb2 = new StringBuilder();
     for(int i=0; i<s.Length; i++)
     {
         if (dic.ContainsKey(s[i]))
             sb1.Append(dic[s[i]]);
         else
         {
             dic.Add(s[i], Convert.ToChar(i));
             sb1.Append(Convert.ToChar(i));
         }
     }
     dic.Clear();
     for(int i=0; i<t.Length;i++)
     {
         if (dic.ContainsKey(t[i]))
             sb2.Append(dic[t[i]]);
         else
         {
             dic.Add(t[i], Convert.ToChar(i));
             sb2.Append(Convert.ToChar(i));
         }
     }
     return sb1.ToString() == sb2.ToString();
 }
        public RootController()
            : base(new RootElement ("Netstat"))
        {
            Settings = Settings.Instance;

            section = new Section ();
            Root.Add (section);

            displayedEntries = new Dictionary<NetstatEntry,DateTime> ();

            RefreshRequested += (sender, e) => {
                Populate ();
                ReloadComplete ();
            };

            Settings.Modified += (sender, e) => InvokeOnMainThread (() => {
                displayedEntries.Clear ();
                Populate ();
            });

            timer = NSTimer.CreateRepeatingTimer (1.0, () => {
                if (View.Hidden || !Settings.AutoRefresh)
                    return;
                Populate ();
            });
            NSRunLoop.Main.AddTimer (timer, NSRunLoopMode.Default);
        }
Example #19
0
        public MainPage()
        {
            InitializeComponent();
            xml = App.GetResourceStream(new Uri("dinesafe.xml", UriKind.Relative));
            loadedData = XDocument.Load(xml.Stream);

            var data = from query in loadedData.Descendants("ROW")
                       select new DineSafe {
                           Name = (string)query.Attribute("N"),
                           FoodType = (string)query.Attribute("T"),
                           Address = (string)query.Attribute("A"),
                           Status = (string)query.Attribute("S"),
                           Details = (string)query.Attribute("D"),
                           Date = (string)query.Attribute("I"),
                           Severity = (string)query.Attribute("X")
                       };

            original = data.ToArray<DineSafe>();
            Dictionary<string, short> seenEntries = new Dictionary<string, short>();
            foreach (DineSafe dineSafe in data) {
                string key = dineSafe.GetKey();
                if (!seenEntries.ContainsKey(key)) {
                    uniques.Add(dineSafe);
                    seenEntries.Add(key, 0);
                }
            }
            seenEntries.Clear();
            array = uniques.ToArray();
        }
Example #20
0
        static Worksheet _sheet; //current worksheet

        #endregion Fields

        #region Methods

        public void parseMessage(String str)
        {
            Message m = Json.deserialize(str);
            switch (m.action)
            {
                case "init":
                    //send the whoami message
                    Dictionary<string, string> dict = new Dictionary<string, string>();
                    dict.Add("type", "alex");
                    dict.Add("doctype", "spreadsheet");
                    dict.Add("setup", "desktop");
                    Message whoami = new Message("whoami", dict);
                    net.send(Json.serialize(whoami));

                    dict.Clear();
                    //send the alex.imap message
                    dict.Add("imap", "test");
                    Message imap = new Message("alex.imap", dict);
                    net.send(Json.serialize(imap));

                    break;
                case "alex.select":
                default:
                    MessageBox.Show(str);
                    break;
            }
        }
Example #21
0
        public static List<CatTable> Fill(DbJet db)
        {
            OleDbDataReader reader = db.Read("select * from 0cat order by catord asc");

            List<CatTable> tables = new List<CatTable>();
            Dictionary<string, object> fields = new Dictionary<string, object>();

            while (reader.Read())
            {
                // Fields will help us to overcome non seq order
                fields.Clear();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    fields.Add(reader.GetName(i).ToLower(), reader.GetValue(i));
                }

                CatTable table = new CatTable();
                table.id = long.Parse(fields["id"].ToString());
                table.name = fields["name"].ToString();
                table.catord = long.Parse(fields["catord"].ToString());
                table.lvl = long.Parse(fields["lvl"].ToString());

                tables.Add(table);
            }

            return tables;
        }
Example #22
0
 private void ListBucket()
 {
     backupProgress.EnterAction(BackupAction.ListingBucket);
     try
     {
         files.RemoveRemoteFiles();
         if (Settings.Default.Bucket != null)
         {
             try
             {
                 S3 s3 = new S3(Settings.Default.Bucket.AccessKeyId, Settings.Default.Bucket.SecretAccessKey);
                 IDictionary<string, BackupFileAttributes> remoteFiles = new Dictionary<string, BackupFileAttributes>();
                 foreach (IS3Object file in s3.ListObjects(Settings.Default.Bucket.BucketName))
                 {
                     executor.CheckAbortion();
                     remoteFiles.Add(GetFileName(file.Key), new BackupFileAttributes(file.Size, file.LastModified, file.ETag));
                     if (remoteFiles.Count == 1000)
                     {
                         files.AddRemoteFiles(remoteFiles);
                         remoteFiles.Clear();
                     }
                 }
                 files.AddRemoteFiles(remoteFiles);
             }
             catch (S3Exception e)
             {
                 MessageBox.Show(e.Message);
             }
         }
     }
     finally
     {
         backupProgress.ExitAction(BackupAction.ListingBucket);
     }
 }
Example #23
0
 static void Main(string[] args)
 {
     string text;
     string patternRepl = @"\s{2,}";
     Regex regexRepl = new Regex(patternRepl);
     string pattern = @"([^=&]+)=([^&=]+)";
     Regex regex = new Regex(pattern);
     MatchCollection matches;
     var query = new Dictionary<string, List<string>>();
     while (!((text = Console.ReadLine()) == "END"))
     {
         text = text.Replace("%20", " ").Replace("+", " ").Replace("?", "&");
         text = regexRepl.Replace(text, " ");
         matches = regex.Matches(text);
         foreach (Match match in matches)
         {
             string field = match.Groups[1].ToString().Trim();
             string value = match.Groups[2].ToString().Trim();
             if (!query.ContainsKey(field))
             {
                 query.Add(field, new List<string>());
             }
             query[field].Add(value);
         }
         foreach (string field in query.Keys)
         {
             Console.Write("{0}=[{1}]", field, string.Join(", ", query[field]));
         }
         Console.WriteLine();
         query.Clear();
     }
 }
        void LoadDictionary(Dictionary<int, string> dic, IniSection section)
        {
            dic.Clear();

            if (section == null)
                return;

            foreach (IniKey iKey in section.Keys)
            {
                if (iKey.IsComment)
                    continue; // entry is commented out

                string key = iKey.Name;
                string value = iKey.Value;
#if DEBUG
                if (key.Trim().StartsWith("EOF"))
                    break; // for testing purposes
#else
                if (key.Trim().StartsWith("EOF"))
                    continue; // ignore
#endif
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                    dic.Add(int.Parse(key), value);
            }
        }
Example #25
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method Clear .");

        try
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("txt", "notepad.exe");
            dictionary.Add("bmp", "paint.exe");
            dictionary.Add("dib", "paint.exe");
            dictionary.Add("rtf", "wordpad.exe");

            dictionary.Clear();

            int actual = dictionary.Count;
            int expected = 0;
            if (actual != expected)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method Clear Err.");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #26
0
 public static bool IsMatch(string testUrl,out IDictionary<string,object> paramter)
 {
     string clearUrl;
     var urlSplits = GetUrlSplit(testUrl,out clearUrl);
     if (urlSplits==null)
     {
         //首页自行处理
         paramter = null;
         return false;
     }
     if (RouteMappings != null)
     {
         IDictionary<string, object> dict = new Dictionary<string, object>();
         foreach (var match in RouteMappings)
         {
             dict.Clear();
             if (match.IsMatch(urlSplits, ref dict))
             {
                 paramter = dict;
                 return true;
             }
         }
     }
     paramter = null;
     return false;
 }
Example #27
0
        public static void Main(string[] args)
        {
            Dictionary<string,int> dict=new Dictionary<string,int>();
            dict.Add("one",1);
            dict.Add("two",2);
            dict.Add("three",3);
            dict.Add("four",4);
            dict.Remove("one");

            Console.WriteLine(dict.ContainsKey("dsaf"));
            Console.WriteLine("Key Value Pairs after Dictionary related operations:");
            foreach (var pair in dict)
            {
                Console.WriteLine("{0}, {1}",
                    pair.Key,
                    pair.Value);
            }
            dict.Clear ();

            List<string> strList = new List<string> ();
            strList.Add ("one");
            strList.Add ("two");
            strList.Add ("three");
            strList.Add ("four");
            strList.Add ("five");
            strList.Insert (3, "great");
            string[] newList = new string[3]{ "ten", "eleven", "twelve" };
            strList.AddRange (newList);
            strList.InsertRange (3, newList);

            Console.WriteLine ("Output after all list related  operations i.e. add, insert, addrange, insertrange,remove");
            foreach (var i in strList)
                Console.WriteLine (i);
        }
Example #28
0
        public static void Main(string[] args)
        {
            /* List Operations */

            List<int> list = new List<int>();

            list.Add (10);

            list.AddRange (new List<int> () { 20, 30, 40 });

            list.Remove (10);

            list.Insert (0, 10);

            list.Clear ();

            /* Dictionary Operations */

            Dictionary<int, string> dictionary = new Dictionary<int, string> ();

            dictionary.Add (1, "Sanjana");
            dictionary.Add (2, "Sumana");

            dictionary.ContainsValue ("Sanjana");
            dictionary.Remove (1);

            dictionary.Add (3, "Srinivas");

            dictionary.Clear ();
        }
        public unsafe static NetworkInterface[] GetLinuxNetworkInterfaces()
        {
            Dictionary<string, LinuxNetworkInterface> interfacesByName = new Dictionary<string, LinuxNetworkInterface>();
            const int MaxTries = 3;
            for (int attempt = 0; attempt < MaxTries; attempt++)
            {
                int result = Interop.Sys.EnumerateInterfaceAddresses(
                    (name, ipAddr, maskAddr) =>
                    {
                        LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name);
                        lni.ProcessIpv4Address(ipAddr, maskAddr);
                    },
                    (name, ipAddr, scopeId) =>
                    {
                        LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name);
                        lni.ProcessIpv6Address( ipAddr, *scopeId);
                    },
                    (name, llAddr) =>
                    {
                        LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name);
                        lni.ProcessLinkLayerAddress(llAddr);
                    });
                if (result == 0)
                {
                    return interfacesByName.Values.ToArray();
                }
                else
                {
                    interfacesByName.Clear();
                }
            }

            throw new NetworkInformationException(SR.net_PInvokeError);
        }
Example #30
0
 /// <summary>
 /// 新增区域,返回新增区域的对象
 /// </summary>
 /// <param name="area"></param>
 /// <returns></returns>
 public object AddArea(Area area)
 {
     using (DBHelper db = DBHelper.Create())
     {
         area.ID = Guid.NewGuid().ToString().Replace("-", "");
         string selectCode = "select max(code) from T_Area where PID = @PID";
         Dictionary<string, object> paramList = new Dictionary<string, object>();
         paramList.Add("PID", area.PID);
         object maxCode = db.ExcuteScular(selectCode, paramList);
         string code = maxCode == null ? "" : maxCode.ToString();
         string selectPCode = "select code from T_Area where ID = @ID";
         paramList.Clear();
         paramList.Add("ID", area.PID);
         object PCode = db.ExcuteScular(selectPCode, paramList);
         if (string.IsNullOrEmpty(code))
             code = PCode + "0001";
         else
             code = code.Substring(0, code.Length - 4) + (Convert.ToInt32(code.Substring(code.Length - 4)) + 1).ToString().PadLeft(4, '0');
         area.Code = code;
         area.Code = PCode + area.Code;
         try
         {
             return db.Insert<Area>(area);
         }
         catch (System.Exception ex)
         {
             area.State = "1";
             area.Errormsg = ex.Message;
             return area;
         }
     }
 }