Inheritance: NameObjectCollectionBase
        /// <summary>
        /// 参数解析
        /// </summary>
        /// <param name="paramters"></param>
        /// <param name="nvs"></param>
        /// <returns></returns>
        public static object[] Convert(ParameterInfo[] paramters, NameValueCollection nvs)
        {
            List<object> args = new List<object>();
            var obj = ConvertJsonObject(nvs);

            foreach (ParameterInfo info in paramters)
            {
                var type = GetElementType(info.ParameterType);

                var property = obj.Properties().SingleOrDefault(p => string.Compare(p.Name, info.Name, true) == 0);
                if (property != null)
                {
                    try
                    {
                        //获取Json值
                        var jsonValue = CoreHelper.ConvertJsonValue(type, property.Value.ToString(Formatting.None));
                        args.Add(jsonValue);
                    }
                    catch (Exception ex)
                    {
                        throw new RESTfulException((int)HttpStatusCode.BadRequest, string.Format("Parameter [{0}] did not match type [{1}].",
                            info.Name, CoreHelper.GetTypeName(type)));
                    }
                }
                else
                {
                    throw new RESTfulException((int)HttpStatusCode.BadRequest, "Parameter [" + info.Name + "] is not found.");
                }
            }

            return args.ToArray();
        }
Beispiel #2
1
 public override NameValueCollection HandleRequest(NameValueCollection request)
 {
     var response = new NameValueCollection();
     response["redirect"] = GetRedirectUrl(request);
     ;
     return response;
 }
 protected void BuildResult(NameValueCollection formVariables)
 {
     this.HashDigest = formVariables["HashDigest"];
     this.MerchantID = formVariables["MerchantID"];
     this.CrossReference = formVariables["CrossReference"];
     this.OrderID = formVariables["OrderID"];
 }
        public CallbackResult(NameValueCollection formVariables)
        {
            if (formVariables == null)
                throw new ArgumentNullException("formVariables");

            BuildResult(formVariables);
        }
Beispiel #5
1
 public ArgumentsDynamic(NameValueCollection nameValueCollection)
 {
     this.args = nameValueCollection.Keys.OfType<string>()
                         .ToDictionary(k => k.ToString(),
                                 k => nameValueCollection[(string)k],
                                 StringComparer.InvariantCultureIgnoreCase);
 }
Beispiel #6
1
        private PagedRecords GetRecords(
            Entity entity,
            NameValueCollection request,
            TableInfo tableInfo,
            Action<IList<BaseFilter>> filtersMutator)
        {
            var filterRecord = create_filter_record(entity, request);
            var filters = _filterFactory.BuildFilters(filterRecord).ToList();
            if (filtersMutator != null)
            {
                filtersMutator(filters);
            }
            var pagedRecords = _entitiesSource.GetRecords(
                entity,
                filters,
                tableInfo.SearchQuery,
                tableInfo.Order,
                tableInfo.OrderDirection,
                false,
                tableInfo.Page,
                tableInfo.PerPage);
            pagedRecords.Filters = filters;

            return pagedRecords;
        }
        public static MoreLikeThisQuery GetParametersFromPath(string path, NameValueCollection query)
        {
            var results = new MoreLikeThisQuery
            {
                IndexName = query.Get("index"),
                Fields = query.GetValues("fields"),
                Boost = query.Get("boost").ToNullableBool(),
                BoostFactor = query.Get("boostFactor").ToNullableFloat(),
                MaximumNumberOfTokensParsed = query.Get("maxNumTokens").ToNullableInt(),
                MaximumQueryTerms = query.Get("maxQueryTerms").ToNullableInt(),
                MaximumWordLength = query.Get("maxWordLen").ToNullableInt(),
                MinimumDocumentFrequency = query.Get("minDocFreq").ToNullableInt(),
                MaximumDocumentFrequency = query.Get("maxDocFreq").ToNullableInt(),
                MaximumDocumentFrequencyPercentage = query.Get("maxDocFreqPct").ToNullableInt(),
                MinimumTermFrequency = query.Get("minTermFreq").ToNullableInt(),
                MinimumWordLength = query.Get("minWordLen").ToNullableInt(),
                StopWordsDocumentId = query.Get("stopWords"),
                AdditionalQuery= query.Get("query")
            };

            var keyValues = query.Get("docid").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var keyValue in keyValues)
            {
                var split = keyValue.IndexOf('=');

                if (split >= 0)
                    results.MapGroupFields.Add(keyValue.Substring(0, split), keyValue.Substring(split + 1));
                else
                    results.DocumentId = keyValue;
            }

            return results;
        }
        public IAuthenticatedClient AuthenticateClient(IAuthenticationServiceSettings authenticationServiceSettings,
                                                       NameValueCollection queryStringParameters)
        {
            if (authenticationServiceSettings == null)
            {
                throw new ArgumentNullException("authenticationServiceSettings");
            }

            if (!string.IsNullOrEmpty(AuthenticateClientExceptionMessage))
            {
                throw new AuthenticationException(AuthenticateClientExceptionMessage);
            }

            return new AuthenticatedClient("facebook")
            {
                AccessToken = "EstSularusOthMithas-MyHonorIsMyLife",
                AccessTokenExpiresOn = DateTime.UtcNow.AddDays(30),
                UserInformation = UserInformation ?? new UserInformation
                {
                    Gender = GenderType.Male,
                    Id = "FakeId-" + Guid.NewGuid().ToString(),
                    Locale = "en-au",
                    Name = "Sturm Brightblade",
                    Picture = "http://i.imgur.com/jtoOF.jpg",
                    UserName = "******"
                }
            };
        }
Beispiel #9
1
        public static TestableChat GetTestableChat(string clientId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            // setup client agent
            chat.Agent = new ClientAgent(mockedConnectionObject, "Chat");

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);

            // setup signal agent
            var prinicipal = new Mock<IPrincipal>();
            chat.Caller = new SignalAgent(mockedConnectionObject, clientId, "Chat", clientState);

            // setup context
            chat.Context = new HubContext(new HostContext(request.Object, null, prinicipal.Object), clientId);

            return chat;
        }
        public ActionResult API()
        {
            Stream filestream = null;
            if (Request.Files.Count > 0)
            {
                filestream = Request.Files[0].InputStream;
            }

            var pars = new NameValueCollection();
            pars.Add(Request.Params);

            if (Request.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
            {
                var parsKeys = pars.AllKeys;
                foreach (var key in Request.Form.AllKeys)
                {
                    if (!parsKeys.Contains(key))
                    {
                        pars.Add(Request.Form);
                    }
                }
            }

            var res = getRuntime.DesignerAPI(pars, filestream, true);
            if (pars["operation"].ToLower() == "downloadscheme")
            {
                return File(Encoding.UTF8.GetBytes(res), "text/xml", "Scheme.xml");
            }

            return Content(res);
        }
Beispiel #11
1
            public void CanDeserializeClientState()
            {
                var clientState = new TrackingDictionary();
                string clientId = "1";
                var user = new ChatUser
                {
                    Id = "1234",
                    Name = "John"
                };

                var cookies = new NameValueCollection();
                cookies["jabbr.state"] = JsonConvert.SerializeObject(new ClientState { UserId = user.Id });

                TestableChat chat = GetTestableChat(clientId, clientState, user, cookies);

                bool result = chat.Join();

                Assert.Equal("1234", clientState["id"]);
                Assert.Equal("John", clientState["name"]);
                Assert.True(result);

                chat.MockedConnection.Verify(m => m.Broadcast("Chat." + clientId, It.IsAny<object>()), Times.Once());
                chat.MockedChatService.Verify(c => c.AddClient(user, clientId), Times.Once());
                chat.MockedChatService.Verify(c => c.UpdateActivity(user), Times.Once());
            }
        void TransferujPlResponseFromNameValueCollectionDoesCorrectlySetOKState()
        {
            var items = new NameValueCollection { { "id", "123" }, { "tr_status", "TRUE" } };
            var response = TransferujPlResponse.FromNameValueCollection(items);

            Assert.True(response.Result);
        }
        public async Task Valid_Code_Request()
        {
            var client = await _clients.FindClientByIdAsync("codeclient");
            var store = new InMemoryAuthorizationCodeStore();

            var code = new AuthorizationCode
            {
                Client = client,
                RedirectUri = "https://server/cb",
                RequestedScopes = new List<Scope>
                {
                    new Scope
                    {
                        Name = "openid"
                    }
                }
            };

            await store.StoreAsync("valid", code);

            var validator = Factory.CreateTokenRequestValidator(
                authorizationCodeStore: store);

            var parameters = new NameValueCollection();
            parameters.Add(Constants.TokenRequest.GrantType, Constants.GrantTypes.AuthorizationCode);
            parameters.Add(Constants.TokenRequest.Code, "valid");
            parameters.Add(Constants.TokenRequest.RedirectUri, "https://server/cb");

            var result = await validator.ValidateRequestAsync(parameters, client);

            result.IsError.Should().BeFalse();
        }
Beispiel #14
1
 public WebPEncoderPlugin(NameValueCollection args)
     : this()
 {
     Lossless = ExtensionMethods.NameValueCollectionExtensions.Get<bool>(args, "lossless", Lossless);
     Quality = ExtensionMethods.NameValueCollectionExtensions.Get<float>(args, "quality", Quality);
     NoAlpha = ExtensionMethods.NameValueCollectionExtensions.Get<bool>(args, "noalpha", NoAlpha);
 }
 /// <summary>
 /// Prepares payment form that will be sent (by user) to payment portal. Can establish a payment transaction if payment process requires it.
 /// </summary>
 /// <param name="order">Order info (id, price to be paid, ..)</param>
 /// <param name="portalLocale">Current user locale, can be send to payment portal to enforce the same.</param>
 /// <param name="urls">Urls that should be provided to payment portal to notify Storefront about success or to return back to portal. Notification is further processed by the <see cref="GetPaymentInfo"/>.</param>
 /// <param name="setupForm">Custom setup of payment method, can be <code>null</code> when no setup requested. See <see cref="CreateSetupForm"/></param>
 /// <returns>Payment form (to be send) plus optionally id of established transaction (to be stored).</returns>
 public PreparedPayment PreparePayment(Order order, string portalLocale, ReturnUrls urls, NameValueCollection setupForm)
 {
     var paymentForm = PaymentForm.Post(
         _settings.Pay ? urls.Notify : urls.Cancel,
         CreatePaymentFormFields(order, setupForm));
     return new PreparedPayment(paymentForm, EncodePriceAndStatusIntoTransaction(order.TotalPriceIncludingTax, PaymentStatus));
 }
 public FakeHttpContext(string relativeUrl, 
     IPrincipal principal, NameValueCollection formParams,
     NameValueCollection queryStringParams, HttpCookieCollection cookies,
     SessionStateItemCollection sessionItems, NameValueCollection serverVariables)
     : this(relativeUrl, null, principal, formParams, queryStringParams, cookies, sessionItems, serverVariables)
 {
 }
Beispiel #17
0
 public int Delete(NameValueCollection where, out ErrorEntity ErrInfo)
 {
     OEQuestionDA da = new OEQuestionDA();
     NameValueCollection parameters = new NameValueCollection();
     parameters.Add("FQuestionStatus", "0");
     return Update(parameters, where, out ErrInfo);
 }
Beispiel #18
0
        public Textarea()
        {
            _settings = new NameValueCollection();

            ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(PROVIDER_TYPE);
            Provider objProvider = (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider];

            if ((objProvider != null))
            {
                foreach (string key in objProvider.Attributes)
                {
                    if ((key.ToLower().StartsWith("mce_")))
                    {
                        string adjustedKey = key.Substring(4, key.Length - 4).ToLower();
                        if ((!string.IsNullOrEmpty(adjustedKey)))
                        {
                            _settings[adjustedKey] = objProvider.Attributes[key];
                        }
                    }
                    else if ((key.ToLower() == "providerpath"))
                    {
                        _providerPath = objProvider.Attributes[key];
                    }
                    else if ((key.ToLower() == "tinymceversion"))
                    {
                        _tinymceVersion = objProvider.Attributes[key];
                    }
                }
            }
        }
Beispiel #19
0
		public object Parse(NameValueCollection data, string key, string prefix, out bool succeed)
		{
			string value = Utils.GetValue(data, key, prefix);
			int num = 0;
			succeed = int.TryParse(value, out num);
			return num;
		}
Beispiel #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebRequest"/> class.
 /// </summary>
 /// <param name="type">Specifies the type of web request.</param>
 /// <param name="destination">Specifies the destination of the request.</param>
 protected WebRequest( WebRequestType type, Uri destination )
 {
     Headers = new NameValueCollection();
     AutoRedirect = true;
     Type = type;
     Destination = destination;
 }
        private static string RetrieveAuthorizationCode(NameValueCollection queryStringParameters, string existingState = null)
        {
            if (queryStringParameters == null)
            {
                throw new ArgumentNullException("queryStringParameters");
            }

            if (queryStringParameters.Count <= 0)
            {
                throw new ArgumentOutOfRangeException("queryStringParameters");
            }

            /* Documentation:
               LinkedIn returns an authorization code to your application if the user grants your application the permissions it requested. 
               The authorization code is returned to your application in the query string parameter code. If the state parameter was included in the request,
               then it is also included in the response. */
            var code = queryStringParameters["code"];
            var error = queryStringParameters["error"];

            // First check for any errors.
            if (!string.IsNullOrEmpty(error))
            {
                throw new AuthenticationException(
                    "Failed to retrieve an authorization code from LinkedIn. The error provided is: " + error);
            }

            // Otherwise, we need a code.
            if (string.IsNullOrEmpty(code))
            {
                throw new AuthenticationException("No code parameter provided in the response query string from LinkedIn.");
            }

            return code;
        }
        void TransferujPlResponseFromNameValueCollectionDoesCorrectlySetTransactionId()
        {
            var items = new NameValueCollection { { "id", "123" }, { "tr_id", "345a1" } };
            var response = TransferujPlResponse.FromNameValueCollection(items);

            Assert.Equal("345a1", response.TransactionId);
        }
        /// <summary>
        /// Runs this post step.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <param name="metaData">The meta data.</param>
        public virtual void Run(ITaskOutput output, NameValueCollection metaData)
        {
            Item detailListTemplate = Database.GetDatabase("master").GetItem(OrderListTemplateItemID);

              foreach (Item column in detailListTemplate.Children)
              {
            foreach (Item columnClone in Globals.LinkDatabase.GetReferrers(column).Select(link => link.GetSourceItem()))
            {
              if (columnClone.TemplateID != ColumnFieldTemplateID)
              {
            continue;
              }

              string expectedHeader = column.Fields[HeaderName].Value;
              string clonnedHeader = columnClone.Fields[HeaderName].Value;
              if (clonnedHeader == expectedHeader)
              {
            continue;
              }

              using (new EditContext(columnClone))
              {
            columnClone.Fields[HeaderName].Reset();
            Log.Info("Resetting detail list header for \"{0}\" column.".FormatWith(columnClone.Paths.FullPath), this);
              }
            }
              }
        }
        /// <summary>
        /// Method to get the list of fields and their values
        /// </summary>
        ///
        /// <returns>Name value collection containing the fields and the values</returns>
        ///
        /// <remarks>
        ///
        /// <RevisionHistory>
        /// Author				Date			Description
        /// DLGenerator			9/19/2012 10:48:08 AM				Created function
        /// 
        /// </RevisionHistory>
        ///
        /// </remarks>
        ///
        public NameValueCollection GetKeysAndValues()
        {
            NameValueCollection nvc=new NameValueCollection();

            nvc.Add("Purl",_purl.ToString());
            return nvc;
        }
Beispiel #25
0
 public PagedRecords GetRecords(
     Entity entity,
     NameValueCollection request,
     TableInfo tableInfo)
 {
     return GetRecords(entity, request, tableInfo, null);
 }
        /// <summary>
        /// Overriding the Execute method that Sitecore calls.
        /// </summary>
        /// <param name = "context"></param>
        public override void Execute(CommandContext context)
        {
            if (context.Parameters["id"] == null || string.IsNullOrEmpty(context.Parameters["id"]))
            {
                return;
            }

            //only use on authoring environment
            Item currentItem = Sitecore.Context.ContentDatabase.GetItem(context.Parameters["id"]);
            if (currentItem == null)
            {
                return;
            }

            NameValueCollection nv = new NameValueCollection();
            nv.Add("id", context.Parameters["id"]);

            Item item = Sitecore.Context.ContentDatabase.GetItem(context.Parameters["id"]);
            if (item.IsNull())
            {
                return;
            }

            if (context.Parameters["fieldid"] != null)
            {
                nv.Add("fieldid", context.Parameters["fieldid"]);
            }

            nv.Add("la", item.Language.ToString());
            nv.Add("vs", item.Version.ToString());

            Sitecore.Context.ClientPage.Start(this, "ItemComparerForm", nv);
        }
Beispiel #27
0
 private SchemaTemplate()
 {
     if (this.template == null)
     {
         this.template = new NameValueCollection();
     }
 }
        public void GetOrCreateHttpRequestMessageFromHttpContextCopiesHeaders()
        {
            // Arrange
            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();
            Dictionary<string, object> items = new Dictionary<string, object>();
            contextMock.Setup(o => o.Items).Returns(items);
            var requestMock = new Mock<HttpRequestBase>();
            requestMock.Setup(r => r.HttpMethod).Returns("GET");
            requestMock.Setup(r => r.InputStream).Returns(new MemoryStream());
            NameValueCollection col = new NameValueCollection();
            col.Add("customHeader", "customHeaderValue");
            requestMock.Setup(r => r.Headers).Returns(col);
            contextMock.Setup(o => o.Request).Returns(requestMock.Object);
            
            // Act
            contextMock.Object.GetOrCreateHttpRequestMessage();

            // Assert
            HttpRequestMessage request = contextMock.Object.GetHttpRequestMessage();
            Assert.NotNull(request);
            Assert.Equal(HttpMethod.Get, request.Method);
            IEnumerable<string> headerValues;
            Assert.True(request.Headers.TryGetValues("customHeader", out headerValues));
            Assert.Equal(1, headerValues.Count());
            Assert.Equal("customHeaderValue", headerValues.First());
        }
        public static HttpRequestMessage CreateHttpRequest(out string content, out NameValueCollection boundVars, out NameValueCollection queryStr, out NameValueCollection headers)
        {
            content = "Number42";
            boundVars = new NameValueCollection
            {
                { "name", "hello" }
            };
            queryStr = new NameValueCollection
            {
                { "msg", "world" }
            };
            headers = new NameValueCollection
            {
                { "Server", "Dev2" }
            };

            var request = new HttpRequestMessage(HttpMethod.Get, string.Format("http://localhost/services/{0}?{1}={2}", boundVars[0], queryStr.Keys[0], queryStr[0]))
            {
                Content = new StringContent(content, Encoding.UTF8)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("text/plain") }
                },
            };
            request.Headers.Add(headers.Keys[0], headers[0]);
            return request;
        }
        public HttpResponseMessage MoreLikeThisGet()
        {
            var nameValueCollection = new NameValueCollection();
            foreach (var queryNameValuePair in InnerRequest.GetQueryNameValuePairs())
            {
                nameValueCollection.Add(queryNameValuePair.Key, queryNameValuePair.Value);
            }

            var parameters = GetParametersFromPath(GetRequestUrl(), nameValueCollection);
            parameters.TransformerParameters = ExtractTransformerParameters();
            parameters.ResultsTransformer = GetQueryStringValue("resultsTransformer");
            parameters.Includes = GetQueryStringValues("include");

            var index = Database.IndexStorage.GetIndexInstance(parameters.IndexName);
            if (index == null)
            {
                return GetMessageWithObject(new { Error = "The index " + parameters.IndexName + " cannot be found" },
                    HttpStatusCode.NotFound);
            }

            var indexEtag = Database.Indexes.GetIndexEtag(parameters.IndexName, null);
            if (MatchEtag(indexEtag))
                return GetEmptyMessage(HttpStatusCode.NotModified);

            
            var result = Database.ExecuteMoreLikeThisQuery(parameters, GetRequestTransaction(), GetPageSize(Database.Configuration.MaxPageSize));

            if (MatchEtag(result.Etag))
                return GetEmptyMessage(HttpStatusCode.NotModified);

            var msg = GetMessageWithObject(result.Result);
            WriteETag(result.Etag, msg);
            return msg;
        }
Beispiel #31
0
        /// <summary>
        /// Extracts queries from a <see cref="Collections.Specialized.NameValueCollection"/> and turns them into a string list
        /// </summary>
        /// <param name="collection">source</param>
        public static string ReadQuery(Collections.Specialized.NameValueCollection collection)
        {
            if (collection == null)
            {
                return("");
            }
            var ret = new StringBuilder().Append("[");

            foreach (var k in collection.AllKeys)
            {
                ret.Append($"{k} = {collection.Get(k)}, ");
            }
            return(ret.ToString().TrimEnd(new char[] { ',', ' ' }) + "]");
        }
Beispiel #32
0
        public static ContentItem GetBeforeItem(Edit.Navigator navigator, System.Collections.Specialized.NameValueCollection request, ContentItem page)
        {
            string before           = request["before"];
            string beforeVersionKey = request["beforeVersionKey"];

            if (!string.IsNullOrEmpty(before))
            {
                ContentItem beforeItem = navigator.Navigate(before);
                return(page.FindPartVersion(beforeItem));
            }
            else if (!string.IsNullOrEmpty(beforeVersionKey))
            {
                return(page.FindDescendantByVersionKey(beforeVersionKey));
            }
            return(null);
        }
        public IQueryContainer BuildQuery(System.Collections.Specialized.NameValueCollection nvc)
        {
            IQueryContainer query = new QueryContainer();

            if (string.IsNullOrEmpty(nvc["q"]))
            {
                query.MatchAllQuery = new MatchAllQuery();
            }
            else
            {
                query.QueryString       = new QueryStringQuery();
                query.QueryString.Query = nvc["q"];
            }

            return(query);
        }
Beispiel #34
0
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);

            if (config != null && config["enableCompositeFiles"] != null && !string.IsNullOrEmpty(config["enableCompositeFiles"]))
            {
                EnableCompositeFiles = bool.Parse(config["enableCompositeFiles"]);
            }

            //if (config != null && config["websiteBaseUrl"] != null && !string.IsNullOrEmpty(config["websiteBaseUrl"]))
            //{
            //    WebsiteBaseUrl = config["website"];
            //    if (!string.IsNullOrEmpty(WebsiteBaseUrl))
            //        WebsiteBaseUrl = WebsiteBaseUrl.TrimEnd('/');
            //}
        }
Beispiel #35
0
 private void ReBind(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("Grade", this.DrGrade.Text);
     nameValueCollection.Add("StoreName", this.txtStoreName.Text);
     nameValueCollection.Add("CellPhone", this.txtCellPhone.Text);
     nameValueCollection.Add("RealName", this.txtRealName.Text);
     nameValueCollection.Add("MicroSignal", this.txtMicroSignal.Text);
     nameValueCollection.Add("Status", this.Status);
     nameValueCollection.Add("pageSize", this.pager.PageSize.ToString(System.Globalization.CultureInfo.InvariantCulture));
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
     }
     base.ReloadPage(nameValueCollection);
 }
Beispiel #36
0
        //########################################################################################
        //iTexmo API for C# / ASP --> go to www.itexmo.com/developers.php for API Documentation
        //########################################################################################
        public object itexmo(string Number, string Message, string API_CODE)
        {
            object functionReturnValue = null;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                System.Collections.Specialized.NameValueCollection parameter = new System.Collections.Specialized.NameValueCollection();
                string url = "https://www.itexmo.com/php_api/api.php";
                parameter.Add("1", Number);
                parameter.Add("2", Message);
                parameter.Add("3", API_CODE);
                dynamic rpb = client.UploadValues(url, "POST", parameter);
                functionReturnValue = (new System.Text.UTF8Encoding()).GetString(rpb);
            }
            return(functionReturnValue);
        }
Beispiel #37
0
        /// <summary>
        /// Reconciles the postback data from the page to check if the value has changed
        /// </summary>
        /// <param name="postDataKey"></param>
        /// <param name="postCollection"></param>
        /// <returns></returns>
        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            bool thisTriggeredThePostBack = postCollection["__EVENTTARGET"] == this.UniqueID;

            if (thisTriggeredThePostBack && this.DataSource.Count > 0)
            {
                string oldValue = this.SelectedValue;
                string newValue = postCollection[postDataKey];

                this.SelectedValue = newValue;

                return(oldValue.Equals(newValue) == false);
            }

            return(false);
        }
        public virtual void BindrptProduct()
        {
            int count;
            var query = new NameValueCollection(Request.QueryString);

            if (string.IsNullOrWhiteSpace(query["storageId"]))
            {
                query.Add("storageId", ddlStorage.SelectedValue);
            }
            var list = Module.GetProductInStock(query, UserIdentity, pagerProduct.PageSize,
                                                pagerProduct.CurrentPageIndex, out count);

            rptProductList.DataSource     = list;
            pagerProduct.VirtualItemCount = count;
            rptProductList.DataBind();
        }
        private byte[] RootResHandler(System.Collections.Specialized.NameValueCollection boundVariables,
                                      string outputFormat,
                                      string requestProperties,
                                      out string responseProperties)
        {
            responseProperties = null;

            JSONObject json = new JSONObject();

            json.AddString("name", ".Net Simple REST SOE");
            json.AddString("description", "Simple REST SOE with 1 sub-resource called \"layers\" and 1 operation called \"getLayerCountByType\".");
            json.AddString("usage", "The \"layers\" subresource returns all layers in the map service.\n"
                           + "The \"getLayerCountByType\" operation returns a count of layer of specified type. It accepts one of the following values as input: \"feature\", \"raster\", "
                           + "\"dataset\", and \"all\".");
            return(Encoding.UTF8.GetBytes(json.ToJSONString(null)));
        }
Beispiel #40
0
 private void ReloadProductOnSales(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("productName", Globals.UrlEncode(this.txtSearchText.Text.Trim()));
     if (this.dropCategories.SelectedValue.HasValue)
     {
         nameValueCollection.Add("categoryId", this.dropCategories.SelectedValue.ToString());
     }
     nameValueCollection.Add("pageSize", this.pager.PageSize.ToString());
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString());
     }
     nameValueCollection.Add("SaleStatus", "1");
     this.ReloadPage(nameValueCollection);
 }
Beispiel #41
0
 private void ReBind(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("startTime", this.calendarStart.SelectedDate.ToString());
     nameValueCollection.Add("endTime", this.calendarEnd.SelectedDate.ToString());
     nameValueCollection.Add("productName", this.txtProductName.Text);
     if (this.ddlSupplier.SelectedValue.HasValue)
     {
         nameValueCollection.Add("supplierId", this.ddlSupplier.SelectedValue.Value.ToString());
     }
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString());
     }
     base.ReloadPage(nameValueCollection);
 }
Beispiel #42
0
        public WebSmsSendMessageResponse WebSmsSendMessageQuery(string senderMsisdn, string recipientMsisdn, string message)
        {
            long   rand          = DateTime.Now.Ticks;
            string messageToHash = WebServiceDefinitions.WebSMSAppId + senderMsisdn + message + recipientMsisdn + rand;
            string token         = HashWithHmac(messageToHash, WebServiceDefinitions.WebSMSSecretKey);

            string parameterlessUrl = this.GetUrl(WebServiceDefinitions.Naming.WebSMSMessageQuery);
            string requestUrl       = String.Format(parameterlessUrl + "?action={0}", "sendsms");

            var postData = new System.Collections.Specialized.NameValueCollection();

            postData.Add("appId", WebServiceDefinitions.WebSMSAppId);
            postData.Add("rand", rand.ToString());
            postData.Add("token", token);
            postData.Add("msisdn", senderMsisdn);
            postData.Add("message", message);
            postData.Add("recipient", recipientMsisdn);

            if (WebServiceDefinitions.Platform == WebServiceDefinitions.PlatformCode.Static)
            {
                requestUrl = parameterlessUrl;
            }

            try
            {
                string json = WebServiceDefinitions.Platform == WebServiceDefinitions.PlatformCode.Static ? this.GetJson(requestUrl) : this.GetJsonFromPost(requestUrl, postData);
                Log(new WebServiceLog
                {
                    Status       = LogService.LogStatus.Success.ToString(),
                    Naming       = WebServiceDefinitions.Naming.WebSMSMessageQuery.ToString(),
                    RequestUrl   = requestUrl + "&" + GenerateQueryStringFromPostData(postData),
                    ResponseData = json
                });
                return(ParseJsonObject <WebSmsSendMessageResponse>(json));
            }
            catch (System.Exception ex)
            {
                Log(new WebServiceLog
                {
                    Status       = LogService.LogStatus.Failure.ToString(),
                    Naming       = WebServiceDefinitions.Naming.WebSMSMessageQuery.ToString(),
                    RequestUrl   = requestUrl + "&" + GenerateQueryStringFromPostData(postData),
                    ResponseData = ex.Message
                });
                return(null);
            }
        }
Beispiel #43
0
 private void ReloadProductOnSales(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("productName", Globals.UrlEncode(this.txtSearchText.Text.Trim()));
     if (this.dropCategories.SelectedValue.HasValue)
     {
         nameValueCollection.Add("categoryId", this.dropCategories.SelectedValue.ToString());
     }
     if (this.dropLines.SelectedValue.HasValue)
     {
         nameValueCollection.Add("lineId", this.dropLines.SelectedValue.ToString());
     }
     nameValueCollection.Add("productCode", Globals.UrlEncode(Globals.HtmlEncode(this.txtSKU.Text.Trim())));
     nameValueCollection.Add("pageSize", this.pager.PageSize.ToString());
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString());
     }
     if (this.calendarStartDate.SelectedDate.HasValue)
     {
         nameValueCollection.Add("startDate", this.calendarStartDate.SelectedDate.Value.ToString());
     }
     if (this.calendarEndDate.SelectedDate.HasValue)
     {
         nameValueCollection.Add("endDate", this.calendarEndDate.SelectedDate.Value.ToString());
     }
     if (this.dropBrandList.SelectedValue.HasValue)
     {
         nameValueCollection.Add("brandId", this.dropBrandList.SelectedValue.ToString());
     }
     if (this.dropTagList.SelectedValue.HasValue)
     {
         nameValueCollection.Add("tagId", this.dropTagList.SelectedValue.ToString());
     }
     if (this.dropType.SelectedValue.HasValue)
     {
         nameValueCollection.Add("typeId", this.dropType.SelectedValue.ToString());
     }
     if (this.dropDistributor.SelectedValue.HasValue)
     {
         nameValueCollection.Add("distributorId", this.dropDistributor.SelectedValue.ToString());
     }
     nameValueCollection.Add("isAlert", this.chkIsAlert.Checked.ToString());
     nameValueCollection.Add("SaleStatus", this.dropSaleStatus.SelectedValue.ToString());
     nameValueCollection.Add("PenetrationStatus", this.dropPenetrationStatus.SelectedValue.ToString());
     base.ReloadPage(nameValueCollection);
 }
Beispiel #44
0
        public void Deserialize(string value, System.Collections.Specialized.NameValueCollection parameters)
        {
            if (string.Equals(parameters["VALUE"], "DATE-TIME", StringComparison.OrdinalIgnoreCase))
            {
                DateTime = value.ToDateTime();
            }
            else
            {
                Relateds related;
                if (System.Enum.TryParse <Relateds>(parameters["RELATED"], true, out related))
                {
                    Related = related;
                }

                var duration = TimeSpan.Zero;
                var neg      = false;
                var num      = "";
                foreach (var c in value.ToUpper())
                {
                    if (char.IsDigit(c))
                    {
                        num += c;
                    }
                    else
                    {
                        switch (c)
                        {
                        case '-': neg = true; continue;

                        case 'W': duration = duration.Add(TimeSpan.FromDays((num.ToInt() ?? 0) * 7)); break;

                        case 'D': duration = duration.Add(TimeSpan.FromDays(num.ToInt() ?? 0)); break;

                        case 'H': duration = duration.Add(TimeSpan.FromHours(num.ToInt() ?? 0)); break;

                        case 'M': duration = duration.Add(TimeSpan.FromMinutes(num.ToInt() ?? 0)); break;

                        case 'S': duration = duration.Add(TimeSpan.FromSeconds(num.ToInt() ?? 0)); break;
                        }
                        num = string.Empty;
                    }
                }

                Duration = neg ? -duration : duration;
            }
        }
Beispiel #45
0
 private void ReBind(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("PayId", this.PayId);
     nameValueCollection.Add("UserName", this.UserName);
     nameValueCollection.Add("StartTime", this.StartTime);
     nameValueCollection.Add("EndTime", this.EndTime);
     nameValueCollection.Add("TradeType", this.TradeTypeValue);
     nameValueCollection.Add("TradeWays", this.TradeWaysValue);
     nameValueCollection.Add("pageSize", this.pager.PageSize.ToString(System.Globalization.CultureInfo.InvariantCulture));
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
     }
     nameValueCollection.Add("lastDay", this.lastDay.ToString());
     base.ReloadPage(nameValueCollection);
 }
 private async void btnEliminar_Clicked(object sender, EventArgs e)
 {
     try
     {
         using (WebClient cliente = new WebClient())
         {
             var parametros = new System.Collections.Specialized.NameValueCollection();
             parametros.Add("idpersona", txtEliminar.Text);
             cliente.UploadValues(Url, "DELETE", cliente.QueryString = parametros);
         }
         await DisplayAlert("Alerta", "Dato Eliminado correctamente", "OK");
     }
     catch (Exception ex)
     {
         await DisplayAlert("Alerta", "ERROR: " + ex.Message, "OK");
     }
 }
        /// <summary>
        /// Encodes a collection of data to the request stream.
        /// </summary>
        /// <param name="tw"></param>
        /// <param name="data"></param>
        protected void AddCollectionData(System.IO.TextWriter tw, System.Collections.Specialized.NameValueCollection data)
        {
            bool first = true;

            foreach (string key in data)
            {
                if (first)
                {
                    tw.Write("{0}={1}", key, Encode(data[key]));
                    first = false;
                }
                else
                {
                    tw.Write("&{0}={1}", key, Encode(data[key]));
                }
            }
        }
Beispiel #48
0
        private void ReBind(bool isSearch)
        {
            System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();

            //nameValueCollection.Add("Username", this.txtSearchText.Text);


            //nameValueCollection.Add("MemberStatus", this.MemberStatus.SelectedItem.Value);
            //nameValueCollection.Add("clientType", (this.ViewState["ClientType"] != null) ? this.ViewState["ClientType"].ToString() : "");
            //nameValueCollection.Add("pageSize", this.pager.PageSize.ToString(System.Globalization.CultureInfo.InvariantCulture));
            //nameValueCollection.Add("phone", this.txtPhone.Text);
            //if (!isSearch)
            //{
            //    nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
            //}
            base.ReloadPage(nameValueCollection);
        }
    public bool UploadQuest(Quest quest, User user)
    {
        var data = new System.Collections.Specialized.NameValueCollection();

        data.Add("username", user.GetUsername());
        data.Add("user_id", "" + user.GetUserID());
        data.Add("quest_name", quest.info.Title);
        data.Add("quest_description", quest.info.Desc);
        data.Add("quest_xp", "" + quest.Xp_reward);
        data.Add("quest_level", "" + quest.Level);
        data.Add("start_lat", "" + quest.Start_co.Lat);
        data.Add("start_long", "" + quest.Start_co.Lon);
        data.Add("end_lat", "" + quest.Stop_co.Lat);
        data.Add("end_long", "" + quest.Stop_co.Lon);

        return(!WebCommunication("upload_quest", data).error);
    }
        private string GetAuthenticationToken()
        {
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                var reqparm = new System.Collections.Specialized.NameValueCollection();
                reqparm.Add("username", UserName);
                reqparm.Add("password", Password);
                byte[] responsebytes = client.UploadValues("https://exist.io/api/1/auth/simple-token/", "POST",
                                                           reqparm);
                string responsebody = Encoding.UTF8.GetString(responsebytes);

                var token = JsonConvert.DeserializeObject <ExistioToken>(responsebody);
                return(token.Token);
            }
        }
Beispiel #51
0
    public static T ToModel <T>(this System.Collections.Specialized.NameValueCollection ValueCollection) where T : new()
    {
        T    ts = new T();
        Type t  = typeof(T);

        foreach (var key in ValueCollection.AllKeys)
        {
            try
            {
                Type tt = t.GetProperty(key).GetMethod.ReturnType;
                t.GetProperty(key).SetValue(ts, Convert.ChangeType(Fun.Query(key), tt));
            }
            catch (Exception ex) { }
        }

        return((T)ts);
    }
Beispiel #52
0
        private void ReBind(bool isSearch)
        {
            System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
            string arg_20_0 = this.Page.Request.QueryString["subLevel"];

            nameValueCollection.Add("UserId", this.Page.Request.QueryString["UserId"]);
            nameValueCollection.Add("StartTime", this.StartTime);
            nameValueCollection.Add("EndTime", this.EndTime);
            nameValueCollection.Add("subLevel", this.subLevel);
            nameValueCollection.Add("pageSize", this.pager.PageSize.ToString(System.Globalization.CultureInfo.InvariantCulture));
            if (!isSearch)
            {
                nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
            }
            nameValueCollection.Add("lastDay", this.lastDay.ToString());
            base.ReloadPage(nameValueCollection);
        }
Beispiel #53
0
        public ApiRequest(string url, string token)
        {
            this.url = url;

            request = (HttpWebRequest)WebRequest.Create(this.url);

            if (!String.IsNullOrEmpty(token))
            {
                var tokenHeader = new System.Collections.Specialized.NameValueCollection();
                tokenHeader.Add("token", token);

                if (tokenHeader.Count > 0)
                {
                    request.Headers.Add(tokenHeader);
                }
            }
        }
Beispiel #54
0
 private void BindQuery()
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     if (!string.IsNullOrEmpty(this.txtcompany.Text.Trim()))
     {
         nameValueCollection.Add("cname", Globals.UrlEncode(this.txtcompany.Text.Trim()));
     }
     if (!string.IsNullOrEmpty(this.txtKuaidi100Code.Text.Trim()))
     {
         nameValueCollection.Add("kuaidi100Code", Globals.UrlEncode(this.txtKuaidi100Code.Text.Trim()));
     }
     if (!string.IsNullOrEmpty(this.txtTaobaoCode.Text.Trim()))
     {
         nameValueCollection.Add("taobaoCode", Globals.UrlEncode(this.txtTaobaoCode.Text.Trim()));
     }
     base.ReloadPage(nameValueCollection);
 }
Beispiel #55
0
        internal PageRequest(ThreadEntity entity)
        {
            _innerRequest = entity.WebContext.Request;
            _values       = new System.Collections.Specialized.NameValueCollection();
            _groupNvc     = new System.Collections.Specialized.NameValueCollection();

            System.Text.RegularExpressions.GroupCollection _groupMatched = entity.URLItem.Regex.Match(entity.URL.Path).Groups;
            for (int i = 0; i < entity.URLItem.URLGroupsName.Length; i++)
            {
                string _key = entity.URLItem.URLGroupsName[i];
                _groupNvc.Add(_key, _groupMatched[_key].Value);
            }

            _values.Add(_innerRequest.QueryString);
            _values.Add(_innerRequest.Form);
            _values.Add(_groupNvc);
        }
Beispiel #56
0
 private void ReloadRefundNotes(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("OrderId", this.txtOrderId.Text);
     nameValueCollection.Add("PageSize", this.pager.PageSize.ToString());
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString());
     }
     if (!string.IsNullOrEmpty(this.Page.Request.QueryString["GroupBuyId"]))
     {
         nameValueCollection.Add("GroupBuyId", this.Page.Request.QueryString["GroupBuyId"]);
     }
     nameValueCollection.Add("StartDate", this.calendarStartDate.Text);
     nameValueCollection.Add("EndDate", this.calendarEndDate.Text);
     base.ReloadPage(nameValueCollection);
 }
Beispiel #57
0
 private void ReBind(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     nameValueCollection.Add("Receiver", this.txtReceiver.Text);
     nameValueCollection.Add("ProductName", this.txtProductName.Text);
     nameValueCollection.Add("StartDate", this.StartDate);
     nameValueCollection.Add("EndDate", this.EndDate);
     nameValueCollection.Add("AddrReggion", this.AddrReggion);
     nameValueCollection.Add("ShowTabNum", this.ShowTabNum);
     nameValueCollection.Add("ActitivyTitle", this.ActitivyTitle);
     nameValueCollection.Add("pageSize", this.pager.PageSize.ToString(System.Globalization.CultureInfo.InvariantCulture));
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
     }
     base.ReloadPage(nameValueCollection);
 }
Beispiel #58
0
 private void ReBind(bool isSearch)
 {
     System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
     if (this.rankList.SelectedValue.HasValue)
     {
         nameValueCollection.Add("rankId", this.rankList.SelectedValue.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
     }
     nameValueCollection.Add("searchKey", this.txtSearchText.Text);
     nameValueCollection.Add("realName", this.txtRealName.Text);
     nameValueCollection.Add("pageSize", this.pager.PageSize.ToString(System.Globalization.CultureInfo.InvariantCulture));
     nameValueCollection.Add("Approved", this.ddlApproved.SelectedValue.ToString());
     if (!isSearch)
     {
         nameValueCollection.Add("pageIndex", this.pager.PageIndex.ToString(System.Globalization.CultureInfo.InvariantCulture));
     }
     base.ReloadPage(nameValueCollection);
 }
Beispiel #59
0
 public void LoadConfig(string data)
 {
     lock (this)
     {
         ConfigMD5 = MD5Encoding(data);
         string filename;
         filename = AppDomain.CurrentDomain.BaseDirectory + string.Format("{0}{1}{2}.config", Name, "_tmp", "");
         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename, false, Encoding.UTF8))
         {
             writer.Write(data);
         }
         System.Configuration.ExeConfigurationFileMap fm = new System.Configuration.ExeConfigurationFileMap();
         fm.ExeConfigFilename = filename;
         mConfiguration       = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fm, System.Configuration.ConfigurationUserLevel.None);
         mAppSetting          = null;
     }
 }
Beispiel #60
0
        public void AddToSubjectTableFailTest()
        {
            CreateDataFile();

            // Mock a request with missing data
            var querystring = new System.Collections.Specialized.NameValueCollection {
                { "Email", "12345" }
            };
            var mock = new Mock <ControllerContext>();

            mock.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring);

            HomeController controller = new HomeController();

            controller.ControllerContext = mock.Object;
            controller.AddToSubjectTable();
        }