Set() public method

public Set ( String name, String value ) : void
name String
value String
return void
Example #1
0
        static public System.Collections.Specialized.NameValueCollection ReadIni(string sFileName)
        {
            System.Collections.Specialized.NameValueCollection coll = null;
            string sTxt = cc.Util.readAll(sFileName);

            if (sTxt != null)
            {
                coll = new System.Collections.Specialized.NameValueCollection();
                string[] lines = sTxt.Replace("\n", "").Split('\r');
                for (int i = 0; i < lines.Length; i++)
                {
                    string line = lines[i].Trim();
                    if (line.Equals("") || line.StartsWith("#") || line.StartsWith(";"))
                    {
                        continue;
                    }

                    int npos;
                    npos = line.IndexOf("=");
                    if (npos > 0)
                    {
                        string skey = line.Substring(0, npos);
                        if (coll.Get(skey) != null)
                        {
                            coll.Set(skey, coll.Get(skey) + "\r\n" + line.Substring(npos + 1));
                        }
                        else
                        {
                            coll.Set(skey, line.Substring(npos + 1));
                        }
                    }
                }
            }
            return(coll);
        }
 public void ToModelTest()
 {
     var collection = new NameValueCollection();
     collection.Set("DecimalNullableValue", "");
     collection.Set("DecimalValue", "10");
     var model = HttpRequestExtension.ToModel(collection, new NullableModel()) as NullableModel;
     Assert.AreEqual(null, model.DecimalNullableValue);
     Assert.AreEqual(10, model.DecimalValue);
 }
Example #3
0
        public void SubComplexPropertyIndexFormat()
        {
            NameValueCollection nv = new NameValueCollection();
            nv.Set("IP", "192.168.8.91");
            nv.Set("UserName", "wangqj");

            ComplexObject obj = new ComplexObject { Headers = nv };
            string htmlContent = new MailTemplet(@"Hello,{Request.Headers[""IP""].Length}, TotalCount:{Request.Headers.Count}!").SetVariable("Request", obj)
               .ToHtmlContent();

            //Console.Write(htmlContent);
            Debug.Assert(htmlContent.Equals("Hello,12, TotalCount:2!"));
        }
        public void TestFedeo()
        {
            XmlSerializer ser = new XmlSerializer(typeof(OpenSearchDescription));
            var osd = (OpenSearchDescription)ser.Deserialize(XmlReader.Create(new FileStream("../Samples/fedeo-osdd.xml", FileMode.Open, FileAccess.Read)));

            GenericOpenSearchable os = new GenericOpenSearchable(osd, new OpenSearchEngine());

            OpenSearchEngine ose = new OpenSearchEngine();
            ose.LoadPlugins();

            var url = new OpenSearchUrl("http://fedeo.esa.int/opensearch/request/?httpAccept=application/atom%2Bxml&parentIdentifier=urn:eop:DLR:EOWEB:Geohazard.Supersite.TerraSAR-X_SSC&startDate=2014-01-01T00:00:00Z&endDate=2015-04-20T00:00:00Z&recordSchema=om");
            NameValueCollection parameters = new NameValueCollection();
            parameters.Set("maximumRecords", "1");

            NameValueCollection nvc;
            if (url != null)
                nvc = HttpUtility.ParseQueryString(url.Query);
            else
                nvc = new NameValueCollection();

            parameters.AllKeys.SingleOrDefault(k =>
            {
                nvc.Set(k, parameters[k]);
                return false;
            });

            var request = OpenSearchRequest.Create(os, os.GetQuerySettings(ose), nvc);
        }
		public string PublishAction(string action, string objectType, string objectUrl)
		{
			requireAuthorization();
			NameValueCollection parameters = new NameValueCollection();
			parameters.Set(objectType, objectUrl);
			return this.Publish("me", this.applicationNamespace + ":" + action, parameters);
		}
Example #6
0
        internal static void SendNotifications(IEnumerable<string> apiKeys, string application, string header, string message)
        {
            var data = new NameValueCollection();
            data["AuthorizationToken"] = "";
            data["Body"] = message;
            data["IsImportant"] = IsImportant;
            data["IsSilent"] = IsSilent;
            data["Source"] = application;
            data["TimeToLive"] = TimeToLive;
            data["Title"] = header;
            if (!Validate(data))
            {
                return;
            }

            foreach (var apiKey in apiKeys)
            {
                using (var client = new WebClient())
                {
                    data.Set("AuthorizationToken", apiKey);

                    client.Headers[HttpRequestHeader.ContentType] = RequestContentType;
                    client.UploadValuesAsync(new Uri(RequestUrl), data);
                }
            }
        }
        public void ExpectedRavenDbCallsAreMade()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);
            object lockId = 0;

            string providedSessionId = "A sessionId";

            SessionStateDocument sessionObject = TestSessionDocumentFactory.CreateSessionStateDocument(providedSessionId, expectedAppName);
            sessionObject.Expiry = DateTime.UtcNow.AddDays(1);

            var sessionItems = new SessionStateItemCollection();

            sessionItems["ACar"] = new Car("A6", "Audi");

            sessionObject.SessionItems = subject.Serialize(sessionItems);

            SessionStateStoreData item = RavenSessionStateStoreProvider.Deserialize(null, sessionObject.SessionItems, 10);

            MockDocumentSession.Setup(cmd => cmd.Store(It.IsAny<SessionStateDocument>())).Verifiable();
            MockDocumentSession.Setup(cmd => cmd.SaveChanges()).Verifiable();

            subject.Initialize("A name", keyPairs, MockDocumentStore.Object);

            // Act
            subject.CreateUninitializedItem(new HttpContext(new SimpleWorkerRequest("", "", "", "", new StringWriter())), providedSessionId, 10);

            // Assert
            MockDocumentSession.Verify(cmd => cmd.Store(It.IsAny<SessionStateDocument>()), Times.Once());
            MockDocumentSession.Verify(cmd => cmd.SaveChanges(), Times.Once());
        }
        public void DocumentStoreNotProvided_ValidConnectionStringDoesNotThrowConfigurationErrorsException()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            string connectionStringName = "AConnectionString";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);
            keyPairs.Set("connectionStringName", connectionStringName);

            // Act
            TestDelegate act = () => subject.Initialize("", keyPairs, null);

            // Assert
            Assert.DoesNotThrow(act, "null connection string should throw configuration errors");
        }
        public void DocumentStoreNotProvided_ValidConnectionStringEnsuresDocumentStoreCreated()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            string connectionStringName = "AConnectionString";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);
            keyPairs.Set("connectionStringName", connectionStringName);

            IDocumentStore docStore = null;

            // Act
            subject.Initialize("", keyPairs, docStore);

            // Assert
            Assert.IsNotNull(subject.DocumentStore);
        }
        public void ConfigNotProvidedThrowsArgumentNullException()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            string connectionStringName = "AConnectionString";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);
            keyPairs.Set("connectionStringName", connectionStringName);

            IDocumentStore docStore = null;

            // Act
            TestDelegate act = () => subject.Initialize("", null, docStore);

            // Assert
            Assert.Throws<ArgumentNullException>(act, "Config cannot be null");
        }
Example #11
0
 public static string UrlSet(this HtmlHelper helper, HttpRequestBase request, string queryName, object queryValue)
 {
     if (queryName != null && queryValue != null)
     {
         string path = request.Path;
         NameValueCollection query = new NameValueCollection(request.QueryString);
         query.Set(queryName, queryValue.ToString());
         return CreateUrl(path, query);
     }
     return request.RawUrl;
 }
Example #12
0
        public object Delete(TypeDeleteRequest request)
        {
            IOpenSearchableElasticType type = ecf.GetOpenSearchableElasticTypeByNameOrDefault(request.IndexName, request.TypeName);
            NameValueCollection parameters = new NameValueCollection();
            parameters.Set("uid", request.Id);
            var results = OpenSearchService.QueryResult(type, parameters);

            var response = Delete(type, results);

            return new HttpResult(response, "application/json");
        }
Example #13
0
 /// <summary>
 /// 读取文件中的键值对,加载进内存集合
 /// </summary>
 /// <param name="doc">文档对象模型</param>
 /// <param name="mv">键值对集合</param>
 public static void SetNameValues(XmlDocument doc,NameValueCollection mv)
 {
     XmlElement root = doc.DocumentElement;
     foreach (XmlNode node in root.ChildNodes)
     {
         if (node.Attributes != null && node.Attributes["key"].Value != null)
         {
             string key = node.Attributes["key"].Value.ToString();
             string value = node.Attributes["value"].Value.ToString();
             mv.Set(key, value);
         }
     }
 }
        public object Get(OpenSearchQueryRequest request)
        {
            IOpenSearchableElasticType type = ecf.GetOpenSearchableElasticTypeByNameOrDefault(request.IndexName, request.TypeName);

            NameValueCollection parameters = new NameValueCollection(Request.QueryString);
            if (request.AdditionalParameters != null) {
                foreach (var key in request.AdditionalParameters.AllKeys) {
                    parameters.Set(key, request.AdditionalParameters[key]);
                }
            }

            return OpenSearchService.Query(type, parameters);
        }
        public void WhenAttributeIsEmptyNameSetToHostingEnvironmentApplicationPath()
        {
            // Arrange
            string expectedAppPath = "ABC its easy as 123";
            var subject = TestStoreProviderFactory.SetupStoreProvider(expectedAppPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", string.Empty);

            // Act
            subject.Initialize("", keyPairs, MockDocumentStore.Object);

            // Assert
            Assert.AreEqual(expectedAppPath, subject.ApplicationName);
        }
        public void WhenAttributeIsWhitespaceNameSetToHostingEnvironmentApplicationPath()
        {
            // Arrange
            string expectedAppPath = "Candy Girl you are my world";
            var subject = TestStoreProviderFactory.SetupStoreProvider(expectedAppPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", "   ");

            // Act
            subject.Initialize("", keyPairs, MockDocumentStore.Object);

            // Assert
            Assert.AreEqual(expectedAppPath, subject.ApplicationName);
        }
        public void InjectSecretsInto(NameValueCollection collection)
        {
            var secretReader = _secretReaderFactory.CreateSecretReader();
            var secretInjector = _secretReaderFactory.CreateSecretInjector(secretReader);

            IEnumerable keys = new List<string>(collection.AllKeys);

            foreach (string key in keys)
            {
                var framedString = collection[key];
                var newValue = secretInjector.InjectAsync(framedString).Result;
                collection.Set(key, newValue);
            }
        }
        public void WhenAttributeIsProvidedNameSetToProvidedAttribute()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);

            // Act
            subject.Initialize("", keyPairs, MockDocumentStore.Object);

            // Assert
            Assert.AreEqual(expectedAppName, subject.ApplicationName);
        }
        public void NullSessionStoreDataItemThrowsArgumentNullException()
        {
            // Arrange & Act
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);

            TestDelegate act =
                () =>
                    subject.SetAndReleaseItemExclusive(new HttpContext(new SimpleWorkerRequest("", "", "", "", new StringWriter())), "A sessionId", null, new object(), true);

            // Assert
            Assert.Throws<ArgumentNullException>(act, "SessionStateStoreData item cannot be null");
        }
        public static string EntrySelfLinkTemplate(IOpenSearchResultItem item, OpenSearchDescription osd, string mimeType)
        {
            if (item == null)
                return null;

            string identifier = item.Identifier;

            NameValueCollection nvc = new NameValueCollection();

            nvc.Set("q", string.Format("_id:{0}", item.Identifier));

            UriBuilder template = new UriBuilder(OpenSearchFactory.GetOpenSearchUrlByType(osd, mimeType).Template);
            string[] queryString = Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", key, nvc[key]));
            template.Query = string.Join("&", queryString);
            return template.ToString();
        }
        /// <summary>
        /// Load configuration from an XML document.
        /// </summary>
        /// <param name="doc">The XML document containing configuration.</param>
        static void LoadConfiguration()
        {
            appSettings = new NameValueCollection();
            if(!File.Exists("App.config"))
                return;
            var doc = XDocument.Load(File.OpenRead("App.config"));
            foreach (XElement element in doc.Element("configuration").Elements("appSettings").Elements("add"))
            {
                if(element.Name.LocalName == "add")
                {
                    var key = 	element.Attribute("key").Value;
                    var value = element.Attribute("value").Value;
                    appSettings.Set(key,value);
                }

            }
        }
        public void DocumentStoreIsDisposedWhenItExists()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);

            subject.Initialize("A name", keyPairs, MockDocumentStore.Object);

            // Act
            subject.Dispose();

            // Assert
            MockDocumentStore.Verify(cmd => cmd.Dispose(), Times.Once());
        }
        public static AuthorizationContext GetAuthorizationContext(string cookieValue, string formValue)
        {
            HttpCookieCollection requestCookies = new HttpCookieCollection();
            NameValueCollection formCollection = new NameValueCollection();

            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();
            mockAuthContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/SomeAppPath");
            mockAuthContext.Expect(c => c.HttpContext.Request.Cookies).Returns(requestCookies);
            mockAuthContext.Expect(c => c.HttpContext.Request.Form).Returns(formCollection);

            if (!String.IsNullOrEmpty(cookieValue)) {
                requestCookies.Set(new HttpCookie(_antiForgeryTokenCookieName, cookieValue));
            }
            if (!String.IsNullOrEmpty(formValue)) {
                formCollection.Set(AntiForgeryData.GetAntiForgeryTokenName(null), formValue);
            }

            return mockAuthContext.Object;
        }
        /// <summary>
        /// Builds the request URL for template.
        /// </summary>
        /// <returns>The request URL for template.</returns>
        /// <param name="remoteUrlTemplate">Remote URL template.</param>
        /// <param name="searchParameters">Search parameters.</param>
        public static OpenSearchUrl BuildRequestUrlForTemplate(OpenSearchDescriptionUrl remoteUrlTemplate, NameValueCollection searchParameters, QuerySettings querySettings)
        {
            // container for the final query url
            UriBuilder finalUrl = new UriBuilder(remoteUrlTemplate.Template);
            // parameters for final query
            NameValueCollection finalQueryParameters = new NameValueCollection();

            // Parse the possible parametrs of the remote urls
            NameValueCollection remoteParametersDef = HttpUtility.ParseQueryString(finalUrl.Query);

            // For each parameter requested
            foreach (string parameter_id in searchParameters.AllKeys) {
                if (remoteParametersDef[parameter_id] == null)
                {
                    // if forced, set the param
                    if (querySettings.ForceUnspecifiedParameters)
                    {
                        if (!(querySettings.SkipNullOrEmptyQueryStringParameters && string.IsNullOrEmpty(searchParameters[parameter_id])))
                            finalQueryParameters.Set(parameter_id, searchParameters[parameter_id]);
                    }
                    continue;
                }
                // first find the defintion of the parameter in the url template
                foreach (var key in remoteParametersDef.GetValues(parameter_id)) {
                    Match matchParamDef = Regex.Match(key, @"^{([^?]+)\??}$");
                    // If parameter does not exist, continue
                    if (!matchParamDef.Success)
                        continue;
                    // We have the parameter defintion
                    string paramDef = matchParamDef.Groups[1].Value;
                    string paramValue = searchParameters[parameter_id];

                    if ( !(querySettings.SkipNullOrEmptyQueryStringParameters && string.IsNullOrEmpty(paramValue)))
                        finalQueryParameters.Set(parameter_id, paramValue);
                }

            }

            string[] queryString = Array.ConvertAll(finalQueryParameters.AllKeys, key => string.Format("{0}={1}", key, HttpUtility.UrlEncode(finalQueryParameters[key])));
            finalUrl.Query = string.Join("&", queryString);

            return new OpenSearchUrl(finalUrl.Uri);
        }
        public void GetItemReturnsExpectedSessionStateStoreDataWhenItemHasNotExpired()
        {
            // Arrange
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);

            bool locked = false;
            TimeSpan lockAge = new TimeSpan();
            SessionStateActions actions = new SessionStateActions();
            object lockId = null;

            string providedSessionId = "A sessionId";

            SessionStateDocument sessionObject = TestSessionDocumentFactory.CreateSessionStateDocument(providedSessionId, expectedAppName);
            sessionObject.Expiry = DateTime.UtcNow.AddDays(1);

            var sessionItems = new SessionStateItemCollection();

            sessionItems["ACar"] = new Car("A6", "Audi");

            sessionObject.SessionItems  = subject.Serialize(sessionItems);

            MockDocumentSession.Setup(cmd => cmd.Load<SessionStateDocument>(SessionStateDocument.GenerateDocumentId(providedSessionId, expectedAppName))).Returns(sessionObject);

            subject.Initialize("A name", keyPairs, MockDocumentStore.Object);

            // Act
            var result =
                    subject.GetItem(new HttpContext(new SimpleWorkerRequest("", "", "", "", new StringWriter())), "A sessionId", out locked, out lockAge, out lockId , out actions );

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(1, result.Items.Count);
            Assert.IsInstanceOf<Car>(result.Items[0]);
            Assert.AreEqual("A6", ((Car)result.Items[0]).Name);
            Assert.AreEqual("Audi", ((Car)result.Items[0]).Manufacturer);
        }
        public void NewItemCallsSessionStore()
        {
            // Arrange & Act
            string expectedAppName = "You are everything ... to me";
            string appPath = "Application path";
            var subject = TestStoreProviderFactory.SetupStoreProvider(appPath, MockHostingProvider);
            NameValueCollection keyPairs = new NameValueCollection();
            keyPairs.Set("applicationName", expectedAppName);
            subject.Initialize("", keyPairs, MockDocumentStore.Object);

            SessionStateStoreData sessionData = new SessionStateStoreData(
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                20
                );

            subject.SetAndReleaseItemExclusive(new HttpContext(new SimpleWorkerRequest("", "", "", "", new StringWriter())), "A sessionId", sessionData, new object(), true);

            MockDocumentSession.Setup(cmd => cmd.Store(It.IsAny<SessionStateDocument>())).Verifiable();

            // Assert
            MockDocumentSession.Verify(cmd => cmd.Store(It.IsAny<SessionStateDocument>()), Times.Once());
        }
Example #27
0
File: Grid.cs Project: xzc3ss/Zaza
        internal string GetPath(NameValueCollection queryString__1, params string[] exclusions)
        {
            NameValueCollection temp = new NameValueCollection(QueryString);
              // update current query string in case values were set programmatically
              if (temp.AllKeys.Contains(SortFieldName))
              {
            if (String.IsNullOrEmpty(SortColumn))
            {
              temp.Remove(SortFieldName);
            }
            else
            {
              temp.Set(SortFieldName, SortColumn);
            }
              }
              if (temp.AllKeys.Contains(SortDirectionFieldName))
              {
            temp.Set(SortDirectionFieldName, GetSortDirectionString(SortDirection));
              }
              // remove fields from exclusions list
              foreach (string key in exclusions)
              {
            temp.Remove(key);
              }
              // replace with new field values
              foreach (string key in queryString__1.Keys)
              {
            temp.Set(key, queryString__1[key]);
              }
              queryString__1 = temp;

              StringBuilder sb = new StringBuilder(HttpContext.Current.Request.Path);
              sb.Append("?");
              for (int i = 0; i <= queryString__1.Count - 1; i++)
              {
            if (i > 0)
            {
              sb.Append("&");
            }
            sb.Append(HttpUtility.UrlEncode(queryString__1.Keys[i]));
            sb.Append("=");
            sb.Append(HttpUtility.UrlEncode(queryString__1[i]));
              }
              return sb.ToString();
        }
Example #28
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            using (JiraUpload up = new JiraUpload(_jiraIssuePrefix, GetSummary))
            {
                if (up.ShowDialog() == DialogResult.Cancel)
                {
                    return new UploadResult
                    {
                        IsSuccess = true,
                        IsURLExpected = false
                    };
                }

                Uri uri = new Uri(_jiraHost, string.Format(PathIssueAttachments, up.IssueId));
                string query = OAuthManager.GenerateQuery(uri.ToString(), null, HttpMethod.Post, AuthInfo);

                NameValueCollection headers = new NameValueCollection();
                headers.Set("X-Atlassian-Token", "nocheck");

                UploadResult res = UploadData(stream, query, fileName, "file", null, null, headers);
                if (res.Response.Contains("errorMessages"))
                {
                    res.Errors.Add(res.Response);
                }
                else
                {
                    res.IsURLExpected = true;
                    var anonType = new[] { new { thumbnail = "" } };
                    var anonObject = JsonConvert.DeserializeAnonymousType(res.Response, anonType);
                    res.ThumbnailURL = anonObject[0].thumbnail;
                    res.URL = new Uri(_jiraHost, string.Format(PathBrowseIssue, up.IssueId)).ToString();
                }

                return res;
            }
        }
Example #29
0
        /// <summary>
        /// Creates a new name value collection and overrides its values
        /// with system values (environment variables).
        /// </summary>
        /// <param name="props">The base properties to override.</param>
        /// <returns>A new NameValueCollection instance.</returns>
        private static NameValueCollection OverrideWithSysProps(NameValueCollection props)
        {
            NameValueCollection retValue = new NameValueCollection(props);
            IDictionary vars = Environment.GetEnvironmentVariables();

            foreach (string key in vars.Keys)
            {
                retValue.Set(key, vars[key] as string);
            }
            return retValue;
        }
Example #30
0
        public override void Render()
        {
            if (objectPage.Pages <= 1)
            {
                CancelView();
                return;
            }

            bool flagParam = false;
            int type = 0;
            NameValueCollection parameters = new NameValueCollection(Request.QueryString);
            parameters.Add(Request.Form);

            StringBuilder content = new StringBuilder();

            //string content = "<table class=\"page\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
            //content += "<tr>";

            content.Append("<p class=\"right\">");

            string url = Request.RawUrl;
            if (url.Contains(".do"))
            {
                string linkFormat = "<a href=\"{0}?{1}\">{2}</a>";
                string currLinkFormat = "<a class=\"hover\" href=\"{0}?{1}\">{2}</a>";
                string queryString;
                int start = 1;
                if (objectPage.CurrPage > maxPages / 2)
                {
                    start = objectPage.CurrPage - maxPages / 2;
                }
                int end = start + maxPages - 1;
                if (end > objectPage.Pages)
                {
                    end = objectPage.Pages;
                }

                if (objectPage.CurrPage > 1)
                {
                    parameters.Set(firstName, Convert.ToString(0));
                    queryString = BuildQueryString(RailsContext.Server, parameters, true);
                    //content += String.Format(linkFormat, Request.FilePath, queryString, firstPageText);
                    content.Append(string.Format(linkFormat,Request.FilePath,queryString,firstPageText));

                    parameters.Set(firstName, Convert.ToString(objectPage.PrevPage));
                    queryString = BuildQueryString(RailsContext.Server, parameters, true);
                    //content += String.Format(linkFormat, Request.FilePath, queryString, prevPageText);
                    content.Append(string.Format(linkFormat,Request.FilePath,queryString,prevPageText));
                }

                for (int i = start; i <= end; i++)
                {
                    string pageText = Convert.ToString(i);
                    parameters.Set(firstName, Convert.ToString((i - 1) * objectPage.MaxResults));
                    queryString = BuildQueryString(RailsContext.Server, parameters, true);
                    if (i == objectPage.CurrPage)
                    {
                        //content += String.Format(currLinkFormat, Request.FilePath, queryString, pageText);
                        content.Append(string.Format(currLinkFormat,Request.FilePath,queryString,pageText));
                    }
                    else
                    {
                        //content += String.Format(linkFormat, Request.FilePath, queryString, pageText);
                        content.Append(string.Format(linkFormat,Request.FilePath,queryString,pageText));
                    }
                }

                if (objectPage.CurrPage < objectPage.Pages)
                {
                    parameters.Set(firstName, Convert.ToString(objectPage.NextPage));
                    queryString = BuildQueryString(RailsContext.Server, parameters, true);
                    //content += String.Format(linkFormat, Request.FilePath, queryString, nextPageText);
                    content.Append(string.Format(linkFormat,Request.FilePath,queryString,nextPageText));

                    parameters.Set(firstName, Convert.ToString(objectPage.LastPage));
                    queryString = BuildQueryString(RailsContext.Server, parameters, true);
                    //content += String.Format(linkFormat, Request.FilePath, queryString, lastPageText);
                    content.Append(string.Format(linkFormat,Request.FilePath,queryString,lastPageText));
                }

            }
            else
            {
                foreach (string s in parameters.AllKeys)
                {
                    if (s == firstName)
                        flagParam = true;
                }
                if (url.EndsWith(".html"))
                {
                    type = 1;
                    if (flagParam)
                        url = url.Substring(0, url.LastIndexOf("-"));
                    else
                        url = url.Substring(0, url.LastIndexOf(".html"));
                }
                else
                {
                    type = 2;
                    if (url.EndsWith("/"))
                    {
                        if (flagParam)
                        {
                            url = url.Substring(0, url.LastIndexOf("/"));
                            url = url.Substring(0, url.LastIndexOf("/"));
                        }
                        else
                        {
                            url = url.Substring(0, url.LastIndexOf("/"));
                        }
                    }
                    else
                    {
                        if (flagParam)
                        {
                            url = url.Substring(0, url.LastIndexOf("/"));
                        }
                    }
                }

                string linkFormat = "<a href=\"{0}\">{1}</a>";
                string currLinkFormat = "<a class=\"hover\" href=\"{0}\">{1}</a>";
                string queryString;
                int start = 1;
                if (objectPage.CurrPage > maxPages / 2)
                {
                    start = objectPage.CurrPage - maxPages / 2;
                }
                int end = start + maxPages - 1;
                if (end > objectPage.Pages)
                {
                    end = objectPage.Pages;
                }

                string urlTemp = url;
                if (objectPage.CurrPage > 1)
                {

                    if (type == 1)
                    {
                        urlTemp = url + "-" + Convert.ToString(0) + ".html";
                    }
                    else if (type == 2)
                    {
                        urlTemp = url + "/" + Convert.ToString(0);
                    }
                    //content += String.Format(linkFormat, urlTemp, firstPageText);
                    content.Append(string.Format(linkFormat,urlTemp,firstPageText));

                    urlTemp = url;
                    if (type == 1)
                    {
                        urlTemp = url + "-" + Convert.ToString(objectPage.PrevPage) + ".html";
                    }
                    else if (type == 2)
                    {
                        urlTemp = url + "/" + Convert.ToString(objectPage.PrevPage);
                    }

                    //content += String.Format(linkFormat, urlTemp, prevPageText);
                    content.Append(string.Format(linkFormat,urlTemp,prevPageText));
                }

                for (int i = start; i <= end; i++)
                {
                    urlTemp = url;
                    string pageText = Convert.ToString(i);
                    if (type == 1)
                    {
                        urlTemp = url + "-" + Convert.ToString((i - 1) * objectPage.MaxResults) + ".html";
                    }
                    else if (type == 2)
                    {
                        urlTemp = url + "/" + Convert.ToString((i - 1) * objectPage.MaxResults);
                    }

                    if (i == objectPage.CurrPage)
                    {
                        //content += String.Format(currLinkFormat, urlTemp, pageText);
                        content.Append(string.Format(currLinkFormat,urlTemp,pageText));
                    }
                    else
                    {
                        //content += String.Format(linkFormat, urlTemp, pageText);
                        content.Append(string.Format(linkFormat,urlTemp,pageText));
                    }
                }

                if (objectPage.CurrPage < objectPage.Pages)
                {
                    urlTemp = url;
                    if (type == 1)
                    {
                        urlTemp = url + "-" + Convert.ToString(objectPage.NextPage) + ".html";
                    }
                    else if (type == 2)
                    {
                        urlTemp = url + "/" + Convert.ToString(objectPage.NextPage);
                    }
                    //content += String.Format(linkFormat, urlTemp, nextPageText);
                    content.Append(string.Format(linkFormat,urlTemp,nextPageText));

                    urlTemp = url;
                    if (type == 1)
                    {
                        urlTemp = url + "-" + Convert.ToString(objectPage.LastPage) + ".html";
                    }
                    else if (type == 2)
                    {
                        urlTemp = url + "/" + Convert.ToString(objectPage.LastPage);
                    }
                    //content += String.Format(linkFormat, urlTemp, lastPageText);
                    content.Append(string.Format(linkFormat,urlTemp,lastPageText));
                }
            }

            #region ��ת����
            if (IsDispSelect)
            {
                if (this.MaxRecord == 0)
                    this.MaxRecord = 20;
                //string gp = RailsContext.Params.Get("gotoPage");
                string first = RailsContext.Params.Get("first");

                int tmp = this.objectPage.AllResults % this.MaxRecord;
                int tmp2 = this.objectPage.AllResults / this.MaxRecord;
                int pageCount = tmp == 0 ? tmp2 : tmp2 + 1;
                if (pageCount > 1)
                {
                    content.Append("<span style='float:right;'>��ת����");
                    content.Append("<select name='gotoPage' onchange='gotoPage(\"" + FormId +  "\",this)'>");
                    for (int i = 0; i < pageCount; i++)
                    {
                        if (!string.IsNullOrEmpty(first) && int.Parse(first) == i * this.MaxRecord)
                        {
                            content.Append(string.Format("<option value='{1}' selected='selected'>{0}</option>", i + 1, i * this.MaxRecord));
                        }
                        else
                        {
                            content.Append(string.Format("<option value='{1}'>{0}</option>", i + 1, i  * this.MaxRecord ));
                        }
                    }
                    content.Append("</select>");
                    content.Append("ҳ</span>");
                }
            }
            #endregion

            content.Append("</p>");

            RenderText(content.ToString());
            CancelView();
        }
Example #31
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();

            //  [] Set() - new simple strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                cnt = nvc.Count;
                nvc.Set(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
            // [] Set() - new 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.Set(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 ( keys 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;
                // add uppercase items
                nvc.Set(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));
                }
            }

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

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

            for (int i = 0; i < len; i++)
            {
                nvc.Set(k, "Value" + i);
                // should replace previous value
                if (nvc.Count != 1)
                {
                    Assert.False(true, string.Format("Error, count is {0} instead of 1", nvc.Count, i));
                }
                if (String.Compare(nvc[k], "Value" + i) != 0)
                {
                    Assert.False(true, string.Format("Error, didn't replace value", i));
                }
            }

            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 != 1)
            {
                Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, 1));
            }

            if (Array.IndexOf(vals, "Value" + (len - 1).ToString()) < 0)
            {
                Assert.False(true, string.Format("Error, value is not {0}", "Value" + (len - 1)));
            }

            //
            // [] Set(string, null)
            //

            k = "kk";

            nvc.Remove(k);      // make sure there is no such item already
            cnt = nvc.Count;
            nvc.Set(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");
            }

            nvc.Remove(k);      // make sure there is no such item already
            nvc.Add(k, "kItem");
            cnt = nvc.Count;
            nvc.Set(k, null);

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

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

            // verify that item at k-key was replaced with null
            //
            if (nvc[k] != null)
            {
                Assert.False(true, "Error, non-null was not replaced with null");
            }

            //
            // Set item with null key - no NullReferenceException expected
            // [] Set(null, string)
            //

            nvc.Remove(null);
            cnt = nvc.Count;

            nvc.Set(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");
            }


            // replace item with null key
            cnt = nvc.Count;
            nvc.Set(null, "newItem");

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

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

            // verify that item with null key was replaced
            //
            if (nvc[null] != "newItem")
            {
                Assert.False(true, "Error, didn't replace value at null key");
            }
        }
        private async void SubmitCampaign(object sender, EventArgs e)
        {
            bool moveOn = true;

            if (CampaignNameEntry.Text == "")
            {
                CampaignNameLabel.TextColor = Color.Red;
                moveOn = false;
            }

            if (CampaignDescriptionEntry.Text == "")
            {
                CampaignDescriptionLabel.TextColor = Color.Red;
                moveOn = false;
            }
            if (isCrowdfund.IsToggled == true)
            {
                if (GoalEntry.Text == "")
                {
                    GoalLabel.TextColor = Color.Red;
                    moveOn = false;
                }

                if (StartDateEntry.Date.CompareTo(EndDateEntry.Date) >= 0)
                {
                    dateWarning.IsVisible = true;
                    moveOn = false;
                }
            }

            if (moveOn == true)
            {
                sendingData.Set("campaignName", CampaignNameEntry.Text);
                sendingData.Set("campaignDescription", CampaignDescriptionEntry.Text);
                if (isCrowdfund.IsToggled)
                {
                    sendingData.Set("goal", GoalEntry.Text);
                    sendingData.Set("startDate", StartDateEntry.Date.ToShortDateString());
                    sendingData.Set("endDate", EndDateEntry.Date.ToShortDateString());
                }
                client.UploadValues("http://www.cvx4u.com/web_service/create_campaign.php", sendingData);
                await Navigation.PushAsync(new CandidateDashboard());
            }
        }
        private void SubmitData(object sender, EventArgs e)
        {
            Button current = (Button)sender;

            if (current.ClassId == "CampaignDescription")
            {
                editData.Set("property", current.ClassId);
                editData.Set("value", CampaignDescriptionEntry.Text);
                editData.Set("campaign", campaignNumber);
                CampaignDescriptionDisplay.Text      = CampaignDescriptionEntry.Text;
                CampaignDescriptionEntry.IsVisible   = false;
                CampaignDescriptionSubmit.IsVisible  = false;
                CampaignDescriptionCancel.IsVisible  = false;
                CampaignDescriptionDisplay.IsVisible = true;
                CampaignDescriptionEdit.IsVisible    = true;
            }
            else if (current.ClassId == "CampaignName")
            {
                editData.Set("property", current.ClassId);
                editData.Set("value", CampaignNameEntry.Text);
                editData.Set("campaign", campaignNumber);
                CampaignNameDisplay.Text      = CampaignNameEntry.Text;
                CampaignNameEntry.IsVisible   = false;
                CampaignNameSubmit.IsVisible  = false;
                CampaignNameCancel.IsVisible  = false;
                CampaignNameDisplay.IsVisible = true;
                CampaignNameEdit.IsVisible    = true;
            }

            else if (current.ClassId == "StartDate")
            {
                editData.Set("property", current.ClassId);
                editData.Set("value", StartDateEntry.Date.ToShortDateString());
                editData.Set("campaign", campaignNumber);
                StartDateDisplay.Text      = StartDateEntry.Date.ToShortDateString();
                StartDateEntry.IsVisible   = false;
                StartDateSubmit.IsVisible  = false;
                StartDateCancel.IsVisible  = false;
                StartDateDisplay.IsVisible = true;
                StartDateEdit.IsVisible    = true;
            }
            else if (current.ClassId == "EndDate")
            {
                editData.Set("property", current.ClassId);
                editData.Set("value", EndDateEntry.Date.ToShortDateString());
                editData.Set("campaign", campaignNumber);
                EndDateDisplay.Text      = EndDateEntry.Date.ToShortDateString();
                EndDateEntry.IsVisible   = false;
                EndDateSubmit.IsVisible  = false;
                EndDateCancel.IsVisible  = false;
                EndDateDisplay.IsVisible = true;
                EndDateEdit.IsVisible    = true;
            }
            else
            {
                editData.Set("property", current.ClassId);
                editData.Set("value", GoalEntry.Text);
                editData.Set("campaign", campaignNumber);
                GoalDisplay.Text      = GoalEntry.Text;
                GoalEntry.IsVisible   = false;
                GoalSubmit.IsVisible  = false;
                GoalCancel.IsVisible  = false;
                GoalDisplay.IsVisible = true;
                GoalEdit.IsVisible    = true;
            }

            if (StartDateEntry.Date.CompareTo(EndDateEntry.Date) > 0)
            {
                dateWarning.IsVisible = true;
            }
            else
            {
                dateWarning.IsVisible = false;
                client.UploadValues("http://www.cvx4u.com/web_service/create_campaign.php", editData);
            }
        }
Example #34
0
        public static string HttpRequestURLSyn(RequestHeader currentHeader, string requestUrl)
        {
            System.Collections.Specialized.NameValueCollection nv = new System.Collections.Specialized.NameValueCollection(StringComparer.InvariantCultureIgnoreCase);

            StringBuilder urlBuilder = new StringBuilder();
            int           qIdx       = requestUrl.IndexOf('?');

            if (qIdx != -1)
            {
                string paramStr = requestUrl.Substring(qIdx + 1);
                urlBuilder.Append(requestUrl.Substring(0, qIdx) + "?");

                string[] subParams = paramStr.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                string[] kvPairs   = new string[2];
                foreach (string crtParam in subParams)
                {
                    kvPairs = crtParam.Split('=');
                    if (kvPairs.Length == 2)
                    {
                        nv.Set(kvPairs[0], kvPairs[1]);
                    }
                    else
                    {
                        //TODO?
                        nv.Set(crtParam, crtParam);
                    }
                }
            }

            if (!nv.HasKeys())
            {
                urlBuilder.Append(requestUrl + "?");
            }
            #region 参数附加

            /*
             * 参数名 参数说明
             * sid 参考2.4.2
             * imei 参考2.4.5
             * imsi 参考2.4.6
             * nid 参考2.4.3
             * did 参考2.4.1
             * dtd 拨号方式说明:
             *         0-CTNET
             *         1-CTWAP
             */
            nv.Set("sid", currentHeader.ESP_SoftwareID.ToString());
            nv.Set("imei", currentHeader.ESP_IMEI.GetRawString());
            nv.Set("imsi", currentHeader.ESP_IMEI.GetRawString()); //??
            nv.Set("nid", currentHeader.ESP_NID.GetHashCode().ToString());
            nv.Set("did", currentHeader.ESP_DID.ToString());
            nv.Set("dtd", currentHeader.ESP_DailType.GetHashCode().ToString());
            #endregion

            foreach (string key in nv.AllKeys)
            {
                urlBuilder.AppendFormat("{0}={1}&", key, nv[key]);
            }

            return(urlBuilder.ToString().TrimEnd('&'));
        }