Clear() public method

public Clear ( ) : void
return void
Example #1
0
        protected override string OnScrape(string url, HtmlNode elem)
        {
            var id = SelectItem(elem, "[name=id]").Attributes["value"].Value;
            var fname = SelectItem(elem, "[name=fname]").Attributes["value"].Value;
            var data = new NameValueCollection();
            data.Add("op", "download1");
            data.Add("usr_login", "");
            data.Add("id", id);
            data.Add("fname", fname);
            data.Add("method_free", "Proceed to Video");
            elem = Post(url, data);

            var rand = SelectItem(elem, "[name=rand]").Attributes["value"].Value;
            data.Clear();
            data.Add("op", "download2");
            data.Add("rand", rand);
            data.Add("id", id);
            data.Add("fname", fname);
            data.Add("method_free", "Proceed to Video");
            data.Add("method_premium", "");
            Thread.Sleep(45000);
            elem = Post(url, data);
            url = new Uri(SelectItem(elem, "#lnk_download").Attributes["href"].Value).AbsoluteUri;

            return url;
        }
Example #2
0
        string GenericReloadUrl(NameValueCollection queryStrings)
        {
            if ((queryStrings == null) || (queryStrings.Count == 0))
            {
                return Request.Url.AbsolutePath;
            }

            StringBuilder builder = new StringBuilder();

            builder.Append(Request.Url.AbsolutePath).Append("?");

            string str = "";

            foreach (string key in queryStrings.Keys)
            {

                 str = queryStrings[key].Trim().Replace("'", "");

                if (!string.IsNullOrEmpty(str) && (str.Length > 0))
                {
                    builder.Append(key).Append("=").Append(Server.UrlEncode(str)).Append("&");
                }

            }
            queryStrings.Clear();

            builder.Remove(builder.Length - 1, 1);

            return builder.ToString();
        }
Example #3
0
 private static WmsServerInfo[] InitServerList()
 {
     SetSearchPath();
     XmlDocument serverDoc = ServerDoc();
     XmlNodeList serverNodes = serverDoc.DocumentElement.SelectNodes("Server");
     ArrayList serverList = new ArrayList();
     NameValueCollection userDefinedParameters = new NameValueCollection();
     foreach (XmlNode serverNode in serverNodes)
     {
         XmlNode userDefinedParametersNode = serverNode.SelectSingleNode("UserDefinedParameters");
         if (null != userDefinedParametersNode)
         {
             foreach (XmlAttribute xmlAttribute in userDefinedParametersNode.Attributes)
             {
                 userDefinedParameters.Add(xmlAttribute.Name, xmlAttribute.Value);
             }
         }
         serverList.Add(new WmsServerInfo(serverNode.SelectSingleNode("Description").InnerText, serverNode.SelectSingleNode("HTTP").InnerText, userDefinedParameters.Count > 0 ? new NameValueCollection(userDefinedParameters) : null));
         userDefinedParameters.Clear();
     }
     XmlNode defaultServerNode = serverDoc.DocumentElement.SelectSingleNode("Server/Default");
     _defaultServer = defaultServerNode.ParentNode.SelectSingleNode("Description").InnerText;
     serverList.Sort();
     return serverList.ToArray(typeof(WmsServerInfo)) as WmsServerInfo[];
 }
Example #4
0
        private List<string> Submit(string url, NameValueCollection require, List<KeyValuePair<string, string>> datas)
        {                        
            var sentvalues = new NameValueCollection();
            List<string> Results = new List<string>();
                        
            for(int i =0;i<datas.Count; i++) 
            {
                KeyValuePair<string, string> data = datas[i];
                sentvalues.Add(data.Key, data.Value);                
                
                if (i % BlukSize == 0 || i == datas.Count -1)
                {
                    if(require != null)
                        sentvalues.Add(require);

                    sentvalues.Add("secret", secret);
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(string.Format("{0}.txt", i));
                    var response = client.UploadValues(url, sentvalues);
                    var resstring = Encoding.UTF8.GetString(response);
                    writer.Write(resstring);
                    writer.Close();
                    foreach (var res in resstring.Split(','))
                        Results.Add(res);
                    
                    sentvalues.Clear();                    
                }
            }
            return Results;
        }
		public void DateTimeBind()
		{
			var args = new NameValueCollection();

			args.Add("person.DOBday", 1.ToString());
			args.Add("person.DOBmonth", 12.ToString());
			args.Add("person.DOByear", 2005.ToString());

			object instance = binder.BindObject(typeof (Person), "person", builder.BuildSourceNode(args));

			Assert.IsNotNull(instance);
			var p = (Person) instance;
			Assert.AreEqual(new DateTime(2005, 12, 1), p.DOB);

			args.Clear();
			args.Add("person.DOBday", 2.ToString());
			args.Add("person.DOBmonth", 1.ToString());
			args.Add("person.DOByear", 2005.ToString());

			instance = binder.BindObject(typeof (Person), "person", builder.BuildSourceNode(args));

			Assert.IsNotNull(instance);
			p = (Person) instance;
			Assert.AreEqual(new DateTime(2005, 1, 2), p.DOB);
		}
Example #6
0
        public ActionResult ContinuePayment(string url)
        {
            HtmlDocument doc = null;
            try {
                var web = new HtmlWeb();
                doc = web.Load(url);

                var form = doc.DocumentNode.Descendants("FORM").Single();
                var action = form.Attributes["ACTION"].Value;

                var formData = new NameValueCollection();
                foreach (var input in doc.DocumentNode.SelectNodes("//input")) {
                    formData.Add(input.Attributes["NAME"].Value, input.Attributes["VALUE"].Value);
                }

                var post = new PaymentWebClient();
                var bytes = post.UploadValues(action, formData);
                using (var ms = new MemoryStream(bytes))
                    doc.Load(ms);

                form = doc.DocumentNode.Descendants("FORM").First();
                action = form.Attributes["ACTION"].Value;

                formData.Clear();
                var skipNames = new string[] { "payment", "alias", "aliasoperation", "cancel" };
                foreach (var input in doc.DocumentNode.SelectNodes("//input")) {
                    var name = input.Attributes["NAME"];
                    if (name == null) continue;
                    if (skipNames.Contains(name.Value)) continue;
                    var valueAtt = input.Attributes["VALUE"];
                    var value = string.Empty;
                    if (valueAtt != null) value = valueAtt.Value;

                    formData[name.Value] = value;
                }
                formData["Ecom_Payment_Card_Name"] = "autotest";
                formData["Ecom_Payment_Card_Number"] = "4111 1111 1111 1111";
                formData["Ecom_Payment_Card_ExpDate_Month"] = "01";
                formData["Ecom_Payment_Card_ExpDate_Year"] = "2015";
                formData["Comp_Expirydate"] = "201501";
                formData["Ecom_Payment_Card_Verification"] = "123";

                post = new PaymentWebClient();
                //action = HttpUtility.UrlDecode(action); does not do the trick?
                action = action.Replace("&#58;", ":");
                bytes = post.UploadValues(action, formData);
                using (var ms = new MemoryStream(bytes))
                    doc.Load(ms);

                var uri = post.ResponseUri;
                return Redirect(Url.Action("Index", "Delivery") + uri.Query);
            }
            catch (Exception ex) {
                return View("BadPayment", new BadPaymentModel(ex, doc));
            }
        }
 public override void WriteShortcutTo(ViewShortcut currentShortcut, NameValueCollection queryString) {
     base.WriteShortcutTo(currentShortcut, queryString);
     if (!IsNewObjectView(currentShortcut)) {
         queryString.Clear();
         var modelView = (IModelViewFriendlyUrl)WebApplication.Instance.Model.Views[currentShortcut.ViewId];
         var objectKey = ObjectKey(currentShortcut, modelView);
         var friendlyUrl = EditModeFriendlyUrl(currentShortcut, modelView.FriendlyUrl, modelView as IModelDetailViewFriendlyUrl);
         queryString.Add(friendlyUrl, objectKey);
     }
 }
Example #8
0
 public void WriteShortcutTo(ViewShortcut currentShortcut, NameValueCollection queryString) {
     if (WebApplication.Instance.SupportsFriendlyUrl()) {
         if (!IsNewObjectView(currentShortcut)){
             var windowId = queryString["WindowId"];
             queryString.Clear();
             var modelView = (IModelViewFriendlyUrl)WebApplication.Instance.Model.Views[currentShortcut.ViewId];
             var objectKey = ObjectKey(currentShortcut, modelView);
             var friendlyUrl = EditModeFriendlyUrl(currentShortcut, modelView.FriendlyUrl, modelView as IModelDetailViewFriendlyUrl);
             queryString.Add(friendlyUrl, objectKey);
             if (!string.IsNullOrEmpty(windowId))
                 queryString.Add("WindowId",windowId);
         }
     }
 }
        /// <summary>
        /// Configures the <see cref="DataProtectionCryptographyService"/> using the
        /// specified settings collection.
        /// </summary>
        /// <param name="settings">A <see cref="NameValueCollection"/> with the setting to use to configure the service.</param>
        public void Configure(NameValueCollection settings)
        {
            Guard.ArgumentNotNull(settings, "settings");

            if (!String.IsNullOrEmpty(settings["Entropy"]))
            {
                entropy = Convert.FromBase64String(settings["Entropy"]);
            }
            if (!String.IsNullOrEmpty(settings["Scope"]))
            {
                scope = (DataProtectionScope) Enum.Parse(typeof (DataProtectionScope), settings["Scope"]);
            }

            // Remove values from setting for security.
            settings.Clear();
        }
Example #10
0
        /// <summary>
        /// Заполнить массив неазваний провайдеров
        /// </summary>
        public static void Initialize_GroupNames()
        {
            XmlElement root = (XmlElement)config.DocumentElement.SelectSingleNode("groups");

            if (GroupNames == null)
            {
                GroupNames = new NameValueCollection();
            }
            else
            {
                GroupNames.Clear();
            }

            foreach (XmlElement el in root)
            {
                GroupNames.Add(el.GetAttribute("id"), el.GetAttribute("name"));
            }
        }
Example #11
0
        private static void ProcessCollection(NameValueCollection collection)
        {
            var copy = new NameValueCollection();

            foreach (string key in collection.AllKeys)
            {
                Array.ForEach(
                    collection.GetValues(key),
                    v => copy.Add(key, ForbiddenWord.Filter(v)));
            }

            s_isReadOnlyPropertyInfo.SetValue(collection, false, null);

            collection.Clear();
            collection.Add(copy);

            s_isReadOnlyPropertyInfo.SetValue(collection, true, null);
        }
        /// <summary>
        /// This method creates secure/non secure web
        /// request based on the parameters passed.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="collHeader">This parameter of type
        ///    NameValueCollection may contain any extra header
        ///    elements to be included in this request      </param>
        /// <param name="RequestMethod">Value can POST OR GET</param>
        /// <param name="NwCred">In case of secure request this would be true</param>
        /// <returns></returns>
        public virtual HttpWebRequest CreateWebRequest(string uri,
          NameValueCollection collHeader,
          string RequestMethod, bool NwCred)
        {
            HttpWebRequest webrequest =
             (HttpWebRequest)WebRequest.Create(uri);
            webrequest.KeepAlive = false;
            webrequest.Method = RequestMethod;

            int iCount = collHeader.Count;
            string key;
            string keyvalue;

            for (int i = 0; i < iCount; i++)
            {
                key = collHeader.Keys[i];
                keyvalue = collHeader[i];
                webrequest.Headers.Add(key, keyvalue);
            }

            webrequest.ContentType = "text/html";
            //"application/x-www-form-urlencoded";

            if (ProxyServer.Length > 0)
            {
                webrequest.Proxy = new
                 WebProxy(ProxyServer, ProxyPort);
            }
            webrequest.AllowAutoRedirect = false;

            if (NwCred)
            {
                CredentialCache wrCache =
                        new CredentialCache();
                wrCache.Add(new Uri(uri), "Basic",
                  new NetworkCredential(UserName, UserPwd));
                webrequest.Credentials = wrCache;
            }
            //Remove collection elements
            collHeader.Clear();
            return webrequest;
        }//End of secure CreateWebRequest
Example #13
0
 private string GenericReloadUrl(System.Collections.Specialized.NameValueCollection queryStrings)
 {
     if (queryStrings == null || queryStrings.Count == 0)
     {
         return(base.Request.Url.AbsolutePath);
     }
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     stringBuilder.Append(base.Request.Url.AbsolutePath).Append("?");
     foreach (string text in queryStrings.Keys)
     {
         string text2 = queryStrings[text].Trim().Replace("'", "");
         if (!string.IsNullOrEmpty(text2) && text2.Length > 0)
         {
             stringBuilder.Append(text).Append("=").Append(base.Server.UrlEncode(text2)).Append("&");
         }
     }
     queryStrings.Clear();
     stringBuilder.Remove(stringBuilder.Length - 1, 1);
     return(stringBuilder.ToString());
 }
Example #14
0
        /// <summary>
        /// Заполнить массив неазваний провайдеров
        /// </summary>
        public static void Initialize_ProviderNames()
        {
            XmlElement root = (XmlElement)Ipaybox.providers.DocumentElement.SelectSingleNode("providers");

            if (ProviderNames == null)
            {
                ProviderNames = new NameValueCollection();
            }
            else
            {
                ProviderNames.Clear();
            }

            foreach (XmlElement el in root)
            {
                if (el.Name.ToLower().Trim() == "provider")
                {
                    ProviderNames.Add(el.GetAttribute("id"), el.GetAttribute("name"));
                }
            }
        }
Example #15
0
        public bool MakeFriendship(int targetId)
        {
            string reqURL = ConfigurationManager.AppSettings["FSQApi"] + "users/" + targetId +
                            "/request?oauth_token=" + token;

            var nv = new NameValueCollection();
            string result = null;
            try
            {
                result = HttpPost(reqURL, nv);
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                    return true;
                return false;
            }
            JObject obj = JObject.Parse(result);
            nv.Clear();

            return obj["response"]["user"] != null;
        }
Example #16
0
 public Venue GetVenuesInfo(string venueID)
 {
     logger.Debug("Getting venue info for " + venueID);
     string reqURL = ConfigurationManager.AppSettings["FSQApi"] + "venues/" + venueID;
     var nv = new NameValueCollection();
     nv["oauth_token"] = token;
     string result = HttpGet(reqURL, nv);
     logger.Debug(result);
     nv.Clear();
     JObject obj = JObject.Parse(result);
     Venue venue = new Venue();
     venue.id = "" + (string) obj["response"]["venue"]["id"];
     venue.Name = "" + (string) obj["response"]["venue"]["name"];
     venue.Contact = "" + (string) obj["response"]["venue"]["contact"]["phone"];
     venue.address = "" + (string) obj["response"]["venue"]["location"]["address"];
     venue.category = "" + (string) obj["response"]["venue"]["categories"][0]["name"];
     /*nv["name"] = "" + (string)obj["response"]["venue"]["name"];
     nv["contact"] = "" + (string)obj["response"]["venue"]["contact"]["phone"];
     nv["address"] = "" + (string)obj["response"]["venue"]["location"]["address"];
     nv["cat"] = "" + (string)obj["response"]["venue"]["categories"][0]["name"];*/
     return venue;
 }
Example #17
0
        /// <summary>
        /// Profile info for user
        /// </summary>
        /// <param name="Target_ID">Foursquare User ID</param>
        /// <returns>User Profile</returns>
        public Profile GetProfileInfo(int Target_ID)
        {
            string reqURL = ConfigurationManager.AppSettings["FSQApi"] + "users/" + Target_ID;
            var nv = new NameValueCollection();
            nv["oauth_token"] = token;
            string result = HttpGet(reqURL, nv);
            JObject obj = JObject.Parse(result);
            nv.Clear();

            nv["FirstName"] = "" + Convert.ToString(obj["response"]["user"]["firstName"]);
            nv["LastName"] = "" + Convert.ToString(obj["response"]["user"]["lastName"]);
            nv["Photo"] = "" + Convert.ToString(obj["response"]["user"]["photo"]);
            nv["Gender"] = "" + Convert.ToString(obj["response"]["user"]["gender"]);
            nv["Homecity"] = "" + Convert.ToString(obj["response"]["user"]["homeCity"]);
            nv["scoremax"] = "" + Convert.ToString(obj["response"]["user"]["scores"]["max"]);
            Profile targetProfile = new Profile(nv);
            return targetProfile;
        }
Example #18
0
		public void SelectMultiple2 ()
		{
			ListBoxPoker list = new ListBoxPoker ();
			list.SelectionMode = ListSelectionMode.Multiple;
			list.Items.Add (new ListItem ("1", "first"));
			list.Items.Add (new ListItem ("2", "second"));
			list.Items.Add (new ListItem ("3", "third"));
			list.Items.Add (new ListItem ("4", "forth"));
			NameValueCollection coll = new NameValueCollection ();
			coll.Add ("key", "second");
			coll.Add ("key", "forth");
			Assert.IsTrue (list.LoadPD ("key", coll), "#00");
			Assert.IsFalse (list.Items [0].Selected, "#01");
			Assert.IsTrue (list.Items [1].Selected, "#02");
			Assert.IsFalse (list.Items [2].Selected, "#03");
			Assert.IsTrue (list.Items [3].Selected, "#04");

			Assert.IsFalse (list.LoadPD ("key", coll), "#05");
			Assert.IsFalse (list.Items [0].Selected, "#06");
			Assert.IsTrue (list.Items [1].Selected, "#07");
			Assert.IsFalse (list.Items [2].Selected, "#08");
			Assert.IsTrue (list.Items [3].Selected, "#09");

			coll.Clear ();
			coll.Add ("key", "first");
			coll.Add ("key", "third");
			Assert.IsTrue (list.LoadPD ("key", coll), "#10");
			Assert.IsTrue (list.Items [0].Selected, "#11");
			Assert.IsFalse (list.Items [1].Selected, "#12");
			Assert.IsTrue (list.Items [2].Selected, "#13");
			Assert.IsFalse (list.Items [3].Selected, "#14");

		}
Example #19
0
        public void ReadSectionValues(string Section, NameValueCollection Values)
        {
            StringCollection KeyList = new StringCollection();
            ReadSection(Section, KeyList);
            Values.Clear();
            foreach (string key in KeyList)
            {
                Values.Add(key, ReadString(Section, key, ""));

            }
        }
Example #20
0
        public void Test01()
        {
            IntlStrings intl;
            NameValueCollection nvc;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count
            string itm;         // item
            // initialize IntStrings
            intl = new IntlStrings();


            // [] NameValueCollection is constructed as expected
            //-----------------------------------------------------------------

            nvc = new NameValueCollection();

            // [] get Item() on empty collection
            //
            Assert.Throws<ArgumentOutOfRangeException>(() => { itm = nvc[-1]; });
            Assert.Throws<ArgumentOutOfRangeException>(() => { itm = nvc[0]; });

            // [] get Item() on collection filled with simple strings
            //

            cnt = nvc.Count;
            int len = values.Length;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            if (nvc.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
            }

            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc[i], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[i], values[i]));
                }
            }


            //
            // Intl strings
            // [] get Item() on collection filled with Intl strings
            //

            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }


            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }


            nvc.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);
            }
            if (nvc.Count != (len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                if (String.Compare(nvc[i], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc[i], intlValues[i]));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            nvc.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                //
                if (String.Compare(nvc[i], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc[i], intlValues[i]));
                }

                if (!caseInsensitive && String.Compare(nvc[i], intlValuesLower[i]) == 0)
                {
                    Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
                }
            }

            // [] get Item() on filled collection - multiple items with the same key
            //

            nvc.Clear();
            len = values.Length;
            string k = "keykey";
            string k1 = "hm1";
            string exp = "";
            string exp1 = "";
            for (int i = 0; i < len; i++)
            {
                nvc.Add(k, "Value" + i);
                nvc.Add(k1, "iTem" + i);
                if (i < len - 1)
                {
                    exp += "Value" + i + ",";
                    exp1 += "iTem" + i + ",";
                }
                else
                {
                    exp += "Value" + i;
                    exp1 += "iTem" + i;
                }
            }
            if (nvc.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
            }

            if (String.Compare(nvc[0], exp) != 0)
            {
                Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[0], exp));
            }
            if (String.Compare(nvc[1], exp1) != 0)
            {
                Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc[1], exp1));
            }


            //
            //  [] Item(-1)
            //
            cnt = nvc.Count;

            Assert.Throws<ArgumentOutOfRangeException>(() => { itm = nvc[-1]; });

            //
            //  [] Item(count)
            //
            if (nvc.Count < 1)
            {
                for (int i = 0; i < len; i++)
                {
                    nvc.Add(keys[i], values[i]);
                }
            }
            cnt = nvc.Count;
            Assert.Throws<ArgumentOutOfRangeException>(() => { itm = nvc[cnt]; });

            //
            //  [] Item(count+1)
            //
            if (nvc.Count < 1)
            {
                for (int i = 0; i < len; i++)
                {
                    nvc.Add(keys[i], values[i]);
                }
            }
            cnt = nvc.Count;
            Assert.Throws<ArgumentOutOfRangeException>(() => { itm = nvc[cnt + 1]; });

            //
            //  [] Item(null)
            //   Item(null)   - calls other overloaded version of Get - Get(string) - no exception
            //
            itm = nvc[null];
            if (itm != null)
            {
                Assert.False(true, "Error, returned non-null ");
            }
        }
Example #21
0
        public void Test01()
        {
            IntlStrings intl;
            NameValueCollection nvc;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count
            string[] ks;           // Keys array

            // initialize IntStrings
            intl = new IntlStrings();


            // [] NameValueCollection is constructed as expected
            //-----------------------------------------------------------------

            nvc = new NameValueCollection();

            //  [] Remove() on empty collection
            //
            cnt = nvc.Count;
            nvc.Remove(null);
            if (nvc.Count != cnt)
            {
                Assert.False(true, "Error, changed collection after Remove(null)");
            }
            cnt = nvc.Count;
            nvc.Remove("some_string");
            if (nvc.Count != cnt)
            {
                Assert.False(true, "Error, changed collection after Remove(some_string)");
            }

            //  [] Remove() on collection filled with simple strings
            //

            cnt = nvc.Count;
            int len = values.Length;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            if (nvc.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
            }
            //

            for (int i = 0; i < len; i++)
            {
                cnt = nvc.Count;
                nvc.Remove(keys[i]);
                if (nvc.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item", i));
                }
                ks = nvc.AllKeys;
                if (Array.IndexOf(ks, keys[i]) > -1)
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            // Intl strings
            //  [] Remove() on collection filled with Intl strings
            //

            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }


            cnt = nvc.Count;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);
            }
            if (nvc.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                cnt = nvc.Count;
                nvc.Remove(intlValues[i + len]);
                if (nvc.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item", i));
                }
                ks = nvc.AllKeys;
                if (Array.IndexOf(ks, intlValues[i + len]) > -1)
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            nvc.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key

                cnt = nvc.Count;
                nvc.Remove(intlValues[i + len]);
                if (nvc.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item", i));
                }
                ks = nvc.AllKeys;
                if (Array.IndexOf(ks, intlValues[i + len]) > -1)
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            nvc.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // lowercase key

                cnt = nvc.Count;
                nvc.Remove(intlValuesLower[i + len]);
                if (nvc.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item using lowercase key", i));
                }
                ks = nvc.AllKeys;
                if (Array.IndexOf(ks, intlValues[i + len]) > -1)
                {
                    Assert.False(true, string.Format("Error, removed wrong item using lowercase key", i));
                }
            }


            //  [] Remove() on filled collection - with multiple items with the same key
            //

            nvc.Clear();
            len = values.Length;
            string k = "keykey";
            string k1 = "hm1";
            for (int i = 0; i < len; i++)
            {
                nvc.Add(k, "Value" + i);
                nvc.Add(k1, "iTem" + i);
            }
            if (nvc.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
            }

            nvc.Remove(k);
            if (nvc.Count != 1)
            {
                Assert.False(true, "Error, failed to remove item");
            }
            ks = nvc.AllKeys;
            if (Array.IndexOf(ks, k) > -1)
            {
                Assert.False(true, "Error, removed wrong item");
            }

            nvc.Remove(k1);
            if (nvc.Count != 0)
            {
                Assert.False(true, "Error, failed to remove item");
            }
            ks = nvc.AllKeys;
            if (Array.IndexOf(ks, k1) > -1)
            {
                Assert.False(true, "Error, removed wrong item");
            }


            //
            //  [] Remove(null) - when there is an item with null-key
            //
            cnt = nvc.Count;
            nvc.Add(null, "nullValue");
            if (nvc.Count != cnt + 1)
            {
                Assert.False(true, "Error, failed to add item with null-key");
            }
            if (nvc[null] == null)
            {
                Assert.False(true, "Error, didn't add item with null-key");
            }

            cnt = nvc.Count;
            nvc.Remove(null);
            if (nvc.Count != cnt - 1)
            {
                Assert.False(true, "Error, failed to remove item");
            }
            if (nvc[null] != null)
            {
                Assert.False(true, "Error, didn't remove item with null-key");
            }

            //
            //  [] Remove(null)   - when no item with null key
            //
            nvc.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            cnt = nvc.Count;

            nvc.Remove(null);
            if (nvc.Count != cnt)
            {
                Assert.False(true, "Error, removed something ");
            }
        }
Example #22
0
        public void Test01()
        {
            IntlStrings intl;
            NameValueCollection nvc;
            string[] vls;          // values collection

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count
            // [] initialize IntStrings
            intl = new IntlStrings();


            // [] NameValueCollection is constructed as expected
            //-----------------------------------------------------------------

            nvc = new NameValueCollection();

            // [] GetValues() on empty collection
            //
            if (nvc.GetValues(null) != null)
            {
                Assert.False(true, "Error, returned non-null");
            }
            if (nvc.GetValues("some_string") != null)
            {
                Assert.False(true, "Error, returned non-null");
            }

            // [] GetValues() on collection filled with simple strings
            //

            cnt = nvc.Count;
            int len = values.Length;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            if (nvc.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
            }
            //
            for (int i = 0; i < len; i++)
            {
                vls = nvc.GetValues(keys[i]);
                if (vls.Length != 1)
                {
                    Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
                }
                if (String.Compare(vls[0], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, vls[0], values[i]));
                }
            }


            //
            // Intl strings
            // [] GetValues() on collection filled with Intl strings
            //

            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }


            nvc.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);
            }
            if (nvc.Count != (len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                vls = nvc.GetValues(intlValues[i + len]);
                if (vls.Length != 1)
                {
                    Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
                }
                if (String.Compare(vls[0], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[0], intlValues[i]));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            nvc.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key
                vls = nvc.GetValues(intlValues[i + len]);
                if (vls.Length != 1)
                {
                    Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
                }
                if (String.Compare(vls[0], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[0], intlValues[i]));
                }

                // lowercase key
                vls = nvc.GetValues(intlValuesLower[i + len]);
                if (vls.Length != 1)
                {
                    Assert.False(true, string.Format("Error, returned number of strings {1} instead of 1", i, vls.Length));
                }
                if (String.Compare(vls[0], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[0], intlValues[i]));
                }

                if (!caseInsensitive && String.Compare(vls[0], intlValuesLower[i]) == 0)
                {
                    Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
                }
            }

            // [] GetValues() on filled collection - with multiple items with the same key
            //

            nvc.Clear();
            len = values.Length;
            string k = "keykey";
            string k1 = "hm1";
            string exp = "";
            string exp1 = "";
            for (int i = 0; i < len; i++)
            {
                nvc.Add(k, "Value" + i);
                nvc.Add(k1, "iTem" + i);
                if (i < len - 1)
                {
                    exp += "Value" + i + ",";
                    exp1 += "iTem" + i + ",";
                }
                else
                {
                    exp += "Value" + i;
                    exp1 += "iTem" + i;
                }
            }
            if (nvc.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
            }

            vls = nvc.GetValues(k);
            if (vls.Length != len)
            {
                Assert.False(true, string.Format("Error, returned number of strings {0} instead of {1}", vls.Length, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(vls[i], "Value" + i) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[i], "Value" + i));
                }
            }
            vls = nvc.GetValues(k1);
            if (vls.Length != len)
            {
                Assert.False(true, string.Format("Error, returned number of strings {0} instead of {1}", vls.Length, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(vls[i], "iTem" + i) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, vls[i], "iTem" + i));
                }
            }


            //
            //  [] GetValues(null) - when there is an item with null-key
            //
            cnt = nvc.Count;
            nvc.Add(null, "nullValue");

            vls = nvc.GetValues(null);
            if (vls.Length != 1)
            {
                Assert.False(true, string.Format("Error, returned number of strings {0} instead of {1}", vls.Length, 1));
            }
            if (String.Compare(vls[0], "nullValue") != 0)
            {
                Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", vls[0], "nullValue"));
            }

            //
            //  [] GetValues(null)   - when no item with null key
            //
            nvc.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }

            vls = nvc.GetValues(null);
            if (vls != null)
            {
                Assert.False(true, "Error, returned non-null ");
            }
        }
Example #23
0
        /// <summary>
        /// 馬情報をHTTPでPOSTする
        /// </summary>
        /// <param name="isError">エラーか</param>
        /// <param name="errorMessage">エラーメッセージ</param>
        /// <returns>POST結果</returns>
        public static string HttpPostUmaRelay(out bool isError, out string errorMessage)
        {
            string result = "";
            string url;
            string fileFormName;

            isError = false;
            errorMessage = string.Empty;

            NameValueCollection querystring = new NameValueCollection();
            CookieContainer cookies = new CookieContainer();

            if (SettingsClass.Setting.IsPost == true)
            {
                // 認証
                querystring["Fnc"] = "Login";
                querystring["Props"] = "/login/";
                querystring["USR"] = SettingsClass.Setting.PostUserName;
                querystring["PWD"] = SettingsClass.Setting.PostPassword;
                url = "http://www.umanushi.com/login/";
                result = WebUtilityClass.HttpPost(url, querystring, cookies);
                if (cookies.Count == 0)
                {
                    // 認証に失敗
                    isError = true;
                    errorMessage = string.Format("ログインに失敗しました。ユーザー名=[{1}]、パスワード=[{2}]",
                        url,
                        SettingsClass.Setting.PostUserName,
                        SettingsClass.Setting.PostPassword);
                    return result;
                }
                querystring.Clear();

                // 馬情報データ送信
                url = "http://www.umanushi.com/balister/admin/";
                fileFormName = "NEWBALISTERFILE";
                querystring["Fnc"] = "Update";
                querystring["Mode"] = "AddNewList";

                result = WebUtilityClass.HttpPostFile(url, new MemoryStream(System.Text.Encoding.GetEncoding("Shift-JIS").GetBytes(JVRelayClass.Output.ToString())),
                    @"c:\dummy.csv", fileFormName, "application/vnd.ms-excel", querystring, cookies);
            }

            return result;
        }
 /// <summary>
 /// Sets the user's UPN back to the onmicrosoft.com UPN, then set it back to the original again, fixes a lot of 
 /// "interesting" O365 issues (assumes adminusername domain is the onmicrosoft.com domain)
 /// </summary>
 public bool ResetUPN(string userupn)
 {
     bool result = false;
     if (adminusername.ToLower().EndsWith("onmicrosoft.com"))
     {
         string[] defaultDomainParts = adminusername.Split("@".ToCharArray());
         if (defaultDomainParts.Length == 2)
         {
             string defaultDomain = defaultDomainParts[1];
             using (CmdletExecutor cmdlet = new CmdletExecutor(adminusername, password, ToStringHints))
             {
                 cmdlet.LoginToOffice365();
                 NameValueCollection setparams = new NameValueCollection();
                 string error_output = "";
                 string onmicrosoft_upn = userupn.Split("@".ToCharArray())[0]+"@"+defaultDomain;
                 setparams.Add("UserPrincipalName",userupn);
                 setparams.Add("NewUserPrincipalName", onmicrosoft_upn);
                 cmdlet.ExecuteCommand("Set-MsolUserPrincipalName", setparams, PowershellType.MSOL, ref error_output);
                 if (error_output.Length <= 0)
                 {
                     // now set it back to normal
                     setparams.Clear();
                     setparams.Add("UserPrincipalName", onmicrosoft_upn);
                     setparams.Add("NewUserPrincipalName", userupn);
                     cmdlet.ExecuteCommand("Set-MsolUserPrincipalName", setparams, PowershellType.MSOL, ref error_output);
                     result = error_output.Length <= 0;
                 }
             }
         }
     }
     return result;
 }
Example #25
0
		public void ConstructorParameters ()
		{
			MemoryCache mc;
			AssertExtensions.Throws<ArgumentNullException> (() => {
				mc = new MemoryCache (null);
			}, "#A1");

			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache (String.Empty);
			}, "#A2");

			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("default");
			}, "#A3");

			var config = new NameValueCollection ();
			config.Add ("CacheMemoryLimitMegabytes", "invalid");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-1");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", "invalid");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-2");

			config.Clear ();
			config.Add ("PollingInterval", "invalid");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-3");

			config.Clear ();
			config.Add ("CacheMemoryLimitMegabytes", "-1");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-4");

			config.Clear ();
			config.Add ("CacheMemoryLimitMegabytes", UInt64.MaxValue.ToString ());
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-5");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", "-1");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-6");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", UInt64.MaxValue.ToString ());
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-7");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", UInt32.MaxValue.ToString ());
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-8");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", "-10");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-9");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", "0");
			// Just make sure it doesn't throw any exception
			mc = new MemoryCache ("MyCache", config);

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", "101");
			AssertExtensions.Throws<ArgumentException> (() => {
				mc = new MemoryCache ("MyCache", config);
			}, "#A4-10");

			// Just make sure it doesn't throw any exception
			config.Clear ();
			config.Add ("UnsupportedSetting", "123");
			mc = new MemoryCache ("MyCache", config);
		}
Example #26
0
        public LoginResult DoLogin()
        {
            var postData = new NameValueCollection();
            var cookies = _cookies;
            string response = null;

            if (cookies.Count == 0)
            {
                //Generate a SessionID
                cookies.Add(new Cookie("mobileClientVersion", "0 (2.1.3)", "/", ".steamcommunity.com"));
                cookies.Add(new Cookie("mobileClient", "android", "/", ".steamcommunity.com"));
                cookies.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com"));

                NameValueCollection headers = new NameValueCollection();
                headers.Add("X-Requested-With", "com.valvesoftware.android.steam.community");

                SteamWeb.MobileLoginRequest("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers);
            }

            postData.Add("username", this.Username);
            response = SteamWeb.MobileLoginRequest(APIEndpoints.COMMUNITY_BASE + "/login/getrsakey", "POST", postData, cookies);

            var rsaResponse = JsonConvert.DeserializeObject<RSAResponse>(response);

            if (!rsaResponse.Success)
            {
                return LoginResult.BadRSA;
            }

            RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider();
            byte[] encryptedPasswordBytes;
            using (var rsaEncryptor = new RSACryptoServiceProvider())
            {
                var passwordBytes = Encoding.ASCII.GetBytes(this.Password);
                var rsaParameters = rsaEncryptor.ExportParameters(false);
                rsaParameters.Exponent = Util.HexStringToByteArray(rsaResponse.Exponent);
                rsaParameters.Modulus = Util.HexStringToByteArray(rsaResponse.Modulus);
                rsaEncryptor.ImportParameters(rsaParameters);
                encryptedPasswordBytes = rsaEncryptor.Encrypt(passwordBytes, false);
            }

            string encryptedPassword = Convert.ToBase64String(encryptedPasswordBytes);

            postData.Clear();
            postData.Add("username", this.Username);
            postData.Add("password", encryptedPassword);

            postData.Add("twofactorcode", this.TwoFactorCode ?? "");

            postData.Add("captchagid", this.RequiresCaptcha ? this.CaptchaGID : "-1");
            postData.Add("captcha_text", this.RequiresCaptcha ? this.CaptchaText : "");

            postData.Add("emailsteamid", (this.Requires2FA || this.RequiresEmail) ? this.SteamID.ToString() : "");
            postData.Add("emailauth", this.RequiresEmail ? this.EmailCode : "");

            postData.Add("rsatimestamp", rsaResponse.Timestamp);
            postData.Add("remember_login", "false");
            postData.Add("oauth_client_id", "DE45CD61");
            postData.Add("oauth_scope", "read_profile write_profile read_client write_client");
            postData.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile");

            response = SteamWeb.MobileLoginRequest(APIEndpoints.COMMUNITY_BASE + "/login/dologin", "POST", postData, cookies);
            var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(response);

            if (loginResponse.CaptchaNeeded)
            {
                this.RequiresCaptcha = true;
                this.CaptchaGID = loginResponse.CaptchaGID;
                return LoginResult.NeedCaptcha;
            }

            if (loginResponse.EmailAuthNeeded)
            {
                this.RequiresEmail = true;
                this.SteamID = loginResponse.EmailSteamID;
                return LoginResult.NeedEmail;
            }

            if (loginResponse.TwoFactorNeeded && !loginResponse.Success)
            {
                this.Requires2FA = true;
                return LoginResult.Need2FA;
            }

            if (loginResponse.OAuthData == null || loginResponse.OAuthData.OAuthToken == null || loginResponse.OAuthData.OAuthToken.Length == 0)
            {
                return LoginResult.GeneralFailure;
            }

            if (!loginResponse.LoginComplete)
            {
                return LoginResult.BadCredentials;
            }
            else
            {
                var readableCookies = cookies.GetCookies(new Uri("https://steamcommunity.com"));
                var oAuthData = loginResponse.OAuthData;

                SessionData session = new SessionData();
                session.OAuthToken = oAuthData.OAuthToken;
                session.SteamID = oAuthData.SteamID;
                session.SteamLogin = session.SteamID + "%7C%7C" + oAuthData.SteamLogin;
                session.SteamLoginSecure = session.SteamID + "%7C%7C" + oAuthData.SteamLoginSecure;
                session.WebCookie = oAuthData.Webcookie;
                session.SessionID = readableCookies["sessionid"].Value;
                this.Session = session;
                this.LoggedIn = true;
                return LoginResult.LoginOkay;
            }

            return LoginResult.GeneralFailure;
        }
Example #27
0
        public List<int> GetFriends()
        {
            string reqURL = ConfigurationManager.AppSettings["FSQApi"] + "users/self/friends";
            var nv = new NameValueCollection();
            nv["oauth_token"] = token;
            string result = HttpGet(reqURL, nv);
            JObject obj = JObject.Parse(result);
            nv.Clear();

            int count = Convert.ToInt32(obj["response"]["friends"]["count"]);
            List<int> users = new List<int>();
            for (int i = 0; i < count; ++i)
            {
                int userId = Convert.ToInt32(obj["response"]["friends"]["items"][i]["id"]);
                users.Add(userId);
            }
            return users;
        }
		public HttpPostRequest(HttpListenerRequest request) {
			string[] contentTypeParts = request.ContentType.Split(';');
			foreach(string contentTypePart in contentTypeParts) {
				Match contentTypePartMatch = Regex.Match(contentTypePart, "(multipart\\/form-data|application\\/x-www-form-urlencoded)", RegexOptions.Compiled);
				Match boundaryMatch = Regex.Match(contentTypePart, "boundary=(.+)", RegexOptions.Compiled);
				if (contentTypePartMatch.Success) {
					this._encType = contentTypePartMatch.Groups[1].Value;
				} else if (boundaryMatch.Success) {
					this._boundary = boundaryMatch.Groups[1].Value.Trim();
				}
			}

			//SConsole.WriteLine("EncodingType: " + this.EncodingType + "; Boundary: " + this.Boundary);
			if (this.EncodingType == "application/x-www-form-urlencoded") {
				using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding)) {
					string queryString = reader.ReadToEnd();
					this._parameters = HttpUtility.ParseQueryString(queryString, request.ContentEncoding);
				}
			} else if (this.EncodingType == "multipart/form-data" && this.Boundary != String.Empty) {
				long requestLength = -1, currentPosition = 0;

				try {
					requestLength = request.InputStream.Length;
				} catch(NotSupportedException) {
					//Console.WriteLine("NotSupportedException: " + e.Message);
					requestLength = request.ContentLength64;
				}

				if (requestLength == -1) {
					Console.WriteLine("ungültige RequestLength");
					return;
				} else if (requestLength == 0) {
					Console.WriteLine("RequestLength == 0");
					return;
				}

				int iByte = -1;
				byte[] buffer = new byte[requestLength];
				byte lastByte;
				UTF8Encoding enc = new UTF8Encoding();
				byte[] boundaryBytes = enc.GetBytes(this.Boundary);
				List<byte> headerBufferList = new List<byte>();
				List<byte> contentBufferList = new List<byte>();
				NameValueCollection currentHeader = new NameValueCollection();

				bool boundaryFound = false, headerStarted = false, contentStarted = false;

				iByte = request.InputStream.ReadByte();
				while(iByte != -1 && currentPosition < requestLength) {
					lastByte = Convert.ToByte(iByte);
					buffer[currentPosition] = lastByte;
					if (currentPosition + 1 >= boundaryBytes.Length) {
						if (buffer[currentPosition] == boundaryBytes[boundaryBytes.Length - 1]) {
							byte[] bytesToCompare = new byte[boundaryBytes.Length];
							Array.Copy(buffer, currentPosition - boundaryBytes.Length + 1, bytesToCompare, 0, boundaryBytes.Length);
							if (this.ByteArrayEquals(bytesToCompare, boundaryBytes)) {
								if (contentStarted) {
									if (currentHeader["name"] != null) {
										contentBufferList.RemoveAt(0);
										contentBufferList.RemoveRange(contentBufferList.Count - (boundaryBytes.Length + 3), boundaryBytes.Length + 3);
										if (currentHeader["filename"] != null) {
											byte[] contentBufferArray = contentBufferList.ToArray();
											string hash = currentHeader["filename"];
											using(SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
												hash = Convert.ToBase64String(sha1.ComputeHash(contentBufferArray));
											}
											string tempFilename = "/tmp/" + hash;
											Match filenameMatch = Regex.Match(currentHeader["filename"], "\\.([^\\.]+)$", RegexOptions.Compiled);
											if (filenameMatch.Success) {
												tempFilename += "." + filenameMatch.Groups[1].Value;
											}

											File.WriteAllBytes(tempFilename, contentBufferArray);
											if (File.Exists(tempFilename)) {
												FileInfo fileInfo = new FileInfo(tempFilename);
												string contentType = (currentHeader["Content-Type"] != null) ? currentHeader["Content-Type"] : "";
												HttpPostFile postFile = new HttpPostFile(currentHeader["filename"], tempFilename, fileInfo.Length, contentType);
												this._files.Add(currentHeader["name"], postFile);
											}
										} else {
											this._parameters.Add(currentHeader["name"], enc.GetString(contentBufferList.ToArray()));
										}
									}
								}

								headerBufferList.Clear();
								contentBufferList.Clear();
								boundaryFound = true;
								headerStarted = false;
								contentStarted = false;
							}
						}
					}

					if (lastByte == '\n' && currentPosition > 0 && buffer[currentPosition - 1] == '\r') {
						if (boundaryFound && !headerStarted) {
							headerBufferList.Clear();
							currentHeader.Clear();
							headerStarted = true;
						}
						if (!contentStarted && currentPosition > 3 && buffer[currentPosition - 3] == '\r' && buffer[currentPosition - 2] == '\n') {
							string[] headerStringParts = enc.GetString(headerBufferList.ToArray()).Trim().Split('\n');
							foreach(string headerString in headerStringParts) {
								string[] splittedHeaderString = headerString.Split(';');
								foreach(string splittedHeader in splittedHeaderString) {
									string currentHeaderInfo = splittedHeader.Trim();
									if (currentHeaderInfo != String.Empty) {
										Match headerContentInfoMatch = Regex.Match(currentHeaderInfo, "([^:]+):\\s*([^\\s]+)", RegexOptions.Compiled);
										if (headerContentInfoMatch.Success) {
											currentHeader.Add(headerContentInfoMatch.Groups[1].Value, headerContentInfoMatch.Groups[2].Value);
										} else {
											Match headerNameValueMatch = Regex.Match(currentHeaderInfo, "([^=]+)=\"([^\"]+)\"", RegexOptions.Compiled);
											if (headerNameValueMatch.Success) {
												currentHeader.Add(headerNameValueMatch.Groups[1].Value, headerNameValueMatch.Groups[2].Value);
											}
										}
									}
								}
							}

							headerBufferList.Clear();
							contentStarted = true;
						}
					}

					if (boundaryFound) {
						if (contentStarted) {
							contentBufferList.Add(lastByte);
						} else if (headerStarted) {
							headerBufferList.Add(lastByte);
						}
					}

					currentPosition++;
					iByte = request.InputStream.ReadByte();
				}
			}
		}
Example #29
0
        public void Test01()
        {
            IntlStrings intl;
            NameValueCollection nvc;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();


            // [] NameValueCollection is constructed as expected
            //-----------------------------------------------------------------

            nvc = new NameValueCollection();
            cnt = nvc.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after default ctor", nvc.Count, 0));
            }

            // [] Clear() on empty collection
            //
            nvc.Clear();
            cnt = nvc.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", nvc.Count, 0));
            }


            // [] Add simple strings and Clear()
            //
            cnt = nvc.Count;
            for (int i = 0; i < values.Length; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            if (nvc.Count != values.Length)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
            }

            nvc.Clear();
            cnt = nvc.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", nvc.Count, 0));
            }


            //
            // [] Add Intl strings and Clear()
            //
            int len = values.Length;
            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            //   Add items
            //
            cnt = nvc.Count;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);
            }
            if (nvc.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + len));
            }

            nvc.Clear();
            cnt = nvc.Count;
            if (cnt != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", nvc.Count, 0));
            }
        }
Example #30
0
		public void ConstructorValues ()
		{
			var config = new NameValueCollection ();
			config.Add ("PhysicalMemoryLimitPercentage", "0");
			config.Add ("CacheMemoryLimitMegabytes", "1");
			config.Add ("pollingInterval", "00:10:00");

			var mc = new MemoryCache ("MyCache", config);
			Assert.AreEqual (98, mc.PhysicalMemoryLimit, "#A1");
			Assert.AreEqual (1048576, mc.CacheMemoryLimit, "#A2");
			Assert.AreEqual (TimeSpan.FromMinutes (10), mc.PollingInterval, "#A3");

			config.Clear ();
			config.Add ("PhysicalMemoryLimitPercentage", "10");
			config.Add ("CacheMemoryLimitMegabytes", "5");
			config.Add ("PollingInterval", "01:10:00");

			mc = new MemoryCache ("MyCache", config);
			Assert.AreEqual (10, mc.PhysicalMemoryLimit, "#B1");
			Assert.AreEqual (5242880, mc.CacheMemoryLimit, "#B2");
			Assert.AreEqual (TimeSpan.FromMinutes (70), mc.PollingInterval, "#B3");
		}
Example #31
0
		public void Clear ()
		{
			NameValueCollection c = new NameValueCollection ();
			Assert.AreEqual (0, c.Count, "#1");
			c.Add ("foo1", "bar1");
			Assert.AreEqual (1, c.Count, "#2");
			c.Clear ();
			Assert.AreEqual (0, c.Count, "#3");
		}
Example #32
0
        public void Test01()
        {
            IntlStrings intl;
            NameValueCollection nvc;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();


            // [] NameValueCollection is constructed as expected
            //-----------------------------------------------------------------

            nvc = new NameValueCollection();

            // [] add simple strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                cnt = nvc.Count;
                nvc.Add(keys[i], values[i]);
                if (nvc.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (Array.IndexOf(nvc.AllKeys, keys[i]) < 0)
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                //  access the item
                //
                if (String.Compare(nvc[keys[i]], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[keys[i]], values[i]));
                }
            }

            //
            // Intl strings
            // [] add Intl strings
            //
            int len = values.Length;
            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }


            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                cnt = nvc.Count;

                nvc.Add(intlValues[i + len], intlValues[i]);
                if (nvc.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                //  access the item
                //
                if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
                }
            }

            //
            // [] Case sensitivity
            // Casing doesn't change ( keya are not converted to lower!)
            //
            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            nvc.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                cnt = nvc.Count;

                nvc.Add(intlValues[i + len], intlValues[i]);
                if (nvc.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
                }

                // verify that collection contains newly added uppercase item
                //
                if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
                }

                //  access the item
                //
                if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
                }

                // verify that collection doesn't contains lowercase item
                //
                if (!caseInsensitive && String.Compare(nvc[intlValuesLower[i + len]], intlValuesLower[i]) == 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" is lowercase after adding uppercase", i, nvc[intlValuesLower[i + len]]));
                }

                // key is not converted to lower
                if (!caseInsensitive && Array.IndexOf(nvc.AllKeys, intlValuesLower[i + len]) >= 0)
                {
                    Assert.False(true, string.Format("Error, key was converted to lower", i));
                }

                // but search among keys is case-insensitive
                if (String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, could not find item using differently cased key", i));
                }
            }

            //
            //  [] Add multiple values with the same key
            //

            nvc.Clear();
            len = values.Length;
            string k = "keykey";

            for (int i = 0; i < len; i++)
            {
                nvc.Add(k, "Value" + i);
            }
            if (nvc.Count != 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of 1}", nvc.Count));
            }

            if (nvc.AllKeys.Length != 1)
            {
                Assert.False(true, "Error, should contain only 1 key");
            }

            // verify that collection contains newly added item
            //
            if (Array.IndexOf(nvc.AllKeys, k) < 0)
            {
                Assert.False(true, "Error, collection doesn't contain key of new item");
            }

            //  access the item
            //
            string[] vals = nvc.GetValues(k);
            if (vals.Length != len)
            {
                Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, len));
            }

            for (int i = 0; i < len; i++)
            {
                if (Array.IndexOf(vals, "Value" + i) < 0)
                {
                    Assert.False(true, string.Format("Error, doesn't contain {1}", i, "Value" + i));
                }
            }

            //
            // [] Add null value
            //

            cnt = nvc.Count;
            k = "kk";
            nvc.Add(k, null);

            if (nvc.Count != cnt + 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
            }

            if (Array.IndexOf(nvc.AllKeys, k) < 0)
            {
                Assert.False(true, "Error, collection doesn't contain key of new item");
            }

            // verify that collection contains null
            //
            if (nvc[k] != null)
            {
                Assert.False(true, "Error, returned non-null on place of null");
            }

            //
            // [] Add item with null key
            // Add item with null key - NullReferenceException expected
            //

            cnt = nvc.Count;

            nvc.Add(null, "item");

            if (nvc.Count != cnt + 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
            }

            if (Array.IndexOf(nvc.AllKeys, null) < 0)
            {
                Assert.False(true, "Error, collection doesn't contain null key ");
            }

            // verify that collection contains null
            //
            if (nvc[null] != "item")
            {
                Assert.False(true, "Error, returned wrong value at null key");
            }
        }
Example #33
0
        public void Test01()
        {
            IntlStrings intl;


            NameValueCollection nvc;
            NameValueCollection nvc1;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();


            // [] NameValueCollection is constructed as expected
            //-----------------------------------------------------------------

            nvc = new NameValueCollection();
            nvc1 = new NameValueCollection();

            // [] Add(empty_coll) to empty collection
            //
            nvc.Clear();
            nvc1.Clear();
            nvc.Add(nvc1);
            if (nvc.Count != 0)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of 0", nvc.Count));
            }

            // [] Add(simple_strings_coll) to empty collection
            //

            nvc.Clear();
            cnt = nvc.Count;
            int len = values.Length;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            if (nvc.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
            }

            nvc1.Clear();
            nvc1.Add(nvc);
            if (nvc1.Count != nvc.Count)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, nvc.Count));
            }
            //
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1[keys[i]], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
                }
            }

            // [] Add(simple_strings_coll) to simple_string_collection
            //

            len = values.Length;
            if (nvc.Count < len)
            {
                nvc.Clear();
                for (int i = 0; i < len; i++)
                {
                    nvc.Add(keys[i], values[i]);
                }
            }
            nvc1.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc1.Add("k" + i, "v" + i);
            }

            cnt = nvc1.Count;
            nvc1.Add(nvc);
            if (nvc1.Count != cnt + nvc.Count)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, cnt + nvc.Count));
            }
            //
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1[keys[i]], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
                }
                if (String.Compare(nvc1["k" + i], "v" + i) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc["k" + i], "v" + i));
                }
            }


            //
            // Intl strings
            // [] Add(intl_strings_coll) to empty collection
            //

            string[] intlValues = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            Boolean caseInsensitive = false;
            for (int i = 0; i < len * 2; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
                    caseInsensitive = true;
            }


            // fill init collection with intl strings
            nvc.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);
            }
            if (nvc.Count != (len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
            }

            // add filled collection to tested empty collection
            nvc1.Clear();
            nvc1.Add(nvc);

            for (int i = 0; i < len; i++)
            {
                //
                if (String.Compare(nvc1[intlValues[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc1[intlValues[i + len]], intlValues[i]));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpperInvariant();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLowerInvariant();
            }

            nvc.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                nvc.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            // add uppercase to tested collection
            nvc1.Clear();
            nvc1.Add(nvc);

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key
                if (String.Compare(nvc1[intlValues[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc1[intlValues[i + len]], intlValues[i]));
                }

                // lowercase key
                if (String.Compare(nvc1[intlValuesLower[i + len]], intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc1[intlValuesLower[i + len]], intlValues[i]));
                }

                if (!caseInsensitive && (String.Compare(nvc1[intlValues[i + len]], intlValuesLower[i]) == 0))
                {
                    Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
                }
            }

            //
            // when adding values with existing keys, values should be added to existing values
            // [] Add(NVC) with already existing keys
            //

            nvc.Clear();
            cnt = nvc.Count;
            len = values.Length;
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], values[i]);
            }
            if (nvc.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
            }

            nvc1.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc1.Add(keys[i], values[i]);
            }
            if (nvc1.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, values.Length));
            }
            cnt = nvc1.Count;

            nvc1.Add(nvc);
            // count should not change
            if (nvc1.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, cnt));
            }
            //  values should be added to previously existed values
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1[keys[i]], values[i] + "," + values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i] + "," + values[i]));
                }
            }

            // [] multiple items with same key
            //

            nvc.Clear();
            len = values.Length;
            string k = "keykey";
            string k1 = "hm1";
            string exp = "";
            string exp1 = "";
            for (int i = 0; i < len; i++)
            {
                nvc.Add(k, "Value" + i);
                nvc.Add(k1, "iTem" + i);
                if (i < len - 1)
                {
                    exp += "Value" + i + ",";
                    exp1 += "iTem" + i + ",";
                }
                else
                {
                    exp += "Value" + i;
                    exp1 += "iTem" + i;
                }
            }
            if (nvc.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
            }

            // add NVC
            nvc1.Clear();
            nvc1.Add(nvc);

            if (String.Compare(nvc1[k], exp) != 0)
            {
                Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc1[k], exp));
            }

            // Values array should contain len items
            if (nvc1.GetValues(k).Length != len)
            {
                Assert.False(true, string.Format("Error, number of values is {0} instead of {1}", nvc1.GetValues(k).Length, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1.GetValues(k)[i], "Value" + i) != 0)
                {
                    Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, nvc1.GetValues(k)[i], "Value" + i));
                }
            }

            if (String.Compare(nvc1[k1], exp1) != 0)
            {
                Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc1[k1], exp1));
            }
            // Values array should contain len items
            if (nvc1.GetValues(k1).Length != len)
            {
                Assert.False(true, string.Format("Error, number of values is {0} instead of {1}", nvc1.GetValues(k1).Length, len));
            }
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1.GetValues(k1)[i], "iTem" + i) != 0)
                {
                    Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, nvc1.GetValues(k1)[i], "iTem" + i));
                }
            }


            //
            //  [] Add(with_null_key) when there is item with null key
            //
            cnt = nvc.Count;
            nvc.Add(null, "nullValue");
            nvc1[null] = "nullValue1";

            nvc1.Add(nvc);
            if (String.Compare(nvc1[null], "nullValue1," + nvc[null]) != 0)
            {
                Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc1[null], "nullValue1," + nvc[null]));
            }

            //
            //  [] Add(with_null_key) when there is no item with null key
            //
            nvc.Clear();
            nvc1.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc1.Add(keys[i], values[i]);
            }
            nvc[null] = "newNullValue";

            nvc1.Add(nvc);
            if (String.Compare(nvc1[null], "newNullValue") != 0)
            {
                Assert.False(true, "Error, returned unexpected value ");
            }

            //
            //  [] Add(null_collection)
            //
            try
            {
                nvc1.Add(null);
                Assert.False(true, "Error, no exception");
            }
            catch (ArgumentNullException)
            {
            }
            catch (Exception e)
            {
                Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
            }

            //
            //  [] Add(empty_coll) to filled collection
            //

            nvc.Clear();
            if (nvc1.Count < len)
            {
                nvc1.Clear();
                for (int i = 0; i < len; i++)
                {
                    nvc1.Add(keys[i], values[i]);
                }
                if (nvc1.Count != len)
                {
                    Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, values.Length));
                }
            }

            cnt = nvc1.Count;
            nvc1.Add(nvc);
            if (nvc1.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count has changed: {0} instead of {1}", nvc1.Count, cnt));
            }
            //   verify that collection has not changed
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1[keys[i]], values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
                }
            }


            //
            //  [] Add collection with null values
            //
            nvc.Clear();
            nvc1.Clear();
            for (int i = 0; i < len; i++)
            {
                nvc.Add(keys[i], null);
            }

            nvc1.Add(nvc);
            if (nvc1.Count != nvc.Count)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, nvc.Count));
            }
            //
            for (int i = 0; i < len; i++)
            {
                if (String.Compare(nvc1[keys[i]], null) != 0)
                {
                    Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
                }
            }
        }