public void Login(string loginPageAddress, NameValueCollection loginData)
        {
            CookieContainer container;

            var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            var buffer = Encoding.ASCII.GetBytes(loginData.ToString());

            request.ContentLength = buffer.Length;
            var requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            container = request.CookieContainer = new CookieContainer();

            var response = request.GetResponse();

            var stmr = new StreamReader(response.GetResponseStream());
            var json = stmr.ReadToEnd();
            readtofile(json);
            //if (json.Contains("loginphrase"))
            //{
            //    MessageBox.Show("Invalid Username or Password", "Login Fail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            //else
            //{

            //}
            response.Close();
            CookieContainer = container;
        }
Beispiel #2
0
        public static void EbexeForward(NameValueCollection queryString)
        {
            string remoteUrl = MarcosServerUri.ToString() +
                               "edms/exe/eb.exe?" + queryString.ToString();

            GetUrl(remoteUrl, true);
        }
        public string MakeYoutubeAuthorizationRequest(NameValueCollection queryString, HttpClient httpClient)
        {
            var authUrl = "https://accounts.google.com/o/oauth2/token";

            var content = new StringContent(queryString.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");

            var exchangePostResponse = httpClient.PostAsync(authUrl, content).Result;
            var resp = exchangePostResponse.Content.ReadAsStringAsync().Result;

            return resp;
        }
Beispiel #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            System.Collections.Specialized.NameValueCollection s = Request.QueryString;

            if (s.Count != 1)
            {
                return;
            }
            string query = HttpUtility.UrlDecode(s.ToString());

            if (query.Contains("id=") && query.Contains("url="))
            {
                string date = DateTime.Now.ToString("yyyyMMdd");
                Guid   id;
                try
                {
                    id = new Guid(query.Substring(query.IndexOf("=") + 1, query.IndexOf("&") - 3));
                }
                catch
                {
                    return;
                }
                int type = string.IsNullOrEmpty(Request.QueryString["type"]) ? 1 : 0;

                ClickInfo info = new ClickInfo();
                info.ClickType = type;
                info.ClickDate = date;
                info.UserAdsId = id;

                if (ClickService.SelectHasCount(info))
                {
                    ClickService.UpdateClickInfo(info);
                }
                else
                {
                    info.ClickCount = 1;
                    ClickService.InsertClickInfo(info);
                }

                string url = query.Substring(query.IndexOf("url=") + 4);
                url = url.Contains("?") ? url + "&" : url + "?";

                Response.Write(@"<script language='javascript' type='text/javascript'  src='http://js.users.51.la/12120626.js'></script><script>if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
var referLink=document.createElement('a');
referLink.href='" + url + "spm=2018.12167184.0.0';document.body.appendChild(referLink);referLink.click();}else{location.href='" + url + "spm=2018.12167184.0.0';}</script>");
            }
        }
    }
Beispiel #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="postCollection"></param>
        /// <returns></returns>
        private string Execute(NameValueCollection postCollection)
        {
            var request = WebRequest.Create(ServiceUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = WebRequestMethods.Http.Post;

            postCollection["file"] = "json";
            postCollection["f"] = "get_data";
            var postData = postCollection.ToString();

            var byteArray = new ASCIIEncoding().GetBytes(postData);
            request.ContentLength = byteArray.Length;

            Stream stream = null;
            StreamReader streamReader = null;
            WebResponse response = null;

            try
            {
                // POST REQUEST
                stream = request.GetRequestStream();
                stream.Write(byteArray, 0, byteArray.Length);
                stream.Close();

                // GET RESPONSE
                response = request.GetResponse();
                stream = response.GetResponseStream();

                // READ RESPONSE
                streamReader = new StreamReader(stream);
                var responseFromServer = streamReader.ReadToEnd();

                // RETURN RESPONSE
                return responseFromServer;

            }
            finally
            {
                if (streamReader != null)
                    streamReader.Close();

                if (stream != null)
                    stream.Close();

                if (response != null)
                    response.Close();
            }
        }
Beispiel #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            System.Collections.Specialized.NameValueCollection s = Request.QueryString;

            if (s.Count != 1)
            {
                return;
            }
            string query = HttpUtility.UrlDecode(s.ToString());

            if (query.Contains("id=") && query.Contains("url="))
            {
                string date = DateTime.Now.ToString("yyyyMMdd");
                Guid   id;
                try
                {
                    id = new Guid(query.Substring(query.IndexOf("=") + 1, query.IndexOf("&") - 3));
                }
                catch
                {
                    return;
                }
                int type = string.IsNullOrEmpty(Request.QueryString["type"]) ? 1 : 0;

                ClickInfo info = new ClickInfo();
                info.ClickType = type;
                info.ClickDate = date;
                info.UserAdsId = id;

                if (ClickService.SelectHasCount(info))
                {
                    ClickService.UpdateClickInfo(info);
                }
                else
                {
                    info.ClickCount = 1;
                    ClickService.InsertClickInfo(info);
                }

                string url = query.Substring(query.IndexOf("url=") + 4);
                url = url.Contains("?") ? url + "&" : url + "?";

                Response.Redirect(url);
            }
        }
    }
        private HttpWebRequest CreateRequest(string relativePath, NameValueCollection queryStringCollection = null)
        {
            if (relativePath == null)
            {
                throw new ArgumentNullException("relativePath");
            }

            queryStringCollection = queryStringCollection ?? CreateQueryStringCollection();

            queryStringCollection.Add("key", this.key);

            var uri = this.urlBase + relativePath + "?" + queryStringCollection.ToString();

            var request = WebRequest.CreateHttp(uri);

            return request;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            System.Collections.Specialized.NameValueCollection s = Request.QueryString;

            if (s.Count != 1)
            {
                return;
            }

            string id = s.ToString();

            string goodsId = tuiDal.GetGoodsId(id);

            Response.Redirect("http://item.taobao.com/item.htm?id=" + goodsId);
        }
    }
Beispiel #9
0
 public void PostToImgur(string filename)
 {
     changeValueEnabled();
     Bitmap bitmap = new Bitmap(filename);
     MemoryStream memoryStream = new MemoryStream();
     bitmap.Save(memoryStream, ImageFormat.Jpeg);
     using (var w = new WebClient())
     {
         w.UploadProgressChanged += new UploadProgressChangedEventHandler(delegate(object send, UploadProgressChangedEventArgs arg)
             {
                 int percent = arg.ProgressPercentage;
                 progressBar.Value = percent > 0 ? (percent < 45 ? percent * 2 : (percent >= 90 ? percent : 90)) : 0;
             });
         this.FormClosing += new FormClosingEventHandler(delegate(object send, FormClosingEventArgs arg)
             {
                 w.CancelAsync();
             });
         var values = new NameValueCollection
         {
             { "key", IMGUR_API_KEY },
             { "image", Convert.ToBase64String(memoryStream.ToArray()) }
         };
         string debug = values.ToString();
         byte[] response = new byte[0];
         w.UploadValuesCompleted += new UploadValuesCompletedEventHandler(delegate(object send, UploadValuesCompletedEventArgs arg)
         {
             if (arg.Cancelled) return;
             response = arg.Result;
             XDocument xDocument = XDocument.Load(new MemoryStream(response));
             bitmap.Dispose();
             _address = (string)xDocument.Root.Element("original_image");
             this.Close();
         });
         w.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), values);
         buttonClose.Click -= buttonClose_Click;
         buttonClose.Click += new EventHandler(delegate(object send, EventArgs arg)
             {
                 w.CancelAsync();
                 changeValueEnabled();
                 buttonClose.Click += buttonClose_Click;
             });
     }
 }
        public NameValueListFieldWrapper(string key, ref ItemWrapper item, ISpawnProvider spawnProvider, ArrayList value = null)
            : base(key, ref item, string.Empty, spawnProvider)
        {
            if (value == null)
            {
                return;
            }

            _value = new NameValueCollection();
            foreach (object val in value)
            {
                if (val is ArrayList)
                {
                    var tmp = val as ArrayList;
                    _value.Add(tmp[0].ToString(), tmp[1].ToString());
                }
            }

            this._rawValue = _value.ToString();
        }
		public void Login(string loginPageAddress, NameValueCollection loginData)
		{
			CookieContainer container;

			var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);

			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";
			var buffer = Encoding.ASCII.GetBytes(loginData.ToString());
			request.ContentLength = buffer.Length;
			var requestStream = request.GetRequestStream();
			requestStream.Write(buffer, 0, buffer.Length);
			requestStream.Close();

			container = request.CookieContainer = new CookieContainer();

			var response = request.GetResponse();
			response.Close();
			CookieContainer = container;
		}
        public void DoLogin(string loginUrl, NameValueCollection loginData)
        {
            CookieContainer container;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            byte[] buffer = Encoding.UTF8.GetBytes(loginData.ToString());
            request.ContentLength = buffer.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            container = request.CookieContainer = new CookieContainer();

            WebResponse response = request.GetResponse();
            response.Close();

            CookieContainer = container;
        }
        public async Task<Uri> Put(Stream stream, TimeSpan? timeToLive = null, CancellationToken cancellationToken = new CancellationToken())
        {
            string keyId = null;
            using (Stream cryptoStream = _streamProvider.GetEncryptStream(stream, keyId, CryptoStreamMode.Read))
            {
                var address = await _repository.Put(cryptoStream, timeToLive, cancellationToken).ConfigureAwait(false);

                var addressBuilder = new UriBuilder(address);

                NameValueCollection parameters = new NameValueCollection();
                if (!string.IsNullOrWhiteSpace(addressBuilder.Query))
                {
                    var query = addressBuilder.Query;

                    if (query.Contains("?"))
                    {
                        query = query.Substring(query.IndexOf('?') + 1);
                    }

                    foreach (string parameter in query.Split('&'))
                    {
                        if (string.IsNullOrWhiteSpace(parameter))
                            continue;

                        string[] pair = parameter.Split('=');

                        parameters.Add(pair[0], pair.Length == 2 ? pair[1] : "");
                    }
                }

                parameters["keyId"] = "";
                addressBuilder.Query = parameters.ToString();

                return addressBuilder.Uri;
            }
        }
        /// <summary>
        /// Add visitor data to a shortened url.
        /// </summary>
        /// <param name="id">Short Url Id</param>
        /// <param name="headers">request headers</param>
        /// <param name="userAgent">request user agent</param>
        /// <returns></returns>
        public async Task AddVisitorAsync(int id, NameValueCollection headers, string userAgent)
        {
            var visitor = Visitors.Create();
            visitor.ShortUrlId = id;
            visitor.Agent = userAgent;
            visitor.Created = DateTime.UtcNow;
            visitor.Headers = headers.ToString();

            Visitors.Add(visitor);
            await SaveChangesAsync();
        }
Beispiel #15
0
        /**
         * This method builds an HTTP request and executes it.
         * @param parameters this is a collection holding the key value pair of the data to be sent as part of the request
         * @param action this is the resource (or the endpoint) we are looking for. It could be customer, shipping or order
         */
        private void buildRequestAndExecute(NameValueCollection parameters, string action)
        {
            string toencode = "";

            foreach(String entry in parameters.AllKeys)
            {
                toencode += parameters[entry] + ".";
            }

            toencode = toencode.Substring(0, toencode.Length - 1);
            var messageBytes = encoding.GetBytes(toencode);

            this._hmacmd5.ComputeHash(messageBytes);

            parameters.Add("hash",ByteToString(this._hmacmd5.Hash));

            HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://api.nitrosell.com/" + this._webstoreUrl + "/v1/"+action+".json");
            request.Method = "POST";

            string postData = parameters.ToString();
            byte[] byteArray = encoding.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            request.UserAgent = "Mozilla/5.0";

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);

            dataStream.Close();

            try
            {
                WebResponse response = request.GetResponse();
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                Console.WriteLine(responseFromServer);
                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();
            } catch(WebException e)
            {
                Console.WriteLine("Error in the request Code : {0}", e.Message);
            }
        }
        /// <summary>
        /// Builds a url from a base url (which can contains protocol and uri or be a relative url and optionaly query string) and additional query string
        /// </summary>
        /// <param name="baseUrl">The base url</param>
        /// <param name="queryStringParams">The additional query string values</param>
        /// <returns>The URL</returns>
        protected virtual string BuildUrl(string baseUrl, NameValueCollection queryStringParams)
        {
            if (queryStringParams.Count < 1)
            {
                return baseUrl;
            }

            if (baseUrl.IndexOf("?") > -1)
            {
                queryStringParams.Add(HttpUtility.ParseQueryString(baseUrl.Substring(baseUrl.IndexOf("?"))));
                baseUrl = baseUrl.Substring(0, baseUrl.IndexOf("?"));
            }

            return baseUrl + "?" + queryStringParams.ToString();
        }
        internal static string GetTabFromDictionary(string url, NameValueCollection querystringCol, FriendlyUrlSettings settings, UrlAction result, Guid parentTraceId)
        {
            //retrive the tab dictionary from the cache and get the path depth values 
            int maxAliasPathDepth;
            int maxTabPathDepth;
            int minAliasPathDepth;
            int minTabPathDepth;
            bool triedFixingSubdomain = false;
            int curAliasPathDepth = 0;

            var tabDict = TabIndexController.FetchTabDictionary(result.PortalId,
                                                                        out minTabPathDepth,
                                                                        out maxTabPathDepth,
                                                                        out minAliasPathDepth,
                                                                        out maxAliasPathDepth,
                                                                        settings,
                                                                        false,
                                                                        result.BypassCachedDictionary,
                                                                        parentTraceId);

            //clean up and prepare the url for scanning
            if (url.EndsWith("/"))
            {
                url = url.TrimEnd('/');
            }

            //ok now scan for the language modifier 
            string langParms = CheckLanguageMatch(ref url, result);

            //clean off the extension before checking the url matches, but 
            //remember if an extension existed
            bool hadExtension;
            string cleanUrl = CleanExtension(url, settings, langParms, out hadExtension);
            string[] splitUrl = cleanUrl.Split('/');

            //initialise logic switches 
            bool reWritten = false;
            bool finished = false;

            string newUrl = CheckIfPortalAlias(url, querystringCol, result, settings, tabDict);
            if (newUrl != url)
            {
                finished = true;
                reWritten = true;
            }

            //start looping through the url segments looking for a match in the tab dictionary 
            while (finished == false)
            {
                //first, try forming up a key based on alias/tabpath 
                int lastIndex = splitUrl.GetUpperBound(0);
                int arraySize = lastIndex + 1;
                int totalDepth = maxAliasPathDepth + 1 + maxTabPathDepth + 1;

                //the maximum depth of segments of a valid url 
                for (int i = lastIndex; i >= 0; i += -1)
                {
                    //only start checking the url when it is in the range of the min->max number of segments 
                    if ((i > minAliasPathDepth & i <= totalDepth))
                    {
                        //join all the tab path sections together 
                        //flag to remember if the incoming path had a .aspx or other pageAndExtension on it 
                        int tabPathStart = curAliasPathDepth + 1;
                        int tabPathLength = i - curAliasPathDepth;
                        if ((tabPathStart + tabPathLength) <= arraySize)
                        {
                            string tabPath = "";
                            if ((tabPathLength > -1))
                            {
                                tabPath = string.Join("/", splitUrl, tabPathStart, tabPathLength);
                            }
                            string aliasPath;
                            if ((curAliasPathDepth <= lastIndex))
                            {
                                aliasPath = string.Join("/", splitUrl, 0, curAliasPathDepth + 1);
                            }
                            else
                            {
                                finished = true;
                                break;
                            }
                            int parmsSize = lastIndex - i;
                            int parmStart = i + 1; //determine if any parameters on this value

                            //make up the index that is looked for in the Tab Dictionary
                            string urlPart = aliasPath + "::" + tabPath;
                            //the :: allows separation of pagename and portal alias

                            string tabKeyVal = urlPart.ToLower(); //force lower case lookup, all keys are lower case

                            //Try with querystring first If last Index
                            bool found = false;
                            if (querystringCol.Count > 0)
                            {
                                found = CheckTabPath(tabKeyVal + "?" + querystringCol.ToString().Split('&')[0].ToLowerInvariant(), result, settings, tabDict, ref newUrl);
                            }
                            if (!found)
                            {
                                found = CheckTabPath(tabKeyVal, result, settings, tabDict, ref newUrl);
                            }

                            bool isSiteRootMatch = false;
                            if (!found && tabPathLength == 1)
                            {
                                //look for special case where the site root has a * value
                                string siteRootLookup = aliasPath + "::" + "*";
                                using (tabDict.GetReadLock())
                                {
                                    found = tabDict.ContainsKey(siteRootLookup);
                                    if (found)
                                    {
                                        isSiteRootMatch = true;
                                        newUrl = tabDict[siteRootLookup];
                                        parmsSize++; //re-increase the parameter size
                                        parmStart--; //shift the point of the parms starting back one
                                    }
                                }
                            }

                            if (found)
                            {
                                if (settings.ProcessRequestList != null)
                                {
                                    newUrl = ReplaceDefaultPage(newUrl, url, settings.ProcessRequestList);
                                }

                                //look for a plain match on the default.aspx page which indicates no more rewriting needs to be done
                                if (!isSiteRootMatch && (newUrl == Globals.glbDefaultPage || newUrl == Globals.glbDefaultPage + "[UseBase]"))
                                {
                                    //the [UseBase] moniker is a shortcut hack.  It's used to recognise pages which have been excluded 
                                    //from using Friendly Urls.  The request will go on to be processed by the dnn siteurls.config processing.
                                    //this stops the loop and exits the function
                                    newUrl = newUrl.Replace("[UseBase]", ""); //get rid of usebase hack pattern
                                    SetRewriteParameters(ref result, newUrl); //set result 
                                    finished = true;
                                }
                                else
                                {
                                    //708 : move result rewrite set so that downstream functions know the tabid
                                    SetRewriteParameters(ref result, newUrl);
                                    //found the correct rewrite page, now investigate whether there 
                                    //is part of the url path that needs to be converted to tab id's 
                                    //  Multi Language Urls not being rewritten 
                                    if (parmsSize > 0)
                                    {
                                        bool rewriteParms = false;

                                        //determine the url action and reason from embedded rewriting tokens
                                        ActionType action;
                                        RedirectReason reason;
                                        string resultingUrl;
                                        RedirectTokens.DetermineRedirectReasonAndAction(newUrl,
                                                                                        result,
                                                                                        true,
                                                                                        settings,
                                                                                        out resultingUrl,
                                                                                        out reason,
                                                                                        out action);
                                        newUrl = resultingUrl;
                                        result.Action = action;
                                        result.Reason = reason;

                                        //copy the parms into a separate array 
                                        var urlParms = new string[parmsSize];
                                        Array.ConstrainedCopy(splitUrl, parmStart, urlParms, 0, parmsSize);

                                        if (!isSiteRootMatch && result.Reason == RedirectReason.User_Profile_Url)
                                        {
                                            result.Reason = RedirectReason.Not_Redirected;
                                            newUrl = RedirectTokens.RemoveAnyRedirectTokensAndReasons(newUrl);
                                        }

                                        //738 : check for custom module providers
                                        //894 : allow disable of custom url providers functionality
                                        if (!rewriteParms && settings.EnableCustomProviders)
                                        {
                                            bool newAction;
                                            //newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested.
                                            //call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite.
                                            List<string> messages = result.DebugMessages;
                                            newUrl = RewriteParametersFromModuleProvider(newUrl,
                                                                                        tabKeyVal,
                                                                                        urlParms,
                                                                                        isSiteRootMatch,
                                                                                        result,
                                                                                        settings,
                                                                                        out rewriteParms,
                                                                                        out newAction,
                                                                                        ref messages,
                                                                                        parentTraceId);
                                            result.DebugMessages = messages;
                                            if (newAction)
                                            {
                                                finished = true;
                                            }
                                        }
                                        //do a rewrite on the parameters from the stored parameter regex rewrites 
                                        if (!rewriteParms)
                                        {
                                            newUrl = RewriteParameters(newUrl,
                                                                        tabKeyVal,
                                                                        urlParms,
                                                                        isSiteRootMatch,
                                                                        result,
                                                                        out rewriteParms,
                                                                        parentTraceId);
                                        }
                                        if (rewriteParms && isSiteRootMatch)
                                        {
                                            //set rewrite parameters to take tabid for site root matches
                                            SetRewriteParameters(ref result, newUrl);
                                        }

                                        //if the parms weren't rewritten by means of a regex, then process them normally
                                        if (!rewriteParms && !isSiteRootMatch)
                                        //can only try other matches if it wasn't a site root match
                                        {
                                            //put those parms on the back of the url as a query string 
                                            string cultureCode;
                                            newUrl = RewriteParameters(newUrl,
                                                                        tabKeyVal,
                                                                        urlParms,
                                                                        result,
                                                                        langParms,
                                                                        settings,
                                                                        out cultureCode);
                                            if (cultureCode != null) //set culture code if not already set
                                            {
                                                result.CultureCode = cultureCode;
                                            }
                                        }
                                        //now check if the request involved a page pageAndExtension, (.aspx) and shouldn't have 
                                        if (!finished)
                                        {
                                            //944 : don't switch to 301 redirect if action already set to 404
                                            if ((settings.PageExtensionUsageType == PageExtensionUsageType.Never
                                                 || settings.PageExtensionUsageType == PageExtensionUsageType.PageOnly) &
                                                hadExtension)
                                            {
                                                //948 : use new 'no downgrade' method
                                                result.SetActionWithNoDowngrade(ActionType.CheckFor301);
                                            }
                                            else
                                                //866 : redirect back from no extension to extension if it didn't have one
                                                if (settings.PageExtensionUsageType != PageExtensionUsageType.Never &&
                                                    hadExtension == false)
                                                {
                                                    //948 : use new 'no downgrade' method
                                                    result.SetActionWithNoDowngrade(ActionType.CheckFor301);
                                                }
                                        }

                                        if (isSiteRootMatch && !finished)
                                        //when it was a site root match, this must be matched with a custom parameter regex
                                        {
                                            //only finished if the parms were rewritten by means of a regex rewrite
                                            reWritten = rewriteParms;
                                            finished = rewriteParms;
                                        }
                                        else
                                        {
                                            //rewriting done
                                            reWritten = true;
                                            finished = true;
                                        }
                                    }
                                    else
                                    {
                                        //determine the url action and redirect reason from embedded tokens in the url rewrite path
                                        string resultUrl;
                                        RedirectReason reason;
                                        ActionType action;
                                        //add back language parameters if they were there
                                        if (string.IsNullOrEmpty(langParms) == false)
                                        {
                                            string[] parms = langParms.Split('/');
                                            if (parms.GetUpperBound(0) >= 1)
                                            {
                                                if (parms[0] == "" && parms.GetUpperBound(0) > 1)
                                                {
                                                    newUrl += "&" + parms[1] + "=" + parms[2];
                                                }
                                                else
                                                {
                                                    newUrl += "&" + parms[0] + "=" + parms[1];
                                                }
                                            }
                                        }
                                        RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, false, settings,
                                                                                        out resultUrl, out reason,
                                                                                        out action);
                                        newUrl = resultUrl;
                                        result.Reason = reason;
                                        result.Action = action;

                                        if (settings.EnableCustomProviders && ExtensionUrlProviderController.CheckForAlwaysCallProviders(result.PortalId,
                                                                                                       result.TabId,
                                                                                                       settings,
                                                                                                       parentTraceId))
                                        {
                                            bool newAction;
                                            //newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested.
                                            //call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite.
                                            string[] urlParms = (new List<string>()).ToArray(); //empty parm array
                                            if (string.IsNullOrEmpty(langParms) == false)
                                            {
                                                urlParms = langParms.Split('/');
                                                //split the lang parms into the url Parms
                                            }
                                            bool rewriteParms;
                                            List<string> messages = result.DebugMessages;
                                            newUrl = RewriteParametersFromModuleProvider(newUrl,
                                                                                        tabKeyVal,
                                                                                        urlParms,
                                                                                        isSiteRootMatch,
                                                                                        result,
                                                                                        settings,
                                                                                        out rewriteParms,
                                                                                        out newAction,
                                                                                        ref messages,
                                                                                        parentTraceId);
                                            result.DebugMessages = messages;
                                        }

                                        //this is a page only, no parameters to deal with 
                                        //944 : don't downgrade to redirect if the current action is a 404 (see 948 for new solution to 944)
                                        if (settings.PageExtensionUsageType == PageExtensionUsageType.Never & hadExtension)
                                        {
                                            //potentially a 301 replaced because shouldn't be using page extensions 
                                            //948 : check to prevent action downgrade, in case already set to redirect
                                            result.SetActionWithNoDowngrade(ActionType.CheckFor301);
                                        }
                                        else
                                        {
                                            //866 : redirect back from no extension to extension if it didn't have one
                                            if (settings.PageExtensionUsageType != PageExtensionUsageType.Never &&
                                                hadExtension == false)
                                            {
                                                result.SetActionWithNoDowngrade(ActionType.CheckFor301);
                                            }
                                        }
                                        //rewriting done
                                        reWritten = true;
                                        finished = true;
                                    }
                                }
                                if (finished)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }

                //next, try forming up a key based on alias1/alias2/tabpath 
                if (!finished)
                {
                    curAliasPathDepth += 1;
                    //gone too deep 
                    if ((curAliasPathDepth > maxAliasPathDepth) & (reWritten == false))
                    {
                        // no hope of finding it then 
                        if (triedFixingSubdomain == false && false)
                        {
                            //resplit the new url 
                            splitUrl = newUrl.Split(Convert.ToChar("/"));
                            curAliasPathDepth = minAliasPathDepth;
                            if (result.RedirectAllowed)
                            {
                                result.Action = ActionType.Redirect301;
                            }
                            //this should be redirected 
                            triedFixingSubdomain = true;
                        }
                        else
                        {
                            if (!AdvancedUrlRewriter.ServiceApi.IsMatch(url) && result.RedirectAllowed)
                            {
                                //nothing left to try 
                                result.Action = (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error)
                                        ? ActionType.Output404
                                        : ActionType.Redirect301;
                                if (result.Action == ActionType.Redirect301)
                                {
                                    result.Reason = RedirectReason.Deleted_Page;
                                    result.DoRewrite = true;
                                    result.FinalUrl = Globals.AddHTTP(result.PortalAlias.HTTPAlias + "/");
                                    reWritten = true;
                                }
                                break;
                            }
                        }
                    }
                }
            }

            result.FriendlyRewrite = reWritten;
            result.DoRewrite = reWritten;
            return newUrl;
        }
Beispiel #18
0
        /// <summary>
        /// Processes client request and performs operations requested by client components
        /// </summary>
        /// <param name="QueryString">QueryString collection of current request</param>
        /// <param name="Form">Form collection fof current request</param>
        public void ProcessRequest(NameValueCollection QueryString, NameValueCollection Form)
        {
            #region LOG ENTRY
#if !NO_LOG
            Log.WriteLine(this, "Processing client request. QueryString: " + QueryString.ToString() + ", Form: " + Form);
#endif
            #endregion
            this._RequestType = this.GetCurrentMode(QueryString);
            switch(this.RequestType)
            {
                //SELECTS
                case DataRequestType.Select:
                    UpdateSelectParams(QueryString);
                    break;
                //UPDATES, INSERTS, DELETES
                case DataRequestType.Edit:
                    this._DataActions.AddRange(ParseDataActions((QueryString["ids"] != null || QueryString["tr_id"] != null || QueryString["gr_id"] != null) ? QueryString : Form));
                    try
                    {
                        //start per-request transaction if necessary
                        if (this.TransactionMode == TransactionMode.PerRequest)
                        {
                            #region LOG ENTRY
#if !NO_LOG
                            Log.WriteLine(this, "Entering " + this.TransactionMode.ToString() + " transaction mode. ");
#endif
                            #endregion
                            this.Adapter.BeginTransaction();
                        }
                        //PROCESS DATA ACTIONS
                        foreach (DataAction action in this.DataActions)
                            for (int i = 0; i < this.DataActions.Count; i++)
                                this.ProcessDataAction(this.DataActions[i]);
                        //close pre-request transaction if necessary
                        if (this.TransactionMode == TransactionMode.PerRequest)
                        {
                            #region LOG ENTRY
#if !NO_LOG
			                Log.WriteLine(this, "Commiting " + this.TransactionMode.ToString() + " transaction.");
#endif
#endregion
                            this.Adapter.CommitTransaction();
                        }
                    }
                    catch (Exception ex1)
                    {
                        #region LOG ENTRY
#if !NO_LOG
                        Log.WriteLine(this, "Exception cought: " + ex1.Message);
#endif
                        #endregion
                        try
                        {
                            //if there was transaction - rollback it
                            if (this.TransactionMode == TransactionMode.PerRequest)
                            {
                                #region LOG ENTRY
#if !NO_LOG
                                Log.WriteLine(this, "Rolling back " + this.TransactionMode.ToString() + " transaction because of the following exception: " + ex1.Message);
#endif
                                #endregion
                                this.Adapter.RollbackTransaction();
                            }
                            //mark all data actions with failed and Completed state, so now their faith is user's concern
                            foreach (DataAction action in this.DataActions)
                                action.SetFailed(ex1.Message);
                        }
                            //Exception that probably occured while trying to rollback transaction
                        catch (Exception ex2)
                        {
                            #region LOG ENTRY
#if !NO_LOG
                            Log.WriteLine(this, "Exception cought: " + ex2.Message);
#endif
                            #endregion
                            foreach (DataAction action in this.DataActions)
                                action.SetFailed(ex1.Message + Environment.NewLine + "Transaction rollback failed with the following error: " + ex2.Message);
                        }
                    }
                    break;
                //SOMETHING UNEXPECTED
                default:
                    throw new NotImplementedException(this.RequestType.ToString() + " mode behavior has not been implemented yet!");
            }
        }
Beispiel #19
0
        public static IHtmlString CreateNavigationGrid(this System.Web.Mvc.HtmlHelper html, ModelGrillaBase model)
        {
            NameValueCollection querystr = new NameValueCollection();
            querystr = html.ViewContext.RequestContext.HttpContext.Request.QueryString;
            string querystring =  querystr.ToString();

            if (querystring.IndexOf("page") > -1)
            {
                querystring = querystring.Remove(0, querystring.IndexOf('&') + 1);
            }

            var controller = html.ViewContext.RouteData.Values["controller"].ToString();
            var action = html.ViewContext.RouteData.Values["action"].ToString();

            int cantPages = (int)Math.Ceiling(Convert.ToDouble(model.Cantidad) / Convert.ToDouble(model.CantidadPorPagina));

            StringBuilder sb = new StringBuilder();
            TagBuilder tbTable = new TagBuilder("table");
            tbTable.AddCssClass("controles-paginacion-grid");
            tbTable.MergeAttribute("align", "right");
            TagBuilder tbTr = new TagBuilder("tr");

            string imgprevsrc = new UrlHelper(html.ViewContext.RequestContext).Content("~/Content/images/btn_prev.png");
            string imgPrev = TagImage(imgprevsrc,  LenceriaKissy.Recursos.AppResources.Vistas.Anterior);

            string imgnextsrc = new UrlHelper(html.ViewContext.RequestContext).Content("~/Content/images/btn_next.png");
            string imgNext = TagImage(imgnextsrc, LenceriaKissy.Recursos.AppResources.Vistas.Siguiente);

            if (model.PaginaActual > 1)
            {
                TagBuilder tbTd = new TagBuilder("td");

                string link = (new UrlHelper(html.ViewContext.RequestContext)).Action(action, new { page = model.PaginaActual - 1 });
                link += "&" + querystring.ToString();

                TagBuilder tbAnchor = new TagBuilder("a");
                tbAnchor.MergeAttribute("href", link);
                tbAnchor.InnerHtml = imgPrev;
                tbTd.InnerHtml = LenceriaKissy.Recursos.AppResources.Vistas.Anterior +  tbAnchor.ToString();
                tbTr.InnerHtml += tbTd.ToString();
            }
            else {
                TagBuilder tbTd = new TagBuilder("td");
                tbTd.InnerHtml = LenceriaKissy.Recursos.AppResources.Vistas.Anterior + imgPrev;
                tbTr.InnerHtml += tbTd.ToString();
            }
            for (int i = 1; i <= cantPages; i++)
            {
                if ((i > (model.PaginaActual - 4)) && (i <= (model.PaginaActual + 3)) || (i == 1) || (i == cantPages))
                {
                    if (i == model.PaginaActual)
                    {
                        TagBuilder tbTd = new TagBuilder("td");
                        tbTd.InnerHtml += model.PaginaActual.ToString();
                        tbTr.InnerHtml += tbTd.ToString();
                    }
                    if (i > model.PaginaActual)
                    {
                        if ((i == cantPages) && !(i <= (model.PaginaActual + 4)))
                        {
                            TagBuilder tagpunt = new TagBuilder("td");
                            tagpunt.InnerHtml += "..";
                            tbTr.InnerHtml += tagpunt.ToString();
                        }

                        TagBuilder tbTd = new TagBuilder("td");
                        string link = new UrlHelper(html.ViewContext.RequestContext).Action(action, new { page = i });
                        link += "&" + querystring;
                        TagBuilder tbAnchor = new TagBuilder("a");
                        tbAnchor.MergeAttribute("href", link);
                        tbAnchor.InnerHtml = i.ToString();
                        tbTd.InnerHtml += tbAnchor.ToString();
                        tbTr.InnerHtml += tbTd.ToString();
                    }
                    if (i < model.PaginaActual)
                    {

                        TagBuilder tbTd = new TagBuilder("td");
                        string link = new UrlHelper(html.ViewContext.RequestContext).Action(action, new { page = i });
                        link += "&" + querystring;
                        TagBuilder tbAnchor = new TagBuilder("a");
                        tbAnchor.MergeAttribute("href", link);
                        tbAnchor.InnerHtml = i.ToString();
                        tbTd.InnerHtml += tbAnchor.ToString();
                        tbTr.InnerHtml += tbTd.ToString();

                        if ((i == 1) && !(i > (model.PaginaActual - 5)))
                        {
                            TagBuilder tagpunt = new TagBuilder("td");
                            tagpunt.InnerHtml += "..";
                            tbTr.InnerHtml += tagpunt.ToString();
                        }
                    }
                }
            }

            if (cantPages > model.PaginaActual)
            {
                TagBuilder tbTd = new TagBuilder("td");
                string link = (new UrlHelper(html.ViewContext.RequestContext)).Action(action, new { page = model.PaginaActual + 1 });
                link += "&" + querystring;
                TagBuilder tbAnchor = new TagBuilder("a");
                tbAnchor.MergeAttribute("href", link);
                tbAnchor.InnerHtml = imgNext;
                tbTd.InnerHtml += tbAnchor.ToString() + LenceriaKissy.Recursos.AppResources.Vistas.Siguiente;
                tbTr.InnerHtml += tbTd.ToString();
            }
            else
            {
                TagBuilder tbTd = new TagBuilder("td");
                tbTd.InnerHtml += imgNext + LenceriaKissy.Recursos.AppResources.Vistas.Siguiente;
                tbTr.InnerHtml += tbTd.ToString();
            }

            TagBuilder tbTdFinal = new TagBuilder("td");
            tbTr.InnerHtml += tbTdFinal.ToString();

            tbTable.InnerHtml = tbTr.ToString();
            return html.Raw(tbTable.ToString());
        }
Beispiel #20
0
        private JObject executeHttpRequest(string path, NameValueCollection parameters, string method)
        {
            if (method == "GET" && parameters != null)
            {
                path = path + "?" + ToQueryString(parameters);
            }

            WebRequest req = WebRequest.Create(this.baseURL + this.apiVersion + path);
            req.Method = method;

            this.debug(this.baseURL + this.apiVersion + path);

            WebHeaderCollection headers = new WebHeaderCollection();
            headers.Add("apiKey:" + apiKey );
            req.Headers = headers;

            if (method == "POST" && parameters != null)
            {
                this.debug(parameters.ToString());

                var data = Encoding.UTF8.GetBytes(ToQueryString(parameters));

                req.ContentLength = data.Length;
                req.ContentType = "application/x-www-form-urlencoded";

                Stream dataStream = req.GetRequestStream();

                dataStream.Write(data, 0, data.Length);
                dataStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream answerStream = resp.GetResponseStream();
            String answerString = new StreamReader(answerStream).ReadToEnd();

            var responseCode = JObject.Parse(answerString)["responseCode"];

            if (responseCode.ToString() != "200")
            {
                if (responseCode.ToString() == "401")
                {
                    throw new JotformException("Unauthozired API call");
                }
                else if (responseCode.ToString() == "404")
                {
                    throw new JotformException(JObject.Parse(answerString)["message"].ToString());
                }
                else if (responseCode.ToString() == "503")
                {
                    throw new JotformException("Service is unavaible, rate limits etc exceeded!");
                }
            }

            return JObject.Parse(answerString);
        }
        private string GetRedirectUrl(HttpRequestBase request, NameValueCollection queryNameValuePair)
        {
            // Don't propagate query strings added by Facebook OAuth Dialog
            queryNameValuePair.Remove("code");
            queryNameValuePair.Remove("error");
            queryNameValuePair.Remove("error_reason");
            queryNameValuePair.Remove("error_description");

            string redirectUrl = String.Format(
                CultureInfo.InvariantCulture,
                "{0}/{1}",
                _config.AppUrl.TrimEnd('/'),
                request.AppRelativeCurrentExecutionFilePath.TrimStart('~', '/'));

            string query = queryNameValuePair.ToString();
            if (!String.IsNullOrEmpty(query))
            {
                redirectUrl += "?" + query;
            }

            return redirectUrl;
        }
 public void ToString_GeneratesCorrectOutput(NameValueCollection input, string expectedOutput)
 {
     string actualOutput = input.ToString();
     Assert.Equal(expectedOutput, actualOutput);
 }
        /// <summary>
        /// return true if the transaction was processed with no problems
        /// </summary>
        /// <param name="context"></param>
        /// <param name="transactionId"></param>
        /// <param name="orderId"></param>
        /// <param name="grossAmount"></param>
        /// <param name="standardCheckoutLog"></param>
        /// <returns></returns>
        public override bool HandleRequest(
            string transactionId,
            NameValueCollection form,
            PayPalLog standardCheckoutLog)
        {
            bool result = false;

            if (standardCheckoutLog.SerializedObject.Length == 0) { return result; }

            Cart cart = (Cart)SerializationHelper.DeserializeFromString(typeof(Cart), standardCheckoutLog.SerializedObject);

            Store store = new Store(cart.StoreGuid);
            SiteSettings siteSettings = new SiteSettings(store.SiteGuid);

            bool debugPayPal = WebConfigSettings.DebugPayPal;

            //mc_gross=5.00
            //&address_status=confirmed
            //&item_number1=d28a6bed-7e51-4f18-a893-77b4d5665a64
            //&payer_id=zzzzzz
            //&tax=0.00
            //&address_street=nnnn
            //&payment_date=10%3A08%3A08+Jul+29%2C+2008+PDT
            //&payment_status=Completed
            //&charset=windows-1252
            //&address_zip=92843
            //&mc_shipping=0.00
            //&mc_handling=0.00
            //&first_name=zz
            //&mc_fee=0.45
            //&address_country_code=US
            //&address_name=zzzz
            //&notify_version=2.4
            //&custom=d9ef5324-2201-4749-b06a-9bba7a9dce61
            //&payer_status=verified
            //&business=sales%40mojoportal.com
            //&address_country=United+States
            //&num_cart_items=1
            //&mc_handling1=0.00
            //&address_city=nnnn
            //&verify_sign=
            //&payer_email=zzzzzz
            //&mc_shipping1=0.00
            //&tax1=0.00
            //&txn_id=81Y88484JA1416221
            //&payment_type=instant
            //&payer_business_name=EBShoes
            //&last_name=Ngo
            //&address_state=CA
            //&item_name1=Buy+Joe+a+Beer
            //&receiver_email=sales%40mojoportal.com
            //&payment_fee=0.45
            //&quantity1=1
            //&receiver_id=nnnn
            //&txn_type=cart
            //&mc_gross_1=5.00
            //&mc_currency=USD
            //&residence_country=US
            //&payment_gross=5.00

            string firstName = string.Empty;
            if (form["first_name"] != null)
            {
                firstName = form["first_name"].ToString();
            }

            string lastName = string.Empty;
            if (form["last_name"] != null)
            {
                lastName = form["last_name"].ToString();
            }

            string paymentStatus = string.Empty;
            if (form["payment_status"] != null)
            {
                paymentStatus = form["payment_status"].ToString();
            }

            string payerEmail = string.Empty;
            if (form["payer_email"] != null)
            {
                payerEmail = form["payer_email"].ToString();
            }

            string paymentGross = string.Empty;
            if (form["mc_gross"] != null)
            {
                paymentGross = form["mc_gross"].ToString();
            }

            string payPalFee = string.Empty;
            if (form["mc_fee"] != null)
            {
                payPalFee = form["mc_fee"].ToString();
            }

            string payPalTax = string.Empty;
            if (form["tax"] != null)
            {
                payPalTax = form["tax"].ToString();
            }

            string payPalShipping = string.Empty;
            if (form["mc_shipping"] != null)
            {
                payPalShipping = form["mc_shipping"].ToString();
            }

            string currencyUsed = string.Empty;
            if (form["mc_currency"] != null)
            {
                currencyUsed = form["mc_currency"].ToString();
            }

            string pendingReason = string.Empty;
            if (form["pending_reason"] != null)
            {
                pendingReason = form["pending_reason"].ToString();
            }

            string reasonCode = string.Empty;
            if (form["reason_code"] != null)
            {
                reasonCode = form["reason_code"].ToString();
            }

            string paymentType = string.Empty;
            if (form["txn_type"] != null)
            {
                paymentType = form["txn_type"].ToString();
            }

            string payPalSettlement = "0";
            if (form["settle_amount"] != null)
            {
                payPalSettlement = form["settle_amount"].ToString();
            }

            string customerAddress = string.Empty;
            if (form["address_street"] != null)
            {
                customerAddress = form["address_street"].ToString();
            }

            string customerCity = string.Empty;
            if (form["address_city"] != null)
            {
                customerCity = form["address_city"].ToString();
            }

            string customerState = string.Empty;
            if (form["address_state"] != null)
            {
                customerState = form["address_state"].ToString();
            }

            string customerPostalCode = string.Empty;
            if (form["address_zip"] != null)
            {
                customerPostalCode = form["address_zip"].ToString();
            }

            string customerCountry = string.Empty;
            if (form["address_country"] != null)
            {
                customerCountry = form["address_country"].ToString();
            }

            string customerPhone = string.Empty;
            if (form["contact_phone"] != null)
            {
                customerPhone = form["contact_phone"].ToString();
            }

            string customerBusinessName = string.Empty;
            if (form["payer_business_name"] != null)
            {
                customerBusinessName = form["payer_business_name"].ToString();
            }

            // TODO: we need to store this somewhere on the cart/order
            // its the message the user enters in special instructions on paypal checkout
            string customerMemo = string.Empty;
            if (form["memo"] != null)
            {
                customerMemo = form["memo"].ToString();
            }

            if (debugPayPal) { log.Info("PayPal currencyUsed was " + currencyUsed); }

            //Regardless of the specified currency, the format will have decimal point
            //with exactly two digits to the right and an optional thousands separator to the left,
            //which must be a comma; for example, EUR 2.000,00 must be specified as 2000.00 or 2,000.00
            // So we want to parse it with US Culture

            CultureInfo currencyCulture = new CultureInfo("en-US");
            //if (currencyUsed.Length > 0)
            //{
            //    currencyCulture = ResourceHelper.GetCurrencyCulture(currencyUsed);
            //}
            //else
            //{
            //    //Currency currency = new Currency(store.DefaultCurrencyId);
            //    //currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code);
            //    Currency currency = siteSettings.GetCurrency();
            //    currencyCulture = ResourceHelper.GetCurrencyCulture(currency.Code);
            //    currencyUsed = currency.Code;
            //}

            //if (debugPayPal) { log.Info("PayPal final currency culture was " + currencyUsed); }

            decimal grossAmount = 0;
            decimal.TryParse(paymentGross, NumberStyles.Currency, currencyCulture, out grossAmount);
            decimal feeAmount = 0;
            decimal.TryParse(payPalFee, NumberStyles.Currency, currencyCulture, out feeAmount);
            decimal taxAmount = 0;
            decimal.TryParse(payPalTax, NumberStyles.Currency, currencyCulture, out taxAmount);
            decimal shippingAmount = 0;
            decimal.TryParse(payPalShipping, NumberStyles.Currency, currencyCulture, out shippingAmount);
            decimal settleAmount = 0;
            decimal.TryParse(payPalSettlement, NumberStyles.Currency, currencyCulture, out settleAmount);

            if (debugPayPal)
            {
                log.Info("PayPal paymentGross was " + paymentGross + " which was parsed as " + grossAmount.ToString());
                log.Info("PayPal payPalFee was " + payPalFee + " which was parsed as " + feeAmount.ToString());
                log.Info("PayPal payPalTax was " + payPalTax + " which was parsed as " + taxAmount.ToString());
                log.Info("PayPal payPalShipping was " + payPalShipping + " which was parsed as " + shippingAmount.ToString());
                log.Info("PayPal payPalSettlement was " + payPalSettlement + " which was parsed as " + settleAmount.ToString());

            }

            PayPalLog payPalLog = new PayPalLog();
            payPalLog.PDTProviderName = standardCheckoutLog.PDTProviderName;
            payPalLog.IPNProviderName = standardCheckoutLog.IPNProviderName;
            payPalLog.ReturnUrl = standardCheckoutLog.ReturnUrl;
            payPalLog.ProviderName = standardCheckoutLog.ProviderName;
            payPalLog.SiteGuid = standardCheckoutLog.SiteGuid;
            payPalLog.StoreGuid = standardCheckoutLog.StoreGuid;
            payPalLog.UserGuid = standardCheckoutLog.UserGuid;
            payPalLog.ApiVersion = standardCheckoutLog.ApiVersion;
            payPalLog.CartGuid = standardCheckoutLog.CartGuid;
            payPalLog.SerializedObject = standardCheckoutLog.SerializedObject;
            payPalLog.CartTotal = grossAmount;
            payPalLog.PayPalAmt = feeAmount;
            if (settleAmount > 0)
            {
                payPalLog.SettleAmt = settleAmount;
            }
            else
            {
                payPalLog.SettleAmt = (grossAmount - feeAmount);
            }
            payPalLog.TaxAmt = taxAmount;
            payPalLog.CurrencyCode = currencyUsed;
            payPalLog.TransactionId = transactionId;
            payPalLog.RawResponse = form.ToString();
            payPalLog.Response = "IPNSuccess";
            payPalLog.RequestType = "IPN";
            payPalLog.PayerId = payerEmail;
            payPalLog.PaymentType = paymentType;
            payPalLog.PaymentStatus = paymentStatus;
            payPalLog.PendingReason = pendingReason;
            payPalLog.ReasonCode = reasonCode;
            payPalLog.Save();

            // see if this cart has already been proceesed
            Order existingOrder = new Order(cart.CartGuid);
            // order already exists
            if (existingOrder.OrderGuid != Guid.Empty)
            {
                // lookup order status if needed make it fullfillable
                // then redirect to order detail page
                if (existingOrder.StatusGuid == OrderStatus.OrderStatusReceivedGuid)
                {
                    if (paymentStatus == "Completed")
                    {
                        existingOrder.StatusGuid = OrderStatus.OrderStatusFulfillableGuid;

                        existingOrder.Save();

                        try
                        {
                            StoreHelper.ConfirmOrder(store, existingOrder);
                            GoogleCheckoutLog.DeleteByCart(existingOrder.OrderGuid);
                        }
                        catch (Exception ex)
                        {
                            log.Error("error sending confirmation email", ex);
                        }
                    }

                }

                result = true;

                payPalLog.ReasonCode = "existing order found";
                payPalLog.Save();

                return result;
            }

            // if we get here the cart has not yet been processed into an order
            cart.DeSerializeCartOffers();

            Guid orderStatus;
            if (paymentStatus == "Completed")
            {
                orderStatus = OrderStatus.OrderStatusFulfillableGuid;
            }
            else
            {
                orderStatus = OrderStatus.OrderStatusReceivedGuid;
            }

            // update the order with customer shipping info
            cart.OrderInfo.DeliveryCompany = customerBusinessName;
            cart.OrderInfo.DeliveryAddress1 = customerAddress;

            cart.OrderInfo.DeliveryCity = customerCity;
            cart.OrderInfo.DeliveryFirstName = firstName;
            cart.OrderInfo.DeliveryLastName = lastName;
            cart.OrderInfo.DeliveryPostalCode = customerPostalCode;
            cart.OrderInfo.DeliveryState = customerState;
            cart.OrderInfo.DeliveryCountry = customerCountry;

            if (customerPhone.Length > 0)
            {
                cart.OrderInfo.CustomerTelephoneDay = customerPhone;
            }

            if (payerEmail.Length > 0)
            {
                cart.OrderInfo.CustomerEmail = payerEmail;
            }

            cart.CopyShippingToBilling();
            cart.CopyShippingToCustomer();
            cart.TaxTotal = taxAmount;
            cart.OrderTotal = grossAmount;
            if (shippingAmount > 0)
            {
                cart.ShippingTotal = shippingAmount;
            }

            StoreHelper.EnsureUserForOrder(cart);

            cart.Save();

            cart.SerializeCartOffers();
            payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart);
            payPalLog.Save();

            Order order = Order.CreateOrder(
                store,
                cart,
                transactionId,
                transactionId,
                string.Empty,
                currencyUsed,
                "PayPal",
                orderStatus);

            if (orderStatus == OrderStatus.OrderStatusFulfillableGuid)
            {
                try
                {
                    StoreHelper.ConfirmOrder(store, order);
                    GoogleCheckoutLog.DeleteByCart(order.OrderGuid);
                }
                catch (Exception ex)
                {
                    log.Error("error sending confirmation email", ex);
                }
            }

            if (orderStatus == OrderStatus.OrderStatusReceivedGuid)
            {
                StoreHelper.ConfirmOrderReceived(store, order);
            }

            result = true;

            return result;
        }
        private IEnumerable<Func<BitmapSource, BitmapSource>> GetBitmapTransforms(NameValueCollection requestData)
        {
            var settings = GetSettings(requestData.ToString()).ToArray();

            foreach (var setting in settings)
            {
                IBitmapTransformFactory factory;
                Func<BitmapSource, BitmapSource> transformer;
                if (_bitmapTransformFactories.TryGetValue(setting.Key, out factory) &&
                    factory.TryGetBitmapTransform(setting.Value, settings, out transformer))
                {
                    yield return transformer;
                }
            }
        }
        /// <summary>
        /// Determines when to do a redirect.  This is separate to the rewriting process.  The module developer can create any type of Url redirect here, because the entire Url of the original request is passed in.
        /// </summary>
        /// <param name="tabId">Identified TabId, if known.  -1 if no valid tabid identified.</param>
        /// <param name="portalid">Identified portalId.</param>
        /// <param name="httpAlias">Identified httpAlias of the request.</param>
        /// <param name="requestUri">The original requested Url</param>
        /// <param name="queryStringCol">The querystring collection of the original request</param>
        /// <param name="options">The friendly url options that currently apply.</param>
        /// <param name="redirectLocation">Out parameter that shows where to redirect to.</param>
        /// <param name="messages">List of messages for debug purposes.  Add to this list to help debug your module.</param>
        /// <returns>true if 301 redirect is required, false if not.  If true, the redirectLocation value must be a valid fully qualified Url.</returns>
        public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, System.Collections.Specialized.NameValueCollection queryStringCol, FriendlyUrlOptions options, out string redirectLocation, ref List <string> messages)
        {
            bool doRedirect = false;

            if (messages == null)
            {
                messages = new List <string>();
            }
            redirectLocation = "";//set blank location
            //compare to known pattern of old Urls
            if (_redirectUrls)
            {
                Regex oldNewsRegex = new Regex(@"(&articleType=(?<type>[^&]+))?((&(?<idname>[a-z]*Id)=(?<id>\d+))|((&month=(?<mm>[\d]{1,2}))?&year=(?<yyyy>[\d]{4})))(&(?<pgname>PageId|CurrentPage)=(?<pg>[\d]+))?", RegexOptions.IgnoreCase);
                Match oldNewsMatch = oldNewsRegex.Match(queryStringCol.ToString());
                if (oldNewsMatch.Success)
                {
                    Group  typeGroup   = oldNewsMatch.Groups["type"];
                    Group  idNameGroup = oldNewsMatch.Groups["idname"];
                    Group  idGroup     = oldNewsMatch.Groups["id"];
                    Group  pageGroup   = oldNewsMatch.Groups["pg"];
                    Group  pgNameGrp   = oldNewsMatch.Groups["pgname"];
                    string msg         = "";
                    string id          = null;
                    string furlKey     = null;
                    string friendlyUrl = null;
                    if (idGroup != null && idGroup.Success)
                    {
                        id = idGroup.Value;
                    }
                    string idType = null;
                    if (typeGroup != null && typeGroup.Success)
                    {
                        idType = typeGroup.Value.ToLower();
                    }
                    else
                    {
                        if (idNameGroup != null && idNameGroup.Success)
                        {
                            //check if it's the 'ID' value
                            if (idNameGroup.Value.ToLower() == "id")
                            {
                                idType = "id";
                            }
                        }
                    }
                    //now look at the idType
                    string pagePath = null;
                    if (pgNameGrp != null && pgNameGrp.Success == true && pageGroup != null && pageGroup.Success)
                    {
                        pagePath = pgNameGrp.Value + "/" + pageGroup.Value;
                    }
                    switch (idType)
                    {
                    case "articleview":
                    case "id":
                        msg = "Identified as old-style news article";
                        //article
                        if (pageGroup != null && pageGroup.Success)
                        {
                            furlKey  = "p" + pageGroup.Value;
                            pagePath = null;     //taking care of page separately
                        }
                        else
                        {
                            int articleId = -1;
                            //only for items that are in the range of allowed article ids
                            if (int.TryParse(id, out articleId))
                            {
                                if (articleId >= this.StartingArticleId)
                                {
                                    furlKey = "a" + id;
                                }
                            }
                        }

                        break;

                    case "categoryview":
                        msg     = "Identified as old-style news category";
                        furlKey = "c" + id;
                        break;

                    case "archiveview":
                        //get the mm and yyyy
                        msg = "Identified as old-style news archive";
                        Group yyyyGrp = oldNewsMatch.Groups["yyyy"];
                        if (yyyyGrp != null && yyyyGrp.Success)
                        {
                            string yyyy  = yyyyGrp.Value;
                            string mm    = null;
                            Group  mmGrp = oldNewsMatch.Groups["mm"];
                            if (mmGrp != null && mmGrp.Success)
                            {
                                mm = mmGrp.Value;
                            }
                            friendlyUrl = yyyy;
                            if (mm != null)
                            {
                                friendlyUrl += "/" + mm;
                            }
                        }
                        break;

                    case "authorview":
                        msg     = "Identified as old-style news author";
                        furlKey = "u" + id;
                        break;
                    }
                    if (furlKey != null)
                    {
                        //now lookup the friendly url index
                        TabUrlOptions urlOptions       = GetTabUrlOptions(tabId);
                        Hashtable     friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options, urlOptions);
                        if (friendlyUrlIndex != null && friendlyUrlIndex.ContainsKey(furlKey))
                        {
                            //look up the index for the item if we don't already have a friendly Url
                            friendlyUrl = (string)friendlyUrlIndex[furlKey];
                        }
                    }
                    if (friendlyUrl != null)
                    {
                        //now merge with the friendly url for the selected page
                        PortalAliasInfo alias = PortalAliasController.GetPortalAliasInfo(httpAlias);
                        PortalSettings  ps    = new PortalSettings(tabId, alias);
                        if (pagePath != null)
                        {
                            friendlyUrl += this.EnsureLeadingChar("/", pagePath);
                        }
                        string baseUrl = "";
                        if (_noDnnPagePathTabId == tabId)
                        {
                            baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + httpAlias + this.EnsureLeadingChar("/", friendlyUrl) + options.PageExtension;//put onto http Alias with no page path
                        }
                        else
                        {
                            baseUrl = DotNetNuke.Common.Globals.NavigateURL(tabId, ps, "", friendlyUrl); //add on with page path
                        }
                        if (baseUrl != null)
                        {
                            redirectLocation = baseUrl;
                            doRedirect       = true;
                            msg += ", found friendly url " + friendlyUrl + ", redirecting";
                            messages.Add(msg);
                        }
                    }
                }
            }
            return(doRedirect);
        }
Beispiel #26
0
        ///// <summary>
        ///// Print DataTable composed of tablename,datetime,value[,flag]
        ///// with columns for each tablename
        ///// </summary>
        ///// <param name="list"></param>
        ///// <param name="table"></param>
        //private static void PrintDataTable(SeriesList list, DataTable table,
        //    Formatter fmt, TimeInterval interval)
        //{
        //    var t0 = "";
        //    if (table.Rows.Count > 0)
        //        t0 = fmt.FormatDate(table.Rows[0][1]);
        //    var vals = new string[list.Count];
        //    var flags = new string[list.Count];
        //    var dict = new Dictionary<string, int>();
        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        dict.Add(list[i].Table.TableName, i);
        //    }
        //    string t = "";
        //    bool printThisRow = false;
        //    for (int i = 0; i < table.Rows.Count; i++)
        //    {
        //        var row = table.Rows[i];
        //        t = fmt.FormatDate(row[1]);
        //        if (t != t0)
        //        {
        //            if (printThisRow)
        //                fmt.PrintRow(t0, vals, flags);
        //            vals = new string[list.Count];
        //            flags = new string[list.Count];
        //            t0 = t;
        //        }
        //        vals[dict[row[0].ToString()]] = fmt.FormatNumber(row[2]);
        //        flags[dict[row[0].ToString()]] = fmt.FormatFlag(row[3]);
        //        DateTime date = Convert.ToDateTime(row[1]);
        //        bool topOfHour = date.Minute == 0;
        //        printThisRow = fmt.HourlyOnly == false || (fmt.HourlyOnly && topOfHour);
        //    }
        //    if (printThisRow)
        //        fmt.PrintRow(t, vals, flags);
        //}
        private static TimeSeriesName[] GetTimeSeriesName(NameValueCollection query, TimeInterval interval)
        {
            List<TimeSeriesName> rval = new List<TimeSeriesName>();

            //add support for the auto generated parameter list
            //if the sites list is just the site return a list of all parameters in the table

            var sites = HydrometWebUtility.GetParameter(query, "list");

            Logger.WriteLine("GetTimeSeriesName()");
            Logger.WriteLine(query.ToString());

            var siteCodePairs = sites.Split(',');

            foreach (var item in siteCodePairs)
            {
                var tokens = item.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (tokens.Length == 2)
                {
                    TimeSeriesName tn = new TimeSeriesName(tokens[0] + "_" + tokens[1], interval);
                    rval.Add(tn);
                }
            }
            return rval.ToArray();
        }
Beispiel #27
0
        private IDictionary<string, object> Request(string method, string relativeUri, NameValueCollection query, IDictionary<string, object> data)
        {
            UriBuilder builder = new UriBuilder(BaseUri);
            if (query != null)
            {
                builder.Path = relativeUri;
                builder.Query = query.ToString();
            }
            else
            {
                int i = relativeUri.IndexOf('?');
                if (i == -1)
                {
                    builder.Path = relativeUri;
                }
                else
                {
                    builder.Path = relativeUri.Substring(0, i);
                    builder.Query = relativeUri.Substring(i);
                }
            }
            Uri uri = builder.Uri;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            req.UserAgent = UserAgent;
            req.Method = method;
            req.Accept = AcceptType;
            req.Headers.Add(
                "Accept-Charset",
                Encoding.WebName
            );
            if (Secret != null)
            {
                req.Headers.Add(
                    "Authorization",
                    "Basic " + System.Convert.ToBase64String(Encoding.UTF8.GetBytes(Secret + ":"))
                );
            }

            if (data != null)
            {
                req.ContentType = ContentType;
                string t = Serialize(data);
                byte[] content = Encoding.GetBytes(Serialize(data));
                req.ContentLength = content.Length;
                using (Stream stream = req.GetRequestStream())
                {
                    stream.Write(content, 0, content.Length);
                    stream.Close();
                }
            }

            try
            {
                using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
                {
                    using (Stream stream = resp.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream);
                        string body = reader.ReadToEnd();
                        if (body.Length == 0)
                        {
                            return null;
                        }
                        return Deserialize(body);
                    }
                }
            }
            catch (WebException ex)
            {
                Exception error = CreateError(ex);
                if (error == null)
                    throw;
                throw error;
            }
        }
Beispiel #28
0
    void ProcessPayPalIPN(System.Collections.Specialized.NameValueCollection reqParams)
    {
        if (reqParams.Count == 0)
        {
            return;
        }

        string strFormValues = reqParams.ToString();

        string strNewValue;
        string strResponse;
        // Create the request back
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(payPalURL);

        // Set values for the request back
        req.Method        = "POST";
        req.ContentType   = "application/x-www-form-urlencoded";
        strNewValue       = "cmd=_notify-validate&" + strFormValues;
        req.ContentLength = strNewValue.Length;
        // Write the request back IPN strings
        StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);

        stOut.Write(strNewValue);
        stOut.Close();

        // Do the request to PayPal and get the response
        StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());

        strResponse = stIn.ReadToEnd();
        stIn.Close();

        // Confirm whether the IPN was VERIFIED or INVALID. If INVALID, just ignore
        if (strResponse == "VERIFIED" && reqParams["txn_type"] == "web_accept")
        {
            try
            {
                NameValueCollection customParams = new NameValueCollection();
                foreach (string s in reqParams["custom"].Split('&'))
                {
                    string[] keyVal = s.Split('=');
                    if (keyVal.Length == 1)
                    {
                        customParams.Add(keyVal[0], "");
                    }
                    if (keyVal.Length >= 2)
                    {
                        customParams.Add(keyVal[0], keyVal[1]);
                    }
                }

                System.Uri uri = null;
                try
                {
                    uri = new System.Uri(customParams["domain"]);
                }
                catch (System.UriFormatException)
                {
                    uri = new System.Uri("http://" + customParams["domain"]);
                }
                if (uri.Host.Length == 0)
                {
                    throw new System.UriFormatException();
                }

                domain_    = uri.Host;
                userID_    = customParams["userId"];
                productID_ = Convert.ToInt32(reqParams["item_number"]);
                price_     = Convert.ToDouble(reqParams["mc_gross"]);
                payPalTID_ = reqParams["txn_id"];

                ProcessPayment();
            }
            catch (System.Exception)
            {
                Refund(reqParams);
                throw;
            }
        }
    }
Beispiel #29
0
 private SortedList OnDefaultWriteTrace(TraceObject traceObj)
 {
     SortedList parameters = new SortedList();
     HttpContext context = HttpContext.Current;
     if (context != null)
     {
         parameters.Add("RequestType", context.Request.RequestType);
         parameters.Add("HttpMethod", context.Request.HttpMethod);
         parameters.Add("Url", DataConvert.ToString(context.Request.Url));
         parameters.Add("UrlReferrer", DataConvert.ToString(context.Request.UrlReferrer));
         parameters.Add("LogonUser", context.Request.LogonUserIdentity.Name);
         parameters.Add("QueryString", context.Request.QueryString.ToString());
         parameters.Add("Form", context.Request.Form.ToString());
         NameValueCollection cookies = new NameValueCollection();
         for (int i = 0; i < context.Request.Cookies.Count; i++)
         {
             HttpCookie cookie = context.Request.Cookies[i];
             cookies.Add(cookie.Name, cookie.Value);
         }
         parameters.Add("Cookies", cookies.ToString());
         if (context.Items.Contains("TraceContext"))
         {
             parameters.Add("TraceContext", context.Items["TraceContext"]);
         }
     }
     parameters.Add("TraceObject", traceObj);
     return parameters;
 }
 private static string AppendQueryString(NameValueCollection queryString, string url) {
     if (queryString.Count > 0) {
         url += '?' + queryString.ToString();
     }
     return url;
 }
Beispiel #31
0
        internal static HttpResponse Post(string url, NameValueCollection requestData, ContentType contentEncode = ContentType.FormData, NameValueCollection headers = null)
        {
            HttpResponse responseData = new HttpResponse();

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Timeout = Timeout;
            httpRequest.Method = "POST";
            httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";

            string postData = string.Empty;

            if (headers != null)
                httpRequest.Headers.Add(headers);

            switch(contentEncode)
            {
                case ContentType.Json:
                    httpRequest.ContentType = "application/json";
                    var dictionary = requestData
                                    .AllKeys
                                    .ToDictionary(k => k, k => requestData[k]);
                    postData = new JavaScriptSerializer().Serialize(dictionary);
                    break;
                case ContentType.FormData:
                    httpRequest.ContentType = "application/x-www-form-urlencoded";
                    postData = requestData.ToString();
                    break;
                default:
                    postData = requestData.ToString();
                    break;
            }

            httpRequest.ContentLength = postData.Length;

            try
            {
                using (StreamWriter myWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    myWriter.Write(postData);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            HttpWebResponse httpResponse;

            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();

            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            using (StreamReader sr = new StreamReader(httpResponse.GetResponseStream()))
            {
                responseData.Response = sr.ReadToEnd();
            }

            var keys = httpResponse.Headers.AllKeys;

            foreach(var key in keys)
            {
                var values = httpResponse.Headers.GetValues(key);
                if (values.Length > 1)
                {
                    for (int i = 0; i < values.Length; i++)
                        responseData.Headers.Add(string.Format("{0}-{1}", key, i), values[i]);
                    continue;
                }
                responseData.Headers.Add(key, values.FirstOrDefault());
            }

            responseData.StatusCode = (int)httpResponse.StatusCode;
            responseData.StatusDescription = httpResponse.StatusDescription;
            responseData.Host = url;

            return responseData;
        }
Beispiel #32
0
        // Request() method runs the REST request returning the HttpStatusCode 
        public async Task<HttpStatusCode> Request()
        {
            // Build uri from base request and resource and add username and password to query string.
            resourceuri = new UriBuilder(otrs.BaseAddress+resource);
            querystring = HttpUtility.ParseQueryString(resourceuri.Query);

            querystring["UserLogin"] = _user;
            querystring["Password"] = _password; 

            resourceuri.Query = querystring.ToString();

            short retries = 0;

            while (true)
            {
                try
                {
                    // Send REST request to OTRS (3 attempts)
                    httpresponse = await otrs.PostAsJsonAsync(resourceuri.Uri.ToString(), request);

                    String rawresponse = await httpresponse.Content.ReadAsStringAsync();

                    
                    response = new ResponseTicket();
                    try
                    {
                        JToken jsonresponse = JToken.Parse(rawresponse);

                        if (jsonresponse["ArticleID"] != null)
                        {
                            response.ArticleID = jsonresponse["ArticleID"].ToString();
                        }

                        if (jsonresponse["TicketID"] != null)
                        {
                            response.TicketID = jsonresponse["TicketID"].ToString();
                        }

                        if (jsonresponse["TicketNumber"] != null)
                        {
                            response.TicketNumber = jsonresponse["TicketNumber"].ToString();
                        }
                    }
                    catch(JsonReaderException e)
                    {
                        Console.WriteLine("Invalid JSON Response: " + rawresponse);
                    }

                    // Return the HTTP Status Code.
                    return httpresponse.StatusCode;
                }
                catch(TaskCanceledException e)
                {
                    // Connection timed out, so check if we should retry
                    retries++;
                    Console.WriteLine("Connection timeout");
                    if (retries > 2) throw;
                    Console.WriteLine("Retry " + retries);
                }
                catch(InvalidOperationException e)
                {
                    // Connection timed out, so check if we should retry
                    retries++;
                    Console.WriteLine("Connection timeout");
                    if (retries > 2) throw;
                    Console.WriteLine("Retry " + retries);
                }
            }
        }
        /// <summary>
        /// Adds query string (minus exclusions) to url.
        /// </summary>
        /// <returns></returns>
        public static string GetUrlWithQueryString(this string url, NameValueCollection queryString, IEnumerable<string> exclusions)
        {
            var qs = HttpUtility.ParseQueryString(queryString.ToString());
            foreach (var e in exclusions)
            {
                qs.Remove(e);
            }

            var newUrl = qs.Count == 0 ? url : string.Format("{0}?{1}", url, qs);
            return newUrl;
        }