Exemple #1
0
        private static async Task <NameValueCollection> ReadAsAsyncCore(HttpContent content, MediaTypeFormatter[] formatters,
                                                                        CancellationToken cancellationToken)
        {
            FormDataCollection formData = await content.ReadAsAsync <FormDataCollection>(formatters, cancellationToken);

            return(formData == null ? null : formData.ReadAsNameValueCollection());
        }
Exemple #2
0
        public HttpResponseMessage OnlineBooking(FormDataCollection formbody)
        {
            try
            {
                var formData = formbody.ReadAsNameValueCollection();

                EmailService emailService = new EmailService();

                string email = emailService.ConvertToEmail(formData);

                emailService.SendMailOnlinebuchung(email);

                var response = Request.CreateResponse(HttpStatusCode.Moved);
                response.Headers.Location = new Uri("http://www.massage-lounge-duesseldorf.de/onlineBookingsuccess.html");
                //response.Headers.Location = new Uri("http://localhost:51010/Application/onlinebookingsuccess.html");
                return(response);
            }
            catch (System.Exception e)
            {
                string erroeMessage = string.Format("Message: {0}, Source: {1}, InnerException: {2} ",
                                                    e.Message,
                                                    e.Source,
                                                    e.InnerException);

                Helper.log.Debug(erroeMessage);

                //return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);

                var response = Request.CreateResponse(HttpStatusCode.Moved);
                response.Headers.Location = new Uri("http://www.massage-lounge-duesseldorf.de/404.html");
                //response.Headers.Location = new Uri("http://localhost:51010/404.html");
                return(response);
            }
        }
Exemple #3
0
        public HttpResponseMessage SendSkrillDepositStatus([FromBody] FormDataCollection collection)
        {
            Log.InfoFormat("Got requests from [{0}] and sending Skrill deposit status.\n{1}",
                           _networkUtility.GetClientIPAddress(), collection == null ? string.Empty : string.Join(", ", collection));

            try
            {
                var depositUrl =
                    new Uri(string.Format("{0}/{1}/{2}", _configurations.DefaultDomain, CultureCode,
                                          _configurations.DepositPath));

                var casinoUrl =
                    new Uri(string.Format("{0}/{1}/{2}", _configurations.DefaultDomain, CultureCode,
                                          _configurations.CasinoPath));

                _paymentApiProxy.SendSkrillDepositNotification(CultureCode,
                                                               collection != null ? collection.ReadAsNameValueCollection() : new NameValueCollection(),
                                                               depositUrl, casinoUrl);
            }
            catch (DepositNotificationNotSentException ex)
            {
                Log.Error("Failed to send Skrill deposit status", ex);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Exemple #4
0
        public async Task <HttpResponseMessage> Notify(FormDataCollection collection)
        {
            var right = await NotifyHelper.NotifyAndVerify(collection.ReadAsNameValueCollection());

            return(new HttpResponseMessage {
                Content = new StringContent(right ? "success" : "fail", System.Text.Encoding.UTF8, "text/plain")
            });
        }
        //public Car Post(Car car) {
        //    if (null != car) {
        //        car.Id = 1;
        //        return car;
        //    }
        //    throw new HttpResponseException(new HttpResponseMessage() {
        //        StatusCode = HttpStatusCode.BadRequest,
        //        ReasonPhrase = "Car data must contain at least one value."
        //    });
        //}

        public Car Post(FormDataCollection carFormData) {
            var carFormKeyValues = carFormData.ReadAsNameValueCollection();
            var car = new Car() {
                Make = carFormKeyValues["Make"],
                Model = carFormKeyValues["Model"],
                Price = Convert.ToSingle(carFormKeyValues["Price"]),
                Year = Convert.ToInt32(carFormKeyValues["Year"])
            };
            return car;
        }
Exemple #6
0
        public ThingModel UpdateThing(string id, [FromBody] FormDataCollection form)
        {
            /* The ThingModel holds the logic for converting NameValueCollectio into a Thing
             * (or updating an existing thing if it has one already). We simply pass it along
             * and return the results. */
            var dataSet = form.ReadAsNameValueCollection();

            dataSet["id"] = id;
            return(ThingModel.FromNameValueCollection(Lib.UserUtils.GetUser(this).RepoId, dataSet, true));
        }
 public IHttpActionResult Counter([FromBody] FormDataCollection request)
 {
     try
     {
         var dataCollection = request.ReadAsNameValueCollection();
         var res            = _statService.CountingWords(dataCollection["input"]);
         return(Ok(res));
     }
     catch (Exception)
     {
         return(BadRequest("Error trying to analyze input for statistics"));
     }
 }
Exemple #8
0
 public static object ConvertToObject(this FormDataCollection formDataCollection, Type type)
 {
     try
     {
         DefaultModelBinder  binder = new DefaultModelBinder();
         ModelBindingContext modelBindingContext = new ModelBindingContext()
         {
             ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, type),
             ValueProvider = new FormValueProvider(formDataCollection.ReadAsNameValueCollection())
         };
         return(binder.BindModel(new ControllerContext(), modelBindingContext));
     }
     catch (Exception)
     {
         return(null);
     }
 }
        public void Put(FormDataCollection form)
        {
            // Manually parse up the form b/c of the muni & county split stuff
            // TODO: make a custom formatter
            int projectVersionId = Convert.ToInt32(form.Get("ProjectVersionId"));
            string year = form.Get("Year");
            //Get the existing model from the datagbase
            LocationModel model = SurveyRepository.GetProjectLocationModel(projectVersionId, year);
            //Update values
            model.Limits = form.Get("Limits");
            model.FacilityName = form.Get("FacilityName");
            int testOut = 0;
            Int32.TryParse(form.Get("RouteId"), out testOut);
            model.RouteId = testOut;

            //parse out the county & muni shares stuff...
            var nvc = form.ReadAsNameValueCollection();
            Dictionary<int, CountyShareModel> countyShares = ControllerBase.ExtractCountyShares(nvc);
            Dictionary<int, MunicipalityShareModel> muniShares = ControllerBase.ExtractMuniShares(nvc);

            //Send updates to repo
            try
            {
                SurveyRepository.UpdateProjectLocationModel(model, projectVersionId);
                SurveyRepository.CheckUpdateStatusId(SurveyRepository.GetProjectBasics(projectVersionId));
                //Update the county shares
                foreach (CountyShareModel m in countyShares.Values)
                {
                    SurveyRepository.UpdateCountyShare(m);
                }
                //Update the muni shares
                foreach (MunicipalityShareModel m in muniShares.Values)
                {
                    SurveyRepository.UpdateMunicipalityShare(m);
                }
                //Ok, we're good.
            }
            catch (Exception ex)
            {
                Logger.WarnException("Could not update Survey Location", ex);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ExpectationFailed) { ReasonPhrase = ex.Message });
            }
        }
            // Read the body upfront , add as a ValueProvider
            public override Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
            {
                HttpRequestMessage request = actionContext.ControllerContext.Request;
                HttpContent        content = request.Content;

                if (content != null)
                {
                    FormDataCollection fd = content.ReadAsAsync <FormDataCollection>().Result;
                    if (fd != null)
                    {
                        NameValueCollection nvc = fd.ReadAsNameValueCollection();

                        IValueProvider vp = new NameValueCollectionValueProvider(nvc, CultureInfo.InvariantCulture);

                        request.Properties.Add(Key, vp);
                    }
                }

                return(base.ExecuteBindingAsync(actionContext, cancellationToken));
            }
Exemple #11
0
        // Post form data
        public string PostFormData(FormDataCollection a)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            try
            {
                NameValueCollection collection = a.ReadAsNameValueCollection();
            }
            catch (InvalidOperationException ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }

            return("success from PostFormData");
        }
Exemple #12
0
        private static bool ParseCookieSegment(CookieHeaderValue instance, string segment)
        {
            if (String.IsNullOrWhiteSpace(segment))
            {
                return(true);
            }

            string[] nameValue = segment.Split(nameValueSeparator, 2);
            if (nameValue.Length < 1 || String.IsNullOrWhiteSpace(nameValue[0]))
            {
                return(false);
            }

            string name = nameValue[0].Trim();

            if (String.Equals(name, ExpiresToken, StringComparison.OrdinalIgnoreCase))
            {
                string         value = GetSegmentValue(nameValue, null);
                DateTimeOffset expires;
                if (FormattingUtilities.TryParseDate(value, out expires))
                {
                    instance.Expires = expires;
                    return(true);
                }
                return(false);
            }
            else if (String.Equals(name, MaxAgeToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                int    maxAge;
                if (FormattingUtilities.TryParseInt32(value, out maxAge))
                {
                    instance.MaxAge = new TimeSpan(0, 0, maxAge);
                    return(true);
                }
                return(false);
            }
            else if (String.Equals(name, DomainToken, StringComparison.OrdinalIgnoreCase))
            {
                instance.Domain = GetSegmentValue(nameValue, null);
                return(true);
            }
            else if (String.Equals(name, PathToken, StringComparison.OrdinalIgnoreCase))
            {
                instance.Path = GetSegmentValue(nameValue, DefaultPath);
                return(true);
            }
            else if (String.Equals(name, SecureToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                if (!String.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }
                instance.Secure = true;
                return(true);
            }
            else if (String.Equals(name, HttpOnlyToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                if (!String.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }
                instance.HttpOnly = true;
                return(true);
            }
            else
            {
                string value = GetSegmentValue(nameValue, null);

                // We read the cookie segment as form data
                try
                {
                    FormDataCollection  formData = new FormDataCollection(value);
                    NameValueCollection values   = formData.ReadAsNameValueCollection();
                    CookieState         cookie   = new CookieState(name, values);
                    instance.Cookies.Add(cookie);
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
        private static bool ParseCookieSegment(CookieHeaderValue instance, string segment)
        {
            if (String.IsNullOrWhiteSpace(segment))
            {
                return true;
            }

            string[] nameValue = segment.Split(nameValueSeparator, 2);
            if (nameValue.Length < 1 || String.IsNullOrWhiteSpace(nameValue[0]))
            {
                return false;
            }

            string name = nameValue[0].Trim();
            if (String.Equals(name, ExpiresToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                DateTimeOffset expires;
                if (FormattingUtilities.TryParseDate(value, out expires))
                {
                    instance.Expires = expires;
                    return true;
                }
                return false;
            }
            else if (String.Equals(name, MaxAgeToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                int maxAge;
                if (FormattingUtilities.TryParseInt32(value, out maxAge))
                {
                    instance.MaxAge = new TimeSpan(0, 0, maxAge);
                    return true;
                }
                return false;
            }
            else if (String.Equals(name, DomainToken, StringComparison.OrdinalIgnoreCase))
            {
                instance.Domain = GetSegmentValue(nameValue, null);
                return true;
            }
            else if (String.Equals(name, PathToken, StringComparison.OrdinalIgnoreCase))
            {
                instance.Path = GetSegmentValue(nameValue, DefaultPath);
                return true;
            }
            else if (String.Equals(name, SecureToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                if (!String.IsNullOrWhiteSpace(value))
                {
                    return false;
                }
                instance.Secure = true;
                return true;
            }
            else if (String.Equals(name, HttpOnlyToken, StringComparison.OrdinalIgnoreCase))
            {
                string value = GetSegmentValue(nameValue, null);
                if (!String.IsNullOrWhiteSpace(value))
                {
                    return false;
                }
                instance.HttpOnly = true;
                return true;
            }
            else
            {
                string value = GetSegmentValue(nameValue, null);

                // We read the cookie segment as form data
                try
                {
                    FormDataCollection formData = new FormDataCollection(value);
                    NameValueCollection values = formData.ReadAsNameValueCollection();
                    CookieState cookie = new CookieState(name, values);
                    instance.Cookies.Add(cookie);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }
Exemple #14
0
 public ThingModel UpdateThing([FromBody] FormDataCollection form)
 {
     return(ThingModel.FromNameValueCollection(Lib.UserUtils.GetUser(this).RepoId, form.ReadAsNameValueCollection(), true));
 }
Exemple #15
0
        /// <summary>
        /// Factory method to make a type of LookTreeNode from the supplied (hyphen delimited) id
        /// </summary>
        /// <param name="id">"-1" or hyphen delimited, first part the node type, the 2nd a value/id</param>
        internal static ILookTreeNode MakeLookTreeNode(string id, FormDataCollection queryStrings)
        {
            if (id == "-1")
            {
                return(new RootTreeNode(id, queryStrings));
            }

            var nodeType   = id.Split('-')[0];
            var nodeParams = id.Split('-')[1]; // TODO: FIX: everything after the first hyphen

            switch (nodeType)
            {
            case "searcher":
                queryStrings.ReadAsNameValueCollection()["searcherName"] = nodeParams;

                return(new SearcherTreeNode(queryStrings));

            case "nodes":
                queryStrings.ReadAsNameValueCollection()["searcherName"] = nodeParams;

                return(new NodesTreeNode(queryStrings));

            case "nodeType":
                var nodeTypeParams = nodeParams.Split('|');

                queryStrings.ReadAsNameValueCollection()["searcherName"] = nodeTypeParams[0];
                queryStrings.ReadAsNameValueCollection()["nodeType"]     = nodeTypeParams[1];

                return(new NodeTypeTreeNode(queryStrings));

            case "detached":
                var detachedParams = nodeParams.Split('|');

                queryStrings.ReadAsNameValueCollection()["searcherName"] = detachedParams[0];
                queryStrings.ReadAsNameValueCollection()["nodeType"]     = detachedParams[1];

                return(new DetachedTreeNode(queryStrings));

            case "tags":
                queryStrings.ReadAsNameValueCollection()["searcherName"] = nodeParams;

                return(new TagsTreeNode(queryStrings));

            case "tagGroup":
                var tagGroupParams = nodeParams.Split('|');

                queryStrings.ReadAsNameValueCollection()["searcherName"] = tagGroupParams[0];
                queryStrings.ReadAsNameValueCollection()["tagGroup"]     = tagGroupParams[1];

                return(new TagGroupTreeNode(queryStrings));

            case "tag":
                var tagParams = nodeParams.Split('|').Take(3).ToArray();     // limit chop, as tag name may contain delimiter

                queryStrings.ReadAsNameValueCollection()["searcherName"] = tagParams[0];
                queryStrings.ReadAsNameValueCollection()["tagGroup"]     = tagParams[1];
                queryStrings.ReadAsNameValueCollection()["tagName"]      = tagParams[2];

                return(new TagTreeNode(queryStrings));    // create tag node without count

            case "locations":
                queryStrings.ReadAsNameValueCollection()["searcherName"] = nodeParams;

                return(new LocationsTreeNode(queryStrings));
            }

            return(null);
        }
        // Post form data
        public string PostFormData(FormDataCollection a)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            try
            {
                NameValueCollection collection = a.ReadAsNameValueCollection();
            }
            catch (InvalidOperationException ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }

            return "success from PostFormData";
        }
        public void ToNameValueCollection()
        {
            FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1a&y=2&x=1b&=ValueOnly&KeyOnly"));

            NameValueCollection nvc = form.ReadAsNameValueCollection();

            // y=2
            // x=1a;x=1b
            // =ValueOnly
            // KeyOnly
            Assert.Equal(4, nvc.Count);
            Assert.Equal(new string[] { "1a", "1b"}, nvc.GetValues("x"));
            Assert.Equal("1a,1b", nvc.Get("x"));
            Assert.Equal("2", nvc.Get("y"));
            Assert.Equal("", nvc.Get("KeyOnly"));            
            Assert.Equal("ValueOnly", nvc.Get(""));
        }
        public void CaseSensitive()
        {
            FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1&X=2"));

            NameValueCollection nvc = form.ReadAsNameValueCollection();

            Assert.Equal(2, nvc.Count);
            Assert.Equal("1", nvc.Get("x"));
            Assert.Equal("2", nvc.Get("X"));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="vendor"></param>
        /// <param name="postedData"></param>
        public HttpResponseMessage PostTransactionByIpn([FromUri] string id, [FromBody] FormDataCollection postedData)
        {
            var vendorId = Guid.Parse(id);
            var txn      = new Transaction();
            var d        = postedData.ReadAsNameValueCollection();

            //To calculate 'handshake', run 'md5 -s [password]', then 'md5 -s [email protected][Last MD5 result]'
            string handshakeParameter = d.Pluck("handshake", null);

            if (handshakeParameter == null)
            {
                throw new Exception("Missing parameter 'handshake'.");
            }

            using (var dataContext = dataContextFactory.Create())
            {
                var vendor =
                    dataContext.Vendors.Where(v => v.ObjectId == vendorId)
                    .Include(v => v.VendorCredentials)
                    .FirstOrDefault();

                if (vendor == null)
                {
                    throw new Exception("Could not find vendor with id: " + vendorId);
                }

                string[] vendorCredentials = vendor.VendorCredentials.Select(
                    c => Encoding.UTF8.GetString(SymmetricEncryption.DecryptForDatabase(c.CredentialValue)).ToLower()).ToArray();

                if (!vendorCredentials.Contains(handshakeParameter.ToLower()))
                {
                    throw new Exception("Invalid handshake provided");
                }
            }

            string txn_id = d.Pluck("txn_id");

            //TODO: We must ignore duplicate POSTs with the same txn_id - all POSTs will contain the same information

            if (!"Completed".Equals(d.Pluck("payment_status"), StringComparison.OrdinalIgnoreCase))
            {
                throw new Exception("Only completed transactions should be sent to this URL");
            }

            //var txn = new Transaction();
            txn.VendorId = vendorId;
            txn.ExternalTransactionId = txn_id;
            txn.PaymentDate           = ConvertPayPalDateTime(d.Pluck("payment_date"));
            txn.PayerEmail            = d.Pluck("payer_email");
            txn.PassThroughData       = d.Pluck("custom");
            txn.Currency        = d.Pluck("mc_currency");
            txn.InvoiceId       = d.Pluck("invoice");
            txn.Gross           = d.Pluck <double>("mc_gross");
            txn.TransactionFee  = d.Pluck <double>("mc_fee");
            txn.Tax             = d.Pluck <double>("tax");
            txn.TransactionType = d.Pluck("transaction_type");

            if (d["payer_name"] == null)
            {
                d["payer_name"] = d["first_name"] + " " + d["last_name"];
            }

            txn.Billing  = ParseFrom(d, "payer_");
            txn.Shipping = ParseFrom(d, "address_");

            var itemCount = d.Pluck <int>("num_cart_items", 1);

            txn.Items = new List <TransactionItem>();
            for (var i = 1; i <= itemCount; i++)
            {
                string suffix = i.ToString();
                var    item   = new TransactionItem();
                item.Gross     = d.Pluck <double>("mc_gross_" + i.ToString()).Value;
                item.ItemName  = d.Pluck("item_name" + i.ToString());
                item.SkuString = d.Pluck("item_number" + i.ToString());
                item.Options   = new List <KeyValuePair <string, string> >();
                for (var j = 1; j < 4; j++)
                {
                    string opt_key = d.Pluck("option_name" + j.ToString() + "_" + i.ToString());
                    string opt_val = d.Pluck("option_selection" + j.ToString() + "_" + i.ToString());
                    if (string.IsNullOrEmpty(opt_val))
                    {
                        continue;
                    }
                    item.Options.Add(new KeyValuePair <string, string>(opt_key, opt_val));
                }

                var qty = d.Pluck <int>("quantity" + i.ToString(), 1).Value;
                for (var j = 0; j < qty; j++)
                {
                    txn.Items.Add(item.DeepCopy());
                }
            }

            if (!string.IsNullOrEmpty(d["gc_xml"]))
            {
                txn.ProcessorXml = new XmlDocument();
                txn.ProcessorXml.LoadXml(d.Pluck("gc_xml"));
            }

            txn.Other = d;

            //All transactions go through TransactionController
            using (var basket = BasketWrapper.CreateNewByVendor(dataContextFactory, vendorId))
            {
                base.ProcessTransaction(txn.ToTransactionRequest(dataContextFactory), basket);
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }