示例#1
0
        public static NameValueCollection ParseQueryString(string Query)
        {
            string query = null;
            var collection = new NameValueCollection();

            if (string.IsNullOrEmpty(Query))
                return new NameValueCollection();

            if (Query.Length > 0 && Query[0] == '?')
                query = Query.Substring(1);
            else
                query = Query;

            string[] items = query.Split('&');

            foreach (var item in items)
            {
                var pair = item.Split('=');

                if (pair.Length > 1)
                    collection.Add(pair[0], pair[1]);
                else
                    collection.Add(pair[0], string.Empty);
            }

            return collection;
        }
    protected void btn_Apply_Click(object sender, EventArgs e)
    {
        if ((int)ViewState["PriceID"] == 0)
        {
            MessageBox.Show(this, "对不起,请您先保存后在发起申请");
            return;
        }

        PDT_StandardPriceBLL bll = new PDT_StandardPriceBLL((int)ViewState["PriceID"]);
        if (bll.GetApplyCityDetail().Count == 0)
        {
            MessageBox.Show(this, "请点击【适用区域】按钮,选择该标准价表适用于的区域!");
            return;
        }

        bt_CompareStdPrice_Click(null, null);

        NameValueCollection dataobjects = new NameValueCollection();
        dataobjects.Add("ID", bll.Model.ID.ToString());
        dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());
        dataobjects.Add("FullName", bll.Model.FullName);
        dataobjects.Add("MaxRate", ((decimal)ViewState["MaxRate"] * 100).ToString());

        int TaskID = EWF_TaskBLL.NewTask("PDT_StandardPrice_Apply", (int)Session["UserID"], "标准价表名称:" + bll.Model.FullName, "~/SubModule/Product/PDT_StandardPriceDetail.aspx?PriceID=" + ViewState["PriceID"].ToString(), dataobjects);
        if (TaskID > 0)
        {
            bll.Model.TaskID = TaskID;
            bll.Update();
            new EWF_TaskBLL(TaskID).Start();        //直接启动流程
        }
        Response.Redirect("~/SubModule/EWF/TaskDetail.aspx?TaskID=" + TaskID.ToString());
    }
示例#3
0
        public void NameValueCollectionAdd()
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("anint", 17);
            nvc.Add("adouble", 1.234);
            nvc.Add("astring", "bugs bunny");
            nvc.Add("aguid", Guid.Empty);

            nvc.Count.Should().Be(4);

            nvc.GetValue<int>("anint").Should().Be(17);
            nvc.GetValue<double>("adouble").Should().Be(1.234);
            nvc.GetValue<string>("astring").Should().Be("bugs bunny");
            nvc.GetValue<Guid>("aguid").Should().Be(Guid.Empty);

            int i = 1;
            10.Times(() => nvc.Add("x" + i, i++));

            nvc.ToString().Should().Contain("anint");
            nvc.ToString().Should().Contain("17");
            nvc.ToString().Should().Contain("adouble");
            nvc.ToString().Should().Contain("bugs bunny");
            nvc.ToString().Should().Contain("aguid");
            nvc.ToString().Should().Contain("...");
        }
    protected void bt_Approve_Click(object sender, EventArgs e)
    {
        if ((int)ViewState["ForcastID"] != 0)
        {
            string wftitle = "经销商销量预估流程申请ID:";
            Save();
            if ((int)ViewState["ClientType"] == 3)
            {
                wftitle = "零售商销量预估流程申请ID:";
            }

            Org_StaffBLL bll = new Org_StaffBLL((int)Session["UserID"]);
            NameValueCollection dataobjects = new NameValueCollection();
            dataobjects.Add("ID", ViewState["ForcastID"].ToString());
            dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());
            dataobjects.Add("ApplyFee", SVM_ClassifyForcastBLL.GetForcastSumPrice((int)ViewState["ForcastID"]).ToString());
            int TaskID = EWF_TaskBLL.NewTask("SVM_ClassifyForcast_Approve", (int)Session["UserID"], wftitle + ViewState["ForcastID"].ToString(), "~/SubModule/SVM/ClassifyForcastDetail.aspx?ClientID=" + ViewState["ClientID"].ToString() + "&ForcastID=" + ViewState["ForcastID"].ToString(), dataobjects);
            if (TaskID > 0)
            {
                SVM_ClassifyForcastBLL.Submit((int)ViewState["ForcastID"], TaskID);
                new EWF_TaskBLL(TaskID).Start();        //直接启动流程
            }
            bt_Approve.Enabled = false;
            Response.Redirect("~/SubModule/SVM/ClassifyForcast.aspx");
        }
    }
示例#5
0
    void OnGUI()
    {
        if (GUI.Button(new Rect(Screen.width - 150,10,100,50),"Sync Back"))
        {
            string semantic = "";
            foreach (Transform o in server.mainObject.transform)
            {
                string id = o.name.ToLower();
                id = HoUtility.SimpleRegexSingle ("\\[(\\d+)\\]",id,1);
                if (id == "")
                    continue;
                int index = server.ids.IndexOf(id);
                if (index == -1)
                    continue;
                string status = server.statuses[index];
                string substatus = "";
                if (status.IndexOf(",") >= 0)
                {
                    substatus = status.Split(',')[1];
                    status = status.Split(',')[0];
                }
                semantic += id+"-"+status + "\n";
            }

            Debug.Log ("Semantic Back:\n" + semantic);
            NameValueCollection pa = new NameValueCollection();
            pa.Add("sid", server.host_id);
            pa.Add("semantic", semantic);
            wclient.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=UploadSemanticBack",pa);
        }
    }
    protected void bt_AddApply_Click(object sender, EventArgs e)
    {
        if ((int)ViewState["ID"] == 0)
        {
            MessageBox.Show(this, "对不起,请您先保存后在发起申请");
            return;
        }

        Org_StaffBLL bll = new Org_StaffBLL((int)ViewState["ID"]);

        NameValueCollection dataobjects = new NameValueCollection();
        dataobjects.Add("ID", ViewState["ID"].ToString());
        dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());
        dataobjects.Add("Position", bll.Model.Position.ToString());
        dataobjects.Add("SalaryFlag", bll.Model["SalaryFlag"].ToString());
        dataobjects.Add("StaffName", bll.Model.RealName.ToString());

        int TaskID = EWF_TaskBLL.NewTask("Add_Staff", (int)Session["UserID"], "人员入职流程,姓名:" + bll.Model.RealName, "~/SubModule/StaffManage/StaffDetail.aspx?ID=" + ViewState["ID"].ToString(), dataobjects);
        if (TaskID > 0)
        {
            bll.Model["TaskID"] = TaskID.ToString();
            bll.Model["State"] = "2";
            bll.Update();
        }

        Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString());
    }
    protected void bt_AddApply_Click(object sender, EventArgs e)
    {
        bt_OK_Click(null, null);
        if ((int)ViewState["ClientID"] == 0)
        {
            MessageBox.Show(this, "对不起,请您先保存后在发起申请");
            return;
        }

        CM_ClientBLL bll = new CM_ClientBLL((int)ViewState["ClientID"]);

        NameValueCollection dataobjects = new NameValueCollection();
        dataobjects.Add("ID", ViewState["ClientID"].ToString());
        dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());
        dataobjects.Add("ClientName", bll.Model.FullName.ToString());
        dataobjects.Add("OperateClassify", bll.Model["OperateClassify"]);
        dataobjects.Add("DIClassify", bll.Model["DIClassify"]);

        int TaskID = EWF_TaskBLL.NewTask("Add_Distributor", (int)Session["UserID"], "新增经销商流程,经销商名称:" + bll.Model.FullName, "~/SubModule/CM/DI/DistributorDetail.aspx?ClientID=" + ViewState["ClientID"].ToString(), dataobjects);
        if (TaskID > 0)
        {
            bll.Model["TaskID"] = TaskID.ToString();
            bll.Model["State"] = "2";
            bll.Update();
            //new EWF_TaskBLL(TaskID).Start();        //直接启动流程
        }

        Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString());
    }
        public void Remove_MultipleValues_SameName()
        {
            NameValueCollection nameValueCollection = new NameValueCollection();
            string name = "name";
            nameValueCollection.Add(name, "value1");
            nameValueCollection.Add(name, "value2");
            nameValueCollection.Add(name, "value3");

            nameValueCollection.Remove(name);
            Assert.Null(nameValueCollection[name]);
        }
        public void CopyTo_MultipleValues_SameName()
        {
            NameValueCollection nameValueCollection = new NameValueCollection();
            string name = "name";
            nameValueCollection.Add(name, "value1");
            nameValueCollection.Add(name, "value2");
            nameValueCollection.Add(name, "value3");

            string[] dest = new string[1];
            nameValueCollection.CopyTo(dest, 0);
            Assert.Equal(nameValueCollection[0], dest[0]);
        }
示例#10
0
    protected void Button7_Click(object sender, EventArgs e)
    {
        UserDao userDao = new UserDao();
        NameValueCollection name = new NameValueCollection();
        name.Add("Age","ASC");
        name.Add("Id", "DESC");

        Hashtable ht = new Hashtable();
        ht.Add("Age>",12);
        IList<User> list = userDao.SelectList(ht, name);
        Response.Write(list.Count);
    }
示例#11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Order order = (Order)Session["order"];
        CreditCard card = (CreditCard)Session["cc"];
        _3DSecure tdsec = (_3DSecure)Session["tds"];

        NameValueCollection col = new NameValueCollection();
        col.Add("PaReq", "123234");
        col.Add("TermUrl", "www.google.com");
        col.Add("MD", "asdasd");

        PostToUrl("http://cots-vm-cs.cloudapp.net", col);
    }
示例#12
0
        /// <summary>
        /// Sends a video file.
        /// </summary>
        /// <param name="chatId">Unique identifier for the message recipient or username of the target channel (in the format
        /// @channelusername).</param>
        /// <param name="videoId">A file id as string to resend a video that is already on the Telegram servers.</param>
        /// <param name="duration">Duration of sent video in seconds.</param>
        /// <param name="caption">Video caption.</param>
        /// <param name="disableNotification">If set to <c>true</c> sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.</param>
        /// <param name="replyToMessageId">If the message is a reply, ID of the original message.</param>
        /// <param name="replyMarkup">Additional interface options. An <see cref="IReply" /> object for a custom reply keyboard,
        /// instructions to hide keyboard or to force a reply from the user.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of
        /// cancellation.</param>
        /// <returns>
        /// On success, returns the sent <see cref="Message" />.
        /// </returns>
        /// <remarks>
        /// Telegram clients support mp4 videos (other formats may be sent as <see cref="Document" />). Bots
        /// can currently send video files of up to 50 MB in size, this limit may be changed in the future.
        /// </remarks>
        public Task<Message> SendVideoAsync([NotNull] string chatId, [NotNull] string videoId, int duration = 0, string caption = null, bool disableNotification = false, long replyToMessageId = 0, IReply replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Contracts.EnsureNotNull(chatId, nameof(chatId));
            Contracts.EnsureNotNull(videoId, nameof(videoId));

            var parameters = new NameValueCollection { { "video", videoId } };
            if( duration > 0 )
                parameters.Add("duration", duration);

            if( caption != null )
                parameters.Add("caption", caption);

            return this.CallTelegramMethodAsync<Message>(cancellationToken, "sendVideo", parameters, chatId, replyToMessageId, replyMarkup, disableNotification);
        }
示例#13
0
 public CountryProvinceBL()
 {
     nvProvince = new NameValueCollection();
     nvProvince.Add("usa", "Massachusetts");
     nvProvince.Add("usa", "California");
     nvProvince.Add("usa", "Texas");
     nvProvince.Add("usa", "New York");
     nvProvince.Add("usa", "Illinois");
     nvProvince.Add("usa", "Washington");
     nvProvince.Add("india", "Tamil Nadu");
     nvProvince.Add("india", "Karnataka");
     nvProvince.Add("india", "Andhra Pradesh?");
     nvProvince.Add("india", "Kerala");        
 }
 public static NameValueCollection ParseQueryString(string s)
 {
     NameValueCollection nvc = new NameValueCollection();
     if (s.Contains("?"))
         s = s.Substring(s.IndexOf('?') + 1);
     foreach (string vp in Regex.Split(s, "&"))
     {
         string[] singlePair = Regex.Split(vp, "=");
         if (singlePair.Length == 2)
             nvc.Add(singlePair[0], singlePair[1]);
         else
             nvc.Add(singlePair[0], String.Empty);
     }
     return nvc;
 }
    /// <summary>
    /// Authenticates the request from the OpenID provider.
    /// </summary>
    public static OpenIdData Authenticate()
    {
        OpenIdData data = (OpenIdData)HttpContext.Current.Session["openid"];

        // Make sure the client has been through the Login method
        if (data == null)
            return new OpenIdData(string.Empty);

        NameValueCollection query = HttpContext.Current.Request.QueryString;

        // Make sure the incoming request's identity matches the one stored in session
        //if (query["openid.claimed_id"] != data.Identity)
        //  return data;

        data = new OpenIdData(string.Empty, query["openid.mode"] == "id_res");
        NameValueCollection nameValueColl = new NameValueCollection();
        foreach (string name in query.Keys)
        {
            nameValueColl.Add(name.Replace("openid.sreg.", string.Empty), query[name]);
        }

        data = new OpenIdData(string.Empty, query["openid.mode"] == "id_res", nameValueColl);
        HttpContext.Current.Session.Remove("openid");
        return data;
    }
    /// <summary>
    /// Initialize the session state provider
    /// </summary>
    public override void Initialize(string name, NameValueCollection config)
    {
        
        if (config == null)
            throw new ArgumentNullException("config");

        if (name == null || name.Length == 0)
            name = "SqlSessionStateProvider";

        if (String.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "Sql session state provider");
        }

        // Initialize the abstract base class.
        base.Initialize(name, config);

        // Set the application name
        this.applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

        // Get the session state configuration
        Configuration cfg = WebConfigurationManager.OpenWebConfiguration(this.applicationName);
        sessionStateConfiguration = (SessionStateSection)cfg.GetSection("system.web/sessionState");

    } // End of the Initialize method
        public void Add_ExistingKeys()
        {
            NameValueCollection nameValueCollection1 = new NameValueCollection();
            NameValueCollection nameValueCollection2 = new NameValueCollection();

            string name = "name";
            string value1 = "value1";
            string value2 = "value2";
            nameValueCollection1.Add(name, value1);
            nameValueCollection2.Add(name, value2);

            nameValueCollection2.Add(nameValueCollection1);
            Assert.Equal(1, nameValueCollection2.Count);
            Assert.Equal(value2 + "," + value1, nameValueCollection2[name]);
            Assert.Equal(new string[] { value2, value1 }, nameValueCollection2.GetValues(name));
        }
    public void getAdmitRegistationDetail()
    {
        Session["UserImage"] = "";
        NameValueCollection objcollection11 = new NameValueCollection();
        objcls = new ClsKrisnAgr(strConnectionString);
        DataSet ds11 = new DataSet();
        objcollection11.Add("@TableId", Request.QueryString["Rid"].ToString());
        //objcollection11.Add("@Type", Session["Type"].ToString());
        ds11 = objcls.GetdataWithPera("selectStudentRegistration", objcollection11);
        if (ds11.Tables[0].Rows.Count > 0)
        {

            dr_Type.SelectedValue = ds11.Tables[0].Rows[0]["Type"].ToString();
            txtStudentId.Text=ds11.Tables[0].Rows[0]["ProfId"].ToString();
            txtName.Text=ds11.Tables[0].Rows[0]["Name"].ToString();
            dr_Graduatyear.SelectedValue=ds11.Tables[0].Rows[0]["GraduatedYear"].ToString();
            dr_course.SelectedValue=ds11.Tables[0].Rows[0]["Course"].ToString();
            txtPhone.Text=ds11.Tables[0].Rows[0]["Phone"].ToString();
            txtEmailId.Text=ds11.Tables[0].Rows[0]["Email"].ToString();
            txtParmanaantaddress.Text=ds11.Tables[0].Rows[0]["Address"].ToString();
            txtPossition.Text=ds11.Tables[0].Rows[0]["Workposition"].ToString();
            ImgPersion.ImageUrl = ds11.Tables[0].Rows[0]["Image"].ToString();
            Session["UserImage"] = ds11.Tables[0].Rows[0]["Image"].ToString();

        }
    }
 /// <summary>
 /// Convert a <see cref="System.Collections.Specialized.NameValueCollection"/> into the corresponding 
 /// common logging equivalent <see cref="Common.Logging.Configuration.NameValueCollection"/>
 /// </summary>
 /// <param name="properties">The properties.</param>
 /// <returns></returns>
 public static NameValueCollection ToCommonLoggingCollection(System.Collections.Specialized.NameValueCollection properties)
 {
     var result = new NameValueCollection();
     foreach (var key in properties.AllKeys)
         result.Add(key, properties.Get(key));
     return result;
 }
示例#20
0
 // function to get order status by order number
 public string GetOrderStatus(string ordernumber)
 {
     try
     {
         NameValueCollection nam = new NameValueCollection();
         nam.Add("_mode", "orderstatus");
         nam.Add("_id", ordernumber);
         DataTable dt = new DataTable();
         dt = objCommon.getDataTable(nam, "spPOS_General");
         return Convert.ToString(dt.Rows[0]["status"]);
     }
     catch (Exception ex)
     {
         return "Pending";
     }
 }
示例#21
0
 /// <summary>
 /// Add a name/value pair to a NameValueCollection if the value is not null.
 /// </summary>
 /// <param name="nameValueCollection">The NameValueCollection to which the name/value pair will be added if the value is not null</param>
 /// <param name="name">The string name of the entry to add.</param>
 /// <param name="value">The string key of the entry to add.</param>
 public static void AddIfNotNull(this NameValueCollection nameValueCollection, string name, string value)
 {
     if (value != null)
     {
         nameValueCollection?.Add(name, value);
     }
 }
示例#22
0
    public void ServerLoop()
    {
        while (server_status == "online")
        {
            NameValueCollection pa = new NameValueCollection();
            pa.Add("sid", host_id);

            byte[] data = client.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=SetServerAct", pa);
            current_server_activity = HoUtility.ByteToString(data);
            //main.Log("current_server_activity: " + current_server_activity);
            if (current_server_activity == "client_connected")
            {
                data = client.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=ClientIP", pa);
                revitClientIP = HoUtility.ByteToString(data).Trim();
            }
            else if (current_server_activity == "model_uploaded")
            {
                System.IO.File.Delete("building.fbx");
                client.DownloadFile(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + AppConst.SERVER_MODEL_PATH + host_id + ".fbx", "building.fbx");
                data = client.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=GetSemanticFile", pa);

                main.SetSemanticInfo(HoUtility.ByteToString(data));
                main.DownloadModelCb();
            }
            Thread.Sleep(1000);
        }
    }
    public void getAdmitRegistationDetail()
    {
        NameValueCollection objcollection11 = new NameValueCollection();
        objcls = new ClsKrisnAgr(strConnectionString);
        DataSet ds11 = new DataSet();
        objcollection11.Add("@TableId", Session["TableId"].ToString());
        objcollection11.Add("@Type", Session["Type"].ToString());
        ds11 = objcls.GetdataWithPera("selectAdminRegistration", objcollection11);
        if (ds11.Tables[0].Rows.Count > 0)
        {

            lblUserName.Text = ds11.Tables[0].Rows[0]["Name"].ToString();

            imgUserImage.ImageUrl = ds11.Tables[0].Rows[0]["Image"].ToString();

        }
    }
 public void Remove_NullName()
 {
     NameValueCollection nameValueCollection = new NameValueCollection();
     nameValueCollection.Add(null, "value");
     nameValueCollection.Remove(null);
     Assert.Equal(0, nameValueCollection.Count);
     Assert.Null(nameValueCollection[null]);
 }
    /// <summary>
    /// Initializes a new instance of the <see cref="BcpMessage"/> class with a single parameter (name/value pair).
    /// </summary>
    /// <param name="command">The message command.</param>
    /// <param name="parameterName">Name of the parameter.</param>
    /// <param name="parameterValue">The parameter value.</param>
    public BcpMessage(string command, string parameterName, string parameterValue)
    {
        Id = String.Empty;
        Command = command;
        Parameters = new NameValueCollection();

        Parameters.Add(parameterName, parameterValue);
    }
示例#26
0
    protected string GetHTMLFromURL()
    {
        string HTMLContent = string.Empty;

        if (!string.IsNullOrEmpty(_URLToConvert))
        {
            WebClient webClient = new WebClient();
            NameValueCollection queryStringCollection = new NameValueCollection();
            queryStringCollection.Add("forPDF", "1");
            webClient.QueryString = queryStringCollection;

            try
            {
                HTMLContent = webClient.DownloadString(_URLToConvert);
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                {
                    switch (((HttpWebResponse)ex.Response).StatusCode)
                    {
                        case HttpStatusCode.NotFound:
                            litResult.Text = "Web site not found";
                            break;

                        default:
                            litResult.Text = ((HttpWebResponse)ex.Response).StatusDescription;
                            break;
                    }
                }
            }

            HTMLContent = HTMLContent.Replace(" media=\"print\"", "");
            HTMLContent = HTMLContent.Replace("table.compare td .cell {\r\n    padding:8px;\r\n}\r\n", "table.compare td .cell {\r\n    padding:0px;\r\n}\r\ntable.compare td.first {font-weight:normal;} table.compare th .cell {color:#000000;height:50px;padding:0;}\r\n");
            HTMLContent = HTMLContent.Replace(".single p {\r\n\tpadding:10px 15px;\r\n\tmargin:0;\t\r\n\tfont-size:11px !important;", "h1 {border-bottom-width:0px;padding:3px;margin-bottom:0px;}\r\nh3 {padding:3px;margin:0px;font-size:13px;}\r\n.single p {\r\n\tpadding:2px;\r\n\tmargin:0;\t\r\n\tfont-size:8px !important;");
            HTMLContent = HTMLContent.Replace("<table class=\"compare\" id=\"cckfs-table\">", "<table class=\"compare\" id=\"cckfs-table\" style=\"margin-bottom:0px\">");
            HTMLContent = HTMLContent.Replace("\r\ntable.compare td, table.compare th {\r\n\tborder:1px solid #ccc;\t\r\n\tfont-size:11px !important;\r\n}", "\r\ntable.compare td, table.compare th {\r\n\tborder:1px solid #ccc;\t\r\n\tfont-size:8px !important;\r\n\tpadding:3px;\r\n}\r\ntable.compare th {\r\n\t\r\n\theight:50px;\r\n}");
            HTMLContent = HTMLContent.Replace("<strong>St.George Bank</strong></p>\r\n", "<img width='118' height='35' style='' src='" + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Images/stgeorgelogo.jpg' /></p>\r\n");
            HTMLContent = HTMLContent.Replace("<th>Product name</th>", "<th style=\"width:115px\">Product name</th>");
            HTMLContent = HTMLContent.Replace(".container {\r\n\twidth:888px;\r\n\tmargin-top:20px;\t\r\n\tfont-size:11px !important;\r\n}", ".container {\r\n\twidth:888px;\r\n\tmargin-top:0px;\t\r\n\tfont-size:11px !important;\r\n}");
            HTMLContent = HTMLContent.Replace("<td align=\"left\"", "<td");
            HTMLContent = HTMLContent.Replace("</body>", "<div style=\"font-size:8px;\">&copy;2012 St.George Bank – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714.</div></body>");

            Regex regex = new Regex("<div class=\"single\">");
            HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-width:0px\">", 1);
            HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-top-width:0px;margin-bottom:5px;\">", 1);
            Regex regex2 = new Regex("<p class=\"left\">");
            HTMLContent = regex2.Replace(HTMLContent, "<p class=\"left\" style=\"border-right-width:0px;padding:0;\">", 1);
            Regex regex3 = new Regex("<p class=\"right\">");
            HTMLContent = regex3.Replace(HTMLContent, "<p class=\"right\" style=\"padding:0px;\">", 1);
        }
        else
        {
            litResult.Text = "No web site URL";
        }

        return HTMLContent;
    }
示例#27
0
    protected string GetHTMLFromURL()
    {
        string HTMLContent = string.Empty;

        if (!string.IsNullOrEmpty(_URLToConvert))
        {
            WebClient webClient = new WebClient();
            NameValueCollection queryStringCollection = new NameValueCollection();
            queryStringCollection.Add("forPDF", "1");
            webClient.QueryString = queryStringCollection;

            try
            {
                HTMLContent = webClient.DownloadString(_URLToConvert);
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                {
                    switch (((HttpWebResponse)ex.Response).StatusCode)
                    {
                        case HttpStatusCode.NotFound:
                            litResult.Text = "Web site not found";
                            break;

                        default:
                            litResult.Text = ((HttpWebResponse)ex.Response).StatusDescription;
                            break;
                    }
                }
            }

            HTMLContent = HTMLContent.Replace(" media=\"print\"", "");
            HTMLContent = HTMLContent.Replace(".single p{padding:15px; margin:0;}", ".single p{padding:5px; margin:0;font-size:8px !important;} table.compare td .cell {padding: 0; } table.compare td.first {font-weight:normal;} table.compare th .cell {color:#000000;} .single p.left {font-size:11px !important;}");
            HTMLContent = HTMLContent.Replace("table.compare td,table.compare th{border:1px solid #ccc;}", "table.compare td,table.compare th{border:1px solid #ccc;font-size:8px;padding:3px;height:0;}");
            HTMLContent = HTMLContent.Replace("<strong>Bank of Melbourne</strong>", "<img style='margin-left:5px' width='31' height='45' src='" + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Images/bankofmelblogo.jpg' /><br/><strong>Bank of Melbourne</strong>");
            HTMLContent = HTMLContent.Replace("<th>Product name</th>", "<th style=\"width:115px\">Product name</th>");
            HTMLContent = HTMLContent.Replace("<table class=\"compare\">", "<table class=\"compare\" style=\"margin-bottom:0px\">");
            HTMLContent = HTMLContent.Replace(".clear{clear:both}", ".clear{clear:both}\r\ntable.compare th .cell { padding:2px;height:25px; } h2, h3 { font-size: 10px; }\r\nh1{margin-bottom:5px !important;padding-bottom:0px !important;;border-bottom-width:0;}\r\nh2{font-size:12px;margin:3px 0;padding:0 !important;}\r\nh3{font-size:14px;margin:0 !important;}");
            HTMLContent = HTMLContent.Replace(".container{width:888px;margin-top:20px;}", ".container{width:888px;margin-top:0px;}");
            HTMLContent = HTMLContent.Replace("<td align=\"left\"", "<td");
            HTMLContent = HTMLContent.Replace("</body>", "<div style=\"font-size:8px;\">&copy;2012 Bank of Melbourne – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714.</div></body>");

            Regex regex = new Regex("<div class=\"single\">");
            HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-width:0px;margin-bottom:5px;\">", 1);
            HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-top-width:0px;margin-bottom:5px;\">", 1);
            Regex regex2 = new Regex("<p class=\"left\">");
            HTMLContent = regex2.Replace(HTMLContent, "<p class=\"left\" style=\"border-right-width:0px;padding:0px;\">", 1);
            Regex regex3 = new Regex("<p class=\"right\">");
            HTMLContent = regex3.Replace(HTMLContent, "<p class=\"right\" style=\"border-right-width:0px;padding:0px;float:right;text-align:center;\">", 1);
        }
        else
        {
            litResult.Text = "No web site URL";
        }

        return HTMLContent;
    }
示例#28
0
 public static string NameValueToSql(Dictionary<string,object> dict, string table, string primary, bool insert)
 {
     NameValueCollection nvc = new NameValueCollection();
     foreach (KeyValuePair<string,object> item in dict)
     {
         nvc.Add(item.Key, item.Value.ToString());
     }
     return NameValueToSql(nvc, table, primary, insert);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        string workingKey = "79226183BBAE50766E8383CEA3FF089D";//put in the 32bit alpha numeric key in the quotes provided here
        CCACrypto ccaCrypto = new CCACrypto();
        string encResponse = ccaCrypto.Decrypt(Request.Form["encResp"], workingKey);
        NameValueCollection Params = new NameValueCollection();
        string[] segments = encResponse.Split('&');
        foreach (string seg in segments)
        {
            string[] parts = seg.Split('=');
            if (parts.Length > 0)
            {
                string Key = parts[0].Trim();
                string Value = parts[1].Trim();
                Params.Add(Key, Value);
            }
        }

        for (int i = 0; i < Params.Count; i++)
        {
            //Response.Write(Params.Keys[i] + " = " + Params[i] + "<br>");

            //Bank Transaction
            ViewState["order_id "] = Params[0].ToString();
            ViewState["tracking_id"] = Params[1].ToString();
            ViewState["bank_ref_no"] = Params[2].ToString();
            ViewState["order_status"] = Params[3].ToString();
            ViewState["failure_status"] = Params[4].ToString();
            ViewState["payment_mode"] = Params[5].ToString();
            ViewState["card_name"] = Params[6].ToString();
            ViewState["status_code"] = Params[7].ToString();
            ViewState["status_message"] = Params[8].ToString();
            ViewState["currency"] = Params[9].ToString();
            ViewState["amount"] = Params[10].ToString();

            ////Billing Information
            ViewState["billing_name"] = Params[11].ToString();
            ViewState["billing_address"] = Params[12].ToString();
            ViewState["billing_city"] = Params[13].ToString();
            ViewState["billing_state"] = Params[14].ToString();
            ViewState["billing_zip"] = Params[15].ToString();
            ViewState["billing_country"] = Params[16].ToString();
            ViewState["billing_tel"] = Params[17].ToString();
            ViewState["billing_email"] = Params[18].ToString();

            //MessageBox(ViewState["card_name"].ToString().Trim());

            PaymentSuccess();
            Session["Ticket"] = "goTicket";
            BindBankTransaction();
            //Response.Redirect("Ticket.aspx");

            Redirect();

        }
    }
示例#30
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="request"></param>
        /// <param name="result"></param>
        /// <param name="statusCode"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public Attachment Map(string key, HttpWebRequest request, IAsyncResult result, out HttpStatusCode statusCode,
                              out Exception exception)
        {
            try
            {
                var response = request.EndGetResponse(result) as HttpWebResponse;
                Stream stream = response.GetResponseStream();

                statusCode = response.StatusCode;
                exception = null;

                var headers = new NameValueCollection();
                foreach (string headerKey in response.Headers.AllKeys)
                {
                    headers.Add(headerKey, response.Headers[key]);
                }

                return new Attachment
                           {
                               Data = stream.ReadData(),
                               Etag = new Guid(response.Headers["ETag"]),
                               Metadata = headers.FilterHeaders(isServerDocument: false)
                           };
            }
            catch (WebException ex)
            {
                var httpWebResponse = ex.Response as HttpWebResponse;
                if (httpWebResponse == null)
                {
                    throw;
                }

                statusCode = httpWebResponse.StatusCode;
                exception = AsyncServerClient.ExtractException(httpWebResponse);

                if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
                {
                    JObject conflictsDoc = JObject.Load(new BsonReader(httpWebResponse.GetResponseStream()));
                    string[] conflictIds =
                        conflictsDoc.Value<JArray>("Conflicts").Select(x => x.Value<string>()).ToArray();

                    throw new ConflictException("Conflict detected on " + key +
                                                ", conflict must be resolved before the attachment will be accessible")
                              {
                                  ConflictedVersionIds = conflictIds
                              };
                }

                if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }

                throw;
            }
        }
示例#31
0
    // function to set order status done after automaticlly  send to kitchen
    public string ChangeStatusPickup(string ordernumber)
    {
        string jsonResult = "";

        try
        {
            NameValueCollection nam = new NameValueCollection();
            nam.Add("_mode", "sendtokitchenpickup");
            nam.Add("_id", ordernumber);
            objCommon.commonMethod(nam, "spPOS_General");
            jsonResult = "{\"Status\":\"Success\"}";
        }
        catch (Exception ex)
        {
            jsonResult = "{\"Error\":\"Please try again\"}";
        }

        return jsonResult;
    }
示例#32
0
        private NameValueCollection BuildRequestData(Transaction t)
        {
            var parameters = new NameValueCollection
            {
                { "x_version", "3.1" },
                { "x_login", Settings.MerchantLoginId },
                { "x_tran_key", Settings.TransactionKey },
                { "x_Amount", t.Amount.ToString(CultureInfo.InvariantCulture) },
                { "x_Cust_ID", t.Customer.Email },
                { "x_Description", t.MerchantDescription },
                { "x_invoice_num", t.MerchantInvoiceNumber },
                { "x_Email_Customer", WriteBool(Settings.SendEmailToCustomer) },
                { "x_delim_data", WriteBool(true) },
                { "x_delim_char", "," },
                { "x_relay_response", WriteBool(false) },
                { "x_Email", t.Customer.Email },
                { "x_First_Name", t.Customer.FirstName },
                { "x_Last_Name", t.Customer.LastName },
                { "x_Company", t.Customer.Company },
                { "x_Address", t.Customer.Street },
                { "x_City", t.Customer.City }
            };

            var country = t.Customer.CountryData;

            if (country != null)
            {
                parameters.Add("x_Country", country.IsoNumeric);
            }
            else
            {
                parameters.Add("x_Country", t.Customer.CountryName);
            }
            // TODO: Add code to make sure we've got the correct state format
            if (!string.IsNullOrWhiteSpace(t.Customer.RegionName))
            {
                parameters.Add("x_State", t.Customer.RegionName);
            }

            parameters.Add("x_Zip", t.Customer.PostalCode);
            parameters.Add("x_Phone", t.Customer.Phone);

            parameters.Add("x_Ship_To_First_Name", t.Customer.ShipFirstName);
            parameters.Add("x_Ship_To_Last_Name", t.Customer.ShipLastName);
            parameters.Add("x_Ship_To_Company", t.Customer.ShipCompany);
            parameters.Add("x_Ship_To_Address", t.Customer.ShipStreet);
            parameters.Add("x_Ship_To_City", t.Customer.ShipCity);
            var shipcountry = t.Customer.ShipCountryData;

            if (shipcountry != null)
            {
                parameters.Add("x_Ship_To_Country", shipcountry.IsoNumeric);
            }
            else
            {
                parameters.Add("x_Ship_To_Country", t.Customer.ShipCountryName);
            }
            // TODO: Add code to make sure we've got the correct state format
            if (!string.IsNullOrWhiteSpace(t.Customer.ShipRegionName))
            {
                parameters.Add("x_Ship_To_State", t.Customer.ShipRegionName);
            }
            parameters.Add("x_Ship_To_Zip", t.Customer.ShipPostalCode);
            parameters.Add("x_Ship_To_Phone", t.Customer.ShipPhone);

            parameters.Add("x_Method", "CC");

            if (Settings.TestMode)
            {
                parameters.Add("x_test_request", WriteBool(true));
            }

            switch (t.Action)
            {
            case ActionType.CreditCardCharge:
                // Charge
                parameters.Add("x_Type", "AUTH_CAPTURE");
                parameters.Add("x_customer_ip", t.Customer.IpAddress);
                break;

            case ActionType.CreditCardHold:
                // Authorize
                parameters.Add("x_Type", "AUTH_ONLY");
                parameters.Add("x_customer_ip", t.Customer.IpAddress);
                break;

            case ActionType.CreditCardCapture:
                // Capture, Post Authorize
                parameters.Add("x_Type", "PRIOR_AUTH_CAPTURE");
                parameters.Add("x_trans_id", t.PreviousTransactionNumber);
                break;

            case ActionType.CreditCardVoid:
                // Void
                parameters.Add("x_Type", "VOID");
                parameters.Add("x_trans_id", t.PreviousTransactionNumber);
                break;

            case ActionType.CreditCardRefund:
                // Refund, Credit
                parameters.Add("x_Type", "CREDIT");
                parameters.Add("x_trans_id", t.PreviousTransactionNumber);
                break;
            }

            // Add Card Number, CVV Code and Expiration Date
            parameters.Add("x_Card_Num", t.Card.CardNumber);
            if (!string.IsNullOrEmpty(t.Card.SecurityCode))
            {
                parameters.Add("x_Card_Code", t.Card.SecurityCode);
            }
            var expDate = t.Card.ExpirationMonthPadded + t.Card.ExpirationYearTwoDigits;

            parameters.Add("x_Exp_Date", expDate);
            return(parameters);
        }
示例#33
0
        public void Login(string id, string pass, int loginMethod, QRCodeClass qrcodeClass = null, string service_code = "610074", string service_region = "T9")
        {
            this.webtoken = null;
            try
            {
                string response = null;
                string skey     = null;
                string akey     = null;
                if (loginMethod == (int)LoginMethod.QRCode)
                {
                    skey = qrcodeClass.skey;
                }
                else
                {
                    skey = GetSessionkey();
                }

                switch (loginMethod)
                {
                case (int)LoginMethod.Regular:
                    akey = RegularLogin(id, pass, skey);
                    break;

                case (int)LoginMethod.QRCode:
                    akey = QRCodeLogin(qrcodeClass);
                    break;

                default:
                    this.errmsg = "LoginNoMethod";
                    return;
                }
                if (akey == null)
                {
                    return;
                }

                NameValueCollection payload = new NameValueCollection();
                payload.Add("SessionKey", skey);
                payload.Add("AuthKey", akey);
                Debug.WriteLine(skey);
                Debug.WriteLine(akey);
                response = Encoding.UTF8.GetString(this.UploadValues("https://tw.beanfun.com/beanfun_block/bflogin/return.aspx", payload));
                Debug.WriteLine(response);
                response = this.DownloadString("https://tw.beanfun.com/" + this.ResponseHeaders["Location"]);
                Debug.WriteLine(response);
                Debug.WriteLine(this.ResponseHeaders);

                this.webtoken = this.GetCookie("bfWebToken");
                if (this.webtoken == "")
                {
                    this.errmsg = "LoginNoWebtoken"; return;
                }

                GetAccounts(service_code, service_region, false);
            }
            catch (Exception e)
            {
                if (e is WebException)
                {
                    this.errmsg = "網路連線錯誤,請檢查官方網站連線是否正常。" + e.Message;
                }
                else
                {
                    this.errmsg = "LoginUnknown\n\n" + e.Message + "\n" + e.StackTrace;
                }
                return;
            }
        }
        public string this[string FieldName]
        {
            get
            {
                switch (FieldName)
                {
                case "ID":
                    return(_id.ToString());

                case "Job":
                    return(_job.ToString());

                case "JobType":
                    return(_jobtype.ToString());

                case "JudgeMode":
                    return(_judgemode.ToString());

                case "Longitude":
                    return(_longitude.ToString());

                case "Latitude":
                    return(_latitude.ToString());

                case "Remark":
                    return(_remark);

                default:
                    if (_extpropertys == null)
                    {
                        return("");
                    }
                    else
                    {
                        return(_extpropertys[FieldName]);
                    }
                }
            }
            set
            {
                switch (FieldName)
                {
                case "ID":
                    int.TryParse(value, out _id);
                    break;

                case "Job":
                    int.TryParse(value, out _job);
                    break;

                case "JobType":
                    int.TryParse(value, out _jobtype);
                    break;

                case "JudgeMode":
                    int.TryParse(value, out _judgemode);
                    break;

                case "Longitude":
                    double.TryParse(value, out _longitude);
                    break;

                case "Latitude":
                    double.TryParse(value, out _latitude);
                    break;

                case "Remark":
                    _remark = value;
                    break;

                default:
                    if (_extpropertys == null)
                    {
                        _extpropertys = new NameValueCollection();
                    }
                    if (_extpropertys[FieldName] == null)
                    {
                        _extpropertys.Add(FieldName, value);
                    }
                    else
                    {
                        _extpropertys[FieldName] = value;
                    }
                    break;
                }
            }
        }
示例#35
0
        /// <summary>
        ///     Collects the specified name.
        /// </summary>
        /// <param name="name">Management object table.</param>
        public void Collect(string name)
        {
            var filter   = Filter;
            var searcher = new ManagementObjectSearcher("SELECT * FROM " + name);

            foreach (var item in searcher.Get())
            {
                foreach (var sp in item.Properties)
                {
                    if (sp.Value == null)
                    {
                        continue;
                    }
                    if (filter != null && filter.Any(x => x.Equals(sp.Name, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    if (sp.Value is string)
                    {
                        var value = Convert.ToString(sp.Value);
                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }

                        //naive attempt to detect dates.
                        if (value.Length == "20100131022308.000000-360".Length &&
                            (value[value.Length - 4] == '-' || value[value.Length - 4] == '+') && value[14] == '.')
                        {
                            try
                            {
                                value = ManagementDateTimeConverter.ToDateTime(value).ToUniversalTime().ToString();
                            }
                            catch (Exception exception)
                            {
                                _collection.Add(sp.Name + ".error", exception.ToString());
                            }
                        }

                        _collection.Add(sp.Name, value);
                    }
                    else if (sp.Value is IEnumerable || sp.IsArray)
                    {
                        _collection.Add(sp.Name, string.Join(";;", (IEnumerable)sp.Value));
                    }
                    else
                    {
                        //System.Management.ManagementDateTimeConverter.ToDateTime("20100131022308.000000-360");

                        var value = Convert.ToString(sp.Value);

                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }

                        _collection.Add(sp.Name, value);
                    }
                }
            }
        }
示例#36
0
        public ActionResult BoostCheckOut(string destinationUrl = null, BoostPaymentModels model = null) ////
        {
            if (model == null && !Core.IsForLocalHost)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            //string destinationUrl2 = Url.Action("TestCheckOut", "Checkout");

            NameValueCollection formData  = new NameValueCollection();
            string BoostRequestPaymentURL = Core.GetAppSettingValueEnhanced("BoostRequestPaymentURL");
            string adyenAppId             = Core.GetAppSettingValueEnhanced("BoostAppId");

            if (Core.IsForStaging) /////for test only
            {
                //formData.Add("onlineRefNum", "2148 - 0VMKG6T");
                //formData.Add("AppID", adyenAppId);
                //formData.Add("amount", "0.01");
                //formData.Add("remark", "ticket");
                //formData.Add("responseURL", destinationUrl);
                //formData.Add("initiatorMobileNo", "+6012346789"); //not sure
                //formData.Add("redirectLabel", "");
                //formData.Add("redirectDeepLink", "");
                formData.Add("onlineRefNum", model.SuperPNRID + " - " + model.SuperPNRNo);
                formData.Add("AppID", adyenAppId);
                formData.Add("amount", "0.01");
                formData.Add("remark", "ticket");
                formData.Add("responseURL", destinationUrl);
                formData.Add("initiatorMobileNo", model.UserContact);
                formData.Add("redirectLabel", "");
                formData.Add("redirectDeepLink", "");
            }
            else
            {
                //follow local after done test
                formData.Add("onlineRefNum", model.SuperPNRID + " - " + model.SuperPNRNo);
                formData.Add("AppID", adyenAppId);
                formData.Add("amount", model.PaymentAmount.ToString());
                formData.Add("remark", "ticket");
                formData.Add("responseURL", destinationUrl);
                formData.Add("initiatorMobileNo", model.UserContact);
                formData.Add("redirectLabel", "");
                formData.Add("redirectDeepLink", "");
            }

            string strForm = PrepareBoostPOSTForm(BoostRequestPaymentURL, formData);

            return(Content(strForm));
        }
示例#37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        IYCDataUtility objIYC = new IYCDataUtility();

        strHTTP_HOST = HttpContext.Current.Request.Url.Host.ToUpper();
        try
        {
            if (Request.QueryString.HasKeys())
            {
                UniqueId = Request.QueryString["ID"].ToString();
            }



            DataTable dtData = new DataTable();
            dtData = objIYC.GetDataTable("select amount,firstname,email,phone,productinfo from FM_PMGRegistrationFee where uniquetxnno='" + UniqueId + "'");
            if (dtData.Rows.Count > 0)
            {
                amount.Text = dtData.Rows[0]["amount"].ToString();


                collection.Add("amount", dtData.Rows[0]["amount"].ToString());

                /*collection.Add("firstname", dtData.Rows[0]["firstname"].ToString());
                 * collection.Add("email", dtData.Rows[0]["email"].ToString());
                 * collection.Add("phone", dtData.Rows[0]["phone"].ToString());
                 * collection.Add("productinfo", dtData.Rows[0]["productinfo"].ToString());*/
                firstname.Value   = dtData.Rows[0]["firstname"].ToString();
                email.Value       = dtData.Rows[0]["email"].ToString();
                phone.Value       = dtData.Rows[0]["phone"].ToString();
                productinfo.Value = dtData.Rows[0]["productinfo"].ToString();
            }

            /*amount.Text = Request.Form["amount"];
             * firstname.Value = Request.Form["firstname"];
             * email.Value = Request.Form["email"];
             * phone.Value = Request.Form["phone"];
             * productinfo.Value = Request.Form["productinfo"];*/

            if ((strHTTP_HOST == "LOCALHOST") || (strHTTP_HOST == "DOTNET"))
            {
                surl.Value = "http://dotnet/DPSBopal/ProgramFiles/PG/ResponseHandling.aspx";
                furl.Text  = "http://dotnet/DPSBopal/ProgramFiles/PG/ResponseHandling.aspx";
                curl.Text  = "http://dotnet/DPSBopal/ProgramFiles/PG/ResponseHandling.aspx";
            }
            else
            {
                surl.Value = "http://dpsbopal.iycworld.com/ProgramFiles/PG/ResponseHandling.aspx";
                furl.Text  = "http://dpsbopal.iycworld.com/ProgramFiles/PG/ResponseHandling.aspx";
                curl.Text  = "http://dpsbopal.iycworld.com/ProgramFiles/OPG/ResponseHandling.aspx";
            }



            key.Value    = ConfigurationManager.AppSettings["MERCHANT_KEY"];
            form1.Action = "SubmitRedirect.aspx";

            /*if (!IsPostBack)
             * {
             *  //frmError.Visible = false; // error form
             * }
             * else
             * {
             *  //frmError.Visible = true;
             * }
             * if (string.IsNullOrEmpty(Request.Form["hash"]))
             * {
             *  submit.Visible = true;
             * }
             * else
             * {
             *  submit.Visible = false;
             * }*/
        }
        catch (Exception ex)
        {
            Response.Write("<span style='color:red'>" + ex.Message + "</span>");
        }
    }
示例#38
0
    private void ParseQueryString(string query, Encoding encoding, NameValueCollection result)
    {
        // taken from: https://gist.github.com/Ran-QUAN/d966423305ce70cbc320f319d9485fa2
        // as alternative to using C# module which was giving problems when building
        if (query.Length == 0)
        {
            return;
        }

        var decodedLength = query.Length;
        var namePos       = 0;
        var first         = true;

        while (namePos <= decodedLength)
        {
            int valuePos = -1, valueEnd = -1;
            for (var q = namePos; q < decodedLength; q++)
            {
                if ((valuePos == -1) && (query[q] == '='))
                {
                    valuePos = q + 1;
                }
                else if (query[q] == '&')
                {
                    valueEnd = q;
                    break;
                }
            }

            if (first)
            {
                first = false;
                if (query[namePos] == '?')
                {
                    namePos++;
                }
            }

            string name;
            if (valuePos == -1)
            {
                name     = null;
                valuePos = namePos;
            }
            else
            {
                name = UnityWebRequest.UnEscapeURL(query.Substring(namePos, valuePos - namePos - 1), encoding);
            }
            if (valueEnd < 0)
            {
                namePos  = -1;
                valueEnd = query.Length;
            }
            else
            {
                namePos = valueEnd + 1;
            }
            var value = UnityWebRequest.UnEscapeURL(query.Substring(valuePos, valueEnd - valuePos), encoding);

            result.Add(name, value);
            if (namePos == -1)
            {
                break;
            }
        }
    }
示例#39
0
        public static NameValueCollection GetStrings()
        {
            NameValueCollection vCardMaker_Lang = new NameValueCollection();

            // Validator strings
            vCardMaker_Lang.Add("NoVersion", "The vCard version is blank.");
            vCardMaker_Lang.Add("NoFormattedName", "The full name is blank.");
            vCardMaker_Lang.Add("NoForename", "The forename is blank.");
            vCardMaker_Lang.Add("NoSurname", "The surname is blank.");
            vCardMaker_Lang.Add("NoNameSource", "If name or source are used, then both must be provided.");
            vCardMaker_Lang.Add("NoBirthdate", "The birth date is not in the correct format.");
            vCardMaker_Lang.Add("NoBirthdatetime", "If the birth time is provided then the birth date must be provided.");
            vCardMaker_Lang.Add("NoBirthtime", "The birth time is not in the correct format.");
            vCardMaker_Lang.Add("NoBirthtimezone", "If the birth timezone is provided then the birth time must be provided.");
            vCardMaker_Lang.Add("NoSoundPhonetic", "The phonetic type for a sound cannot be used in a 3.0 vCard.");
            vCardMaker_Lang.Add("NoSoundPhoneticR", "The phonetic representation for your sound is blank.");
            vCardMaker_Lang.Add("NoSoundURL", "The URL for your sound is blank.");
            vCardMaker_Lang.Add("NoSoundSource", "The sound source is blank.");
            vCardMaker_Lang.Add("NoPhotoURL", "The photo URL is blank.");
            vCardMaker_Lang.Add("NoPhotoSource", "The photo source is blank.");
            vCardMaker_Lang.Add("NoPhotoQP", "The Quoted-Printable type for a photo cannot be used in a 3.0 vCard.");
            vCardMaker_Lang.Add("NoDeliveryStreet", "The street name for your address is blank.");
            vCardMaker_Lang.Add("NoDeliveryLocality", "The locality for your address is blank.");
            vCardMaker_Lang.Add("NoDeliveryPostCode", "The postal code for your address is blank.");
            vCardMaker_Lang.Add("NoDeliveryCountry", "The country for your address is blank.");
            vCardMaker_Lang.Add("NoLabelStreet", "The street name for your delivery label is blank.");
            vCardMaker_Lang.Add("NoLabelLocality", "The locality for your delivery label is blank.");
            vCardMaker_Lang.Add("NoLabelPostCode", "The postal code for your delivery label is blank.");
            vCardMaker_Lang.Add("NoLabelCountry", "The country for your delivery label is blank.");
            vCardMaker_Lang.Add("NoTelNumber", "The telephone number is blank.");
            vCardMaker_Lang.Add("NoEmailAddress", "The email address is blank.");
            vCardMaker_Lang.Add("NoGeoLoc", "The geographical location is incorrect.");
            vCardMaker_Lang.Add("NoLogoURL", "The URL for your logo is blank.");
            vCardMaker_Lang.Add("NoLogoSource", "The logo source is blank.");
            vCardMaker_Lang.Add("NoLogoQP", "The Quoted-Printable type for a logo cannot be used in a 3.0 vCard.");
            vCardMaker_Lang.Add("NoAgentvCard", "The vCard for your agent is blank.");
            vCardMaker_Lang.Add("NoAgentURL", "The URL for your agent is blank.");
            vCardMaker_Lang.Add("NoAgentURLType", "The URL agent type cannot be used in a 2.1 vCard.");
            vCardMaker_Lang.Add("NoKeyBinary", "The binary key type cannot be used in a 2.1 vCard.");
            vCardMaker_Lang.Add("NoKeyPGPX509", "The PGP and X.509 key types cannot be used in a 3.0 vCard.");
            vCardMaker_Lang.Add("NoKeySource", "The key is blank.");
            vCardMaker_Lang.Add("VErrorsFound", "The following errors were found:");

            // Email strings
            vCardMaker_Lang.Add("ESubject", "Your vCard from vCardMaker");
            vCardMaker_Lang.Add("EMessage", "Hello!\n\nYou recently created a vCard using vCardMaker and asked us to email it to you. Your vCard is included below between the dashes. If you didn't request this message, please reply to this email and we'll do our best to make sure it doesn't happen again.\n\nThank you for using vCardMaker!");

            return(vCardMaker_Lang);
        }
示例#40
0
        /// <summary>
        /// http://tools.ietf.org/html/rfc1459#section-2.3.1
        /// </summary>
        /// <param name="sr"></param>
        /// <returns></returns>
        private Message _read(StreamReader sr)
        {
            //  Initialize buffers
            MessageState        mode      = MessageState.Start;
            NameValueCollection tags      = new NameValueCollection();
            StringBuilder       key       = new StringBuilder();
            StringBuilder       value     = new StringBuilder();
            StringBuilder       input     = new StringBuilder();
            StringBuilder       prefix    = new StringBuilder();
            StringBuilder       command   = new StringBuilder();
            StringBuilder       parameter = new StringBuilder();
            List <string>       @params   = new List <string>();

            do
            {
                char[] ca = new char[1];
                sr.Read(ca, 0, 1);
                char c = ca[0];
                input.Append(c);

                switch (mode)
                {
                case MessageState.Start:
                    switch (c)
                    {
                    case '@':
                        mode = MessageState.TagKey;
                        break;

                    case ':':
                        mode = MessageState.Prefix;
                        break;

                    case ' ':
                        break;

                    case '\r':
                        mode = MessageState.EndLine;
                        break;

                    default:
                        mode = MessageState.Command;
                        if (char.IsLetterOrDigit(c))
                        {
                            command.Append(c);
                        }
                        else
                        {
                            throw new FormatException(string.Format("Unexpected character in command {0}.", (int)c));
                        }
                        break;
                    }
                    break;

                case MessageState.TagKey:
                    switch (c)
                    {
                    case ' ':
                        mode = MessageState.Start;
                        tags.Add(key.ToString(), null);
                        key.Clear();
                        break;

                    case ';':
                        mode = MessageState.TagKey;
                        tags.Add(key.ToString(), null);
                        key.Clear();
                        break;

                    case '=':
                        mode = MessageState.TagValue;
                        break;

                    case '\r':
                        mode = MessageState.EndLine;
                        key.Clear();
                        break;

                    default:
                        if (char.IsLetterOrDigit(c) || c == '-' || c == '.' || c == '/')
                        {
                            key.Append(c);
                        }
                        else
                        {
                            throw new FormatException(string.Format("Unexpected character {0} found.", (int)c));
                        }
                        break;
                    }
                    break;

                case MessageState.TagValue:
                    switch (c)
                    {
                    case ' ':
                        mode = MessageState.Start;
                        tags.Add(key.ToString(), value.ToString());
                        key.Clear();
                        value.Clear();
                        break;

                    case ';':
                        mode = MessageState.TagKey;
                        tags.Add(key.ToString(), value.ToString());
                        key.Clear();
                        value.Clear();
                        break;

                    case '\\':
                        if (sr.Peek() == -1)
                        {
                            throw new EndOfStreamException("Unexpected end of stream during escape sequence.");
                        }
                        char x = (char)sr.Read();
                        switch (x)
                        {
                        case ':':
                            value.Append(';');
                            break;

                        case 's':
                            value.Append(' ');
                            break;

                        case '\\':
                            value.Append('\\');
                            break;

                        case 'r':
                            value.Append('\r');
                            break;

                        case 'n':
                            value.Append('\n');
                            break;

                        default:
                            throw new FormatException(string.Format("Unexpected escape sequence {0}.", (int)c));
                        }
                        break;

                    case '\r':
                    case '\n':
                    case '\0':
                        throw new FormatException("Unexpected character in escaped value.");

                    default:
                        value.Append(c);
                        break;
                    }
                    break;

                case MessageState.Prefix:
                    switch (c)
                    {
                    case ' ':
                        mode = MessageState.Start;
                        break;

                    case '\r':
                    case '\n':
                    case '\0':
                        throw new FormatException("Unexpected character in prefix.");

                    default:
                        prefix.Append(c);
                        break;
                    }
                    break;

                case MessageState.Command:
                    switch (c)
                    {
                    case ' ':
                        mode = MessageState.StartParameter;
                        break;

                    default:
                        if (char.IsLetterOrDigit(c))
                        {
                            command.Append(c);
                        }
                        else
                        {
                            throw new FormatException(string.Format("Unexpected character in command {0}.", (int)c));
                        }
                        break;
                    }
                    break;

                case MessageState.StartParameter:
                    switch (c)
                    {
                    case ' ':
                        break;

                    case ':':
                        mode = MessageState.Trailing;
                        break;

                    case '\r':
                        mode = MessageState.EndLine;
                        break;

                    case '\n':
                    case '\0':
                        throw new FormatException(string.Format("Unexpected character in parameter list {0}.", (int)c));

                    default:
                        mode = MessageState.Parameter;
                        parameter.Append(c);
                        break;
                    }
                    break;

                case MessageState.Parameter:
                    switch (c)
                    {
                    case ' ':
                        mode = MessageState.StartParameter;
                        if (parameter.Length > 0)
                        {
                            @params.Add(parameter.ToString());
                        }
                        parameter.Clear();
                        break;

                    case '\r':
                        mode = MessageState.EndLine;
                        break;

                    case '\n':
                    case '\0':
                        throw new FormatException("Unexpected character in parameter list.");

                    default:
                        parameter.Append(c);
                        break;
                    }
                    break;

                case MessageState.Trailing:
                    switch (c)
                    {
                    case '\r':
                        mode = MessageState.EndLine;
                        break;

                    case '\n':
                    case '\0':
                        throw new FormatException("Unexpected character in trailing parameter.");

                    default:
                        parameter.Append(c);
                        break;
                    }
                    break;

                case MessageState.EndLine:
                    if (c == '\n')
                    {
                        input.Remove(input.Length - 2, 2);
                        var lastParam = parameter.ToString();
                        if (!string.IsNullOrWhiteSpace(lastParam))
                        {
                            @params.Add(lastParam);
                        }
                        var message = new Message
                        {
                            Raw        = input.ToString(),
                            Tags       = tags,
                            Prefix     = prefix.ToString(),
                            Command    = command.ToString(),
                            Parameters = @params.ToArray()
                        };

                        OnReceived(message);

                        return(message);
                    }
                    else
                    {
                        throw new FormatException(string.Format("Found {0} instead of LF character.", (int)c));
                    }
                }
            } while (sr.Peek() != -1);
            throw new EndOfStreamException("Stream ended before a full message could be constructed");
        }
        public override NameValueCollection AsNameValues(string entryId)
        {
            var data = new NameValueCollection();

            data.Add(clsSuiteCRMHelper.SetNameValuePair("email1", Email1Address));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("title", JobTitle));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("phone_work", BusinessTelephoneNumber));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("phone_home", HomeTelephoneNumber));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("phone_mobile", MobileTelephoneNumber));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("phone_fax", BusinessFaxNumber));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("department", Department));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("primary_address_city", BusinessAddressCity));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("primary_address_state", BusinessAddressState));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("primary_address_postalcode", BusinessAddressPostalCode));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("primary_address_country", BusinessAddressCountry));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("primary_address_street", BusinessAddressStreet));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("description", Body));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("last_name", LastName));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("first_name", FirstName));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("account_name", CompanyName));
            data.Add(clsSuiteCRMHelper.SetNameValuePair("salutation", Title));
            data.Add(string.IsNullOrEmpty(entryId) ?
                     clsSuiteCRMHelper.SetNameValuePair("assigned_user_id", clsSuiteCRMHelper.GetUserId()) :
                     clsSuiteCRMHelper.SetNameValuePair("id", entryId));

            return(data);
        }
示例#42
0
        /// <summary>
        /// Using the provided usage scopes and parameters, shows a window asking user to grant the application access
        /// to their account. Returns the authorization code if the user grants access to this app.
        /// </summary>
        /// <param name="scopes">The scopes that the app has requested.</param>
        /// <param name="extraParams">Any extra parameters that are needed for authorization.</param>
        /// <returns>The authorization code for getting the initial access token, or null on cancel or error.</returns>
        protected string RequestAuthorization(List <string> scopes, NameValueCollection extraParams)
        {
            //Represents the collection that will contain all parameters of the request url. Start by adding the
            //required stuff to it.
            NameValueCollection parameters = new NameValueCollection()
            {
                { "response_type", "code" },
                { "client_id", ClientId },
                { "redirect_uri", RedirectUri }
            };

            //Add scopes if any are provided.
            if (scopes != null && scopes.Count > 0)
            {
                string scopesStr = "";
                //Add the scope parameter and then the list of scopes, separated by spaces.
                for (int i = 0; i < scopes.Count; i++)
                {
                    if (i != scopes.Count - 1)
                    {
                        scopesStr += scopes[i] + " ";
                    }
                    else
                    {
                        scopesStr += scopes[i];
                    }
                }

                parameters["scope"] = scopesStr;
            }
            //Add any extra parameters.
            if (extraParams != null && extraParams.Count > 0)
            {
                parameters.Add(extraParams);
            }

            //Create the authorization request url.
            var requestUrl = ConstructUri(AuthorizationEndpoint, parameters).ToString();

            //Create the authorization window that will prompt the user to login to their account. The user will then
            //grant or deny access to this app.
            var loginWindow = new AuthorizeForm();

            loginWindow.Text = "Login To " + ProviderName;
            loginWindow.RequestAuthorization(requestUrl, AuthorizationFormCloseParams);
            //Show the window as a dialog to block application use until the user gives access to this app, denies
            //access to this app, or chooses to just close the window (also denying access to this app).
            loginWindow.ShowDialog();

            //Check if authorization was cancelled by closing the window early.
            if (loginWindow.WasAuthorizationCancelled)
            {
                LastError        = OAuthClientResult.UserCancelled;
                LastErrorMessage = "Authorization process cancelled by closing login window.";
                return(null);
            }
            //The redirect url should not be empty.
            if (string.IsNullOrEmpty(loginWindow.AuthorizationRedirectUrl))
            {
                LastError        = OAuthClientResult.UnexpectedError;
                LastErrorMessage = "Authorization url is null or empty.";
                return(null);
            }

            //Success.
            LastError        = OAuthClientResult.Success;
            LastErrorMessage = "Operation completed successfully.";

            //Return the authorization code. Subclasses will handle this value, including if it is null or empty.
            return(loginWindow.AuthorizationRedirectUrl);
        }
示例#43
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases        = new List <ReleaseInfo>();
            var queryUrl        = SearchUrl;
            var queryCollection = new NameValueCollection();
            var cats            = MapTorznabCapsToTrackers(query);
            var tags            = string.Empty;
            var catGroups       = new List <string>();

            foreach (var cat in cats)
            {
                //"cat[]=7&tags=x264"
                var cSplit = cat.Split('&');
                if (cSplit.Length > 0)
                {
                    var gsplit = cSplit[0].Split('=');
                    if (gsplit.Length > 1)
                    {
                        catGroups.Add(gsplit[1]);
                    }
                }

                if (cSplit.Length > 1)
                {
                    var gsplit = cSplit[1].Split('=');
                    if (gsplit.Length > 1)
                    {
                        if (tags != string.Empty)
                        {
                            tags += ",";
                        }
                        tags += gsplit[1];
                    }
                }
            }

            if (catGroups.Distinct().Count() == 1)
            {
                queryCollection.Add("cat[]", catGroups.First());
            }

            if (!string.IsNullOrWhiteSpace(query.GetQueryString()))
            {
                queryCollection.Add("st", "1");
                queryCollection.Add("search", query.GetQueryString());
            }

            // Do not include too many tags as it'll mess with their servers.
            if (tags.Split(',').Length < 7)
            {
                queryCollection.Add("tags", tags);
                if (!string.IsNullOrWhiteSpace(tags))
                {
                    // if tags are specified match any
                    queryCollection.Add("tf", "any");
                }
                else
                {
                    // if no tags are specified match all, with any we get random results
                    queryCollection.Add("tf", "all");
                }
            }

            if (queryCollection.Count > 0)
            {
                queryUrl += "?" + queryCollection.GetQueryString();
            }

            var response = await RequestStringWithCookiesAndRetry(queryUrl);

            if (response.IsRedirect)
            {
                await ApplyConfiguration(null);

                response = await RequestStringWithCookiesAndRetry(queryUrl);
            }

            try
            {
                CQ  dom  = response.Content;
                var rows = dom["table > tbody > tr.browse"];
                foreach (var row in rows)
                {
                    CQ  qRow    = row.Cq();
                    var release = new ReleaseInfo();

                    release.MinimumRatio    = 1;
                    release.MinimumSeedTime = 172800;

                    var qLink = row.ChildElements.ElementAt(1).Cq().Find("a").First();
                    release.Title = qLink.Text().Trim();
                    if (qLink.Find("span").Count() == 1 && release.Title.StartsWith("NEW! |"))
                    {
                        release.Title = release.Title.Substring(6).Trim();
                    }

                    release.Comments = new Uri(SiteLink + qLink.Attr("href"));
                    release.Guid     = release.Comments;

                    var qDownload = row.ChildElements.ElementAt(2).Cq().Find("a").First();
                    release.Link = new Uri(SiteLink + qDownload.Attr("href"));

                    var dateStr = Regex.Replace(row.ChildElements.ElementAt(5).InnerHTML, @"\<br[\s]{0,1}[\/]{0,1}\>", " ");
                    release.PublishDate = DateTimeUtil.FromTimeAgo(dateStr);

                    var sizeStr = row.ChildElements.ElementAt(7).Cq().Text();
                    release.Size = ReleaseInfo.GetBytes(sizeStr);

                    release.Seeders = ParseUtil.CoerceInt(row.ChildElements.ElementAt(9).InnerText);
                    release.Peers   = ParseUtil.CoerceInt(row.ChildElements.ElementAt(10).InnerText) + release.Seeders;

                    var cat = row.ChildElements.ElementAt(0).ChildElements.ElementAt(0).GetAttribute("href").Replace("browse.php?", string.Empty);
                    release.Category = MapTrackerCatToNewznab(cat);

                    var files = qRow.Find("td:nth-child(4)").Text();
                    release.Files = ParseUtil.CoerceInt(files);

                    var grabs = qRow.Find("td:nth-child(9)").Text();
                    release.Grabs = ParseUtil.CoerceInt(grabs);

                    release.DownloadVolumeFactor = 0; // ratioless
                    release.UploadVolumeFactor   = 1;

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(response.Content, ex);
            }
            return(releases);
        }
示例#44
0
        public async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            List <ReleaseInfo> releases = new List <ReleaseInfo>();

            var searchString    = query.GetQueryString();
            var searchUrl       = SearchUrl;
            var queryCollection = new NameValueCollection();

            queryCollection.Add("incldead", "1");
            queryCollection.Add("xtype", "0");
            queryCollection.Add("stype", "0");

            if (query.ImdbID != null)
            {
                queryCollection.Add("search", query.ImdbID);
            }
            else if (!string.IsNullOrWhiteSpace(searchString))
            {
                queryCollection.Add("search", searchString);
            }

            foreach (var cat in MapTorznabCapsToTrackers(query))
            {
                queryCollection.Add("c" + cat, "1");
            }

            searchUrl += "?" + queryCollection.GetQueryString();

            var results = await RequestStringWithCookiesAndRetry(searchUrl);

            try
            {
                CQ dom = results.Content;

                var sideWideFreeLeech = false;
                if (dom.Find("td > b > font[color=\"white\"]:contains(Free Leech)").Length >= 1)
                {
                    sideWideFreeLeech = true;
                }

                var rows = dom["table > tbody > tr[height=36]"];
                foreach (var row in rows)
                {
                    var release = new ReleaseInfo();
                    release.MinimumRatio    = 1;
                    release.MinimumSeedTime = 7 * 24 * 60 * 60;

                    var qRow          = row.Cq();
                    var qCatLink      = qRow.Find("a[href^=?cat]").First();
                    var qDetailsLink  = qRow.Find("a[href^=details.php]").First();
                    var qSeeders      = qRow.Find("td:eq(8)");
                    var qLeechers     = qRow.Find("td:eq(9)");
                    var qDownloadLink = qRow.Find("a[href^=\"download.php\"]").First();
                    var qImdbLink     = qRow.Find("a[href^=/redir.php?url=http://www.imdb.com]");
                    var qSize         = qRow.Find("td:eq(6)");

                    var catStr = qCatLink.Attr("href").Split('=')[1];
                    release.Category = MapTrackerCatToNewznab(catStr);

                    release.Link     = new Uri(SiteLink + qDownloadLink.Attr("href"));
                    release.Title    = qDetailsLink.Text().Trim();
                    release.Comments = new Uri(SiteLink + qDetailsLink.Attr("href"));
                    release.Guid     = release.Link;

                    var sizeStr = qSize.Text();
                    release.Size = ReleaseInfo.GetBytes(sizeStr);

                    if (qImdbLink.Length == 1)
                    {
                        var ImdbId = qImdbLink.Attr("href").Split('/').Last().Substring(2);
                        release.Imdb = ParseUtil.CoerceLong(ImdbId);
                    }

                    release.Seeders = ParseUtil.CoerceInt(qSeeders.Text());
                    release.Peers   = ParseUtil.CoerceInt(qLeechers.Text()) + release.Seeders;

                    var files = qRow.Find("td:nth-child(3)").Text();
                    release.Files = ParseUtil.CoerceInt(files);

                    var grabs = qRow.Find("td:nth-child(8)").Get(0).FirstChild.ToString();
                    release.Grabs = ParseUtil.CoerceInt(grabs);

                    if (sideWideFreeLeech || qRow.Find("font[color=\"red\"]:contains(FREE)").Length >= 1)
                    {
                        release.DownloadVolumeFactor = 0;
                    }
                    else
                    {
                        release.DownloadVolumeFactor = 1;
                    }
                    release.UploadVolumeFactor = 1;

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results.Content, ex);
            }

            return(releases);
        }
        /// <summary>
        /// Validate Instant Transaction Notification Callback
        /// </summary>
        /// <param name="form">List of parameters</param>
        /// <param name="order">Order</param>
        /// <returns>true if there are no errors; otherwise false</returns>
        protected bool ValidateITN(IFormCollection form, out Order order)
        {
            order = null;

            //validate order
            if (!Guid.TryParse(form["m_payment_id"], out Guid orderGuid))
            {
                return(false);
            }

            order = _orderService.GetOrderByGuid(orderGuid);
            if (order == null)
            {
                _logger.Error($"PayFast ITN error: Order with guid {orderGuid} is not found");
                return(false);
            }

            //validate merchant ID
            if (!form["merchant_id"].ToString().Equals(_payFastPaymentSettings.MerchantId, StringComparison.InvariantCulture))
            {
                _logger.Error("PayFast ITN error: Merchant ID mismatch");
                return(false);
            }

            //validate IP address
            if (!IPAddress.TryParse(_webHelper.GetCurrentIpAddress(), out IPAddress ipAddress))
            {
                _logger.Error("PayFast ITN error: IP address is empty");
                return(false);
            }

            var validIPs = new[]
            {
                "www.payfast.co.za",
                "sandbox.payfast.co.za",
                "w1w.payfast.co.za",
                "w2w.payfast.co.za"
            }.SelectMany(Dns.GetHostAddresses);

            if (!validIPs.Contains(ipAddress))
            {
                _logger.Error($"PayFast ITN error: IP address {ipAddress} is not valid");
                return(false);
            }

            //validate data
            var postData = new NameValueCollection();

            foreach (var pair in form)
            {
                if (!pair.Key.Equals("signature", StringComparison.InvariantCultureIgnoreCase))
                {
                    postData.Add(pair.Key, pair.Value);
                }
            }

            try
            {
                var site = $"{(_payFastPaymentSettings.UseSandbox ? "https://sandbox.payfast.co.za" : "https://www.payfast.co.za")}/eng/query/validate";

                using (var webClient = new WebClient())
                {
                    var response = webClient.UploadValues(site, postData);

                    // Get the response and replace the line breaks with spaces
                    var result = Encoding.ASCII.GetString(response);

                    if (!result.StartsWith("VALID", StringComparison.InvariantCulture))
                    {
                        _logger.Error("PayFast ITN error: passed data is not valid");
                        return(false);
                    }
                }
            }
            catch (WebException)
            {
                _logger.Error("PayFast ITN error: passed data is not valid");
                return(false);
            }

            //validate payment status
            if (!form["payment_status"].ToString().Equals("COMPLETE", StringComparison.InvariantCulture))
            {
                _logger.Error($"PayFast ITN error: order #{order.Id} is {form["payment_status"]}");
                return(false);
            }

            return(true);
        }
示例#46
0
        public void Test01()
        {
            IntlStrings         intl;
            NameValueCollection nvc;

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

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

            int cnt = 0;            // Count

            // [] initialize IntStrings
            intl = new IntlStrings();


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

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

            //
            //  [] on empty collection
            //
            if (nvc.HasKeys())
            {
                Assert.False(true, "Error, HasKeys returned true after default ctor");
            }


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

            if (!nvc.HasKeys())
            {
                Assert.False(true, string.Format("Error, returned false for collection with {0} items", nvc.Count));
            }


            //
            // [] Add Intl strings and HasKeys()
            //
            int len = values.Length;

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

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

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

            if (!nvc.HasKeys())
            {
                Assert.False(true, string.Format("Error, returned false for collection with {0} items", nvc.Count));
            }

            //
            //  [] Add item with null-key and call HasKeys()
            //
            nvc.Clear();
            cnt = nvc.Count;
            for (int i = 0; i < values.Length; i++)
            {
                nvc.Add(null, values[i]);
            }
            if (nvc.Count != 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 1));
            }

            if (nvc.HasKeys())
            {
                Assert.False(true, "Error, returned true for collection null-key");
            }
        }
        /// <summary>
        /// GitHub Auth API
        /// </summary>
        /// <remarks>
        /// GET: /Auth/GitHub
        /// </remarks>
        /// <returns></returns>
        public ActionResult GitHub()
        {
            var code = Request.Params["code"];

            if (!string.IsNullOrWhiteSpace(code))
            {
                try
                {
                    string responseData = null;
                    using (var client = new WebClient())
                    {
                        var nameValuePairs = new NameValueCollection();
                        nameValuePairs.Add("code", code);
                        nameValuePairs.Add("client_secret", ServerConfiguration.GitHubSecret);
                        nameValuePairs.Add("client_id", ServerConfiguration.GitHubClientId);
                        client.Headers.Add("content-type", "application/x-www-form-urlencoded");
                        var response = client.UploadValues(GitHubAuthorizationPost, nameValuePairs);
                        responseData = client.Encoding.GetString(response);
                    }

                    if (!string.IsNullOrWhiteSpace(responseData))
                    {
                        var    gitHubResponse = GitHubResponse.Parse(responseData);
                        string profileJson    = null;
                        using (var client = new WebClient())
                        {
                            profileJson = client.DownloadString(string.Format(GitHubApi, "user", gitHubResponse.AccessToken));
                        }

                        if (!string.IsNullOrWhiteSpace(profileJson))
                        {
                            var serializer = new JavaScriptSerializer();

                            var profile = serializer.Deserialize <GitHubProfile>(profileJson);
                            if (this.Login(profile)) //New User
                            {
                                var source     = new DomainSource();
                                var user       = source.GetUserByNameIdentifier(Application.Default.Identifier, string.Format("github{0}", profile.Id));
                                var preference = profile.Convert();
                                preference.Application = Application.Default;
                                preference.User        = user.Convert();
                                var core = new UserCore();
                                core.Save(preference);
                                var profilePage = ((IConvert <ProfilePage>)profile).Convert();
                                profilePage.ApplicationIdentifier = Application.Default.Identifier;
                                profilePage.OwnerIdentifier       = user.Id;
                                profilePage.GitCode        = code;
                                profilePage.GitAccessToken = gitHubResponse.AccessToken;
                                core.Save(profilePage);
                                return(this.RedirectToAction("Welcome", "Home"));
                            }
                            else
                            {
                                return(this.RedirectToAction("Index", "Profile", new { username = profile.Login }));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Log(ex, Abc.Services.Contracts.EventTypes.Critical, (int)ServiceFault.Unknown);
                }
            }

            return(this.RedirectToAction("Index", "Auth"));
        }
        public string this[string FieldName]
        {
            get
            {
                switch (FieldName)
                {
                case "ID":
                    return(_id.ToString());

                case "AccountMonth":
                    return(_accountmonth.ToString());

                case "OrganizeCity":
                    return(_organizecity.ToString());

                case "Client":
                    return(_client.ToString());

                case "ApproveFlag":
                    return(_approveflag.ToString());

                case "InsertTime":
                    return(_inserttime.ToString());

                case "InsertStaff":
                    return(_insertstaff.ToString());

                case "UpdateTime":
                    return(_updatetime.ToString());

                case "UpdateStaff":
                    return(_updatestaff.ToString());

                default:
                    if (_extpropertys == null)
                    {
                        return("");
                    }
                    else
                    {
                        return(_extpropertys[FieldName]);
                    }
                }
            }
            set
            {
                switch (FieldName)
                {
                case "ID":
                    int.TryParse(value, out _id);
                    break;

                case "AccountMonth":
                    int.TryParse(value, out _accountmonth);
                    break;

                case "OrganizeCity":
                    int.TryParse(value, out _organizecity);
                    break;

                case "Client":
                    int.TryParse(value, out _client);
                    break;

                case "ApproveFlag":
                    int.TryParse(value, out _approveflag);
                    break;

                case "InsertTime":
                    DateTime.TryParse(value, out _inserttime);
                    break;

                case "InsertStaff":
                    int.TryParse(value, out _insertstaff);
                    break;

                case "UpdateTime":
                    DateTime.TryParse(value, out _updatetime);
                    break;

                case "UpdateStaff":
                    int.TryParse(value, out _updatestaff);
                    break;

                default:
                    if (_extpropertys == null)
                    {
                        _extpropertys = new NameValueCollection();
                    }
                    if (_extpropertys[FieldName] == null)
                    {
                        _extpropertys.Add(FieldName, value);
                    }
                    else
                    {
                        _extpropertys[FieldName] = value;
                    }
                    break;
                }
            }
        }
        public static List <string> GetBeforeAndAfterLinks(Uri url, IReadOnlyCollection <TEntity> content, bool isDescending, bool hasMore, Func <TEntity, string> pagePropertyAccessor)
        {
            if (pagePropertyAccessor == null && typeof(IIdentity).IsAssignableFrom(typeof(TEntity)))
            {
                pagePropertyAccessor = e => ((IIdentity)e).Id;
            }

            if (pagePropertyAccessor == null)
            {
                return(new List <string>());
            }

            string firstId = content.Any() ? pagePropertyAccessor(!isDescending ? content.First() : content.Last()) : String.Empty;
            string lastId  = content.Any() ? pagePropertyAccessor(!isDescending ? content.Last() : content.First()) : String.Empty;

            bool hasBefore = false;
            bool hasAfter  = false;

            var previousParameters = url.ParseQueryString();

            if (previousParameters["before"] != null)
            {
                hasBefore = true;
            }
            previousParameters.Remove("before");
            if (previousParameters["after"] != null)
            {
                hasAfter = true;
            }
            previousParameters.Remove("after");
            var nextParameters = new NameValueCollection(previousParameters);

            previousParameters.Add("before", firstId);
            nextParameters.Add("after", lastId);

            bool includePrevious = hasBefore ? hasMore : true;
            bool includeNext     = !hasBefore ? hasMore : true;

            if (hasBefore && !content.Any())
            {
                // are we currently before the first page?
                includePrevious = false;
                includeNext     = true;
                nextParameters.Remove("after");
            }
            else if (!hasBefore && !hasAfter)
            {
                // are we at the first page?
                includePrevious = false;
            }

            string baseUrl = url.ToString();

            if (!String.IsNullOrEmpty(url.Query))
            {
                baseUrl = baseUrl.Replace(url.Query, "");
            }

            string previousLink = String.Format("<{0}?{1}>; rel=\"previous\"", baseUrl, previousParameters.ToQueryString());
            string nextLink     = String.Format("<{0}?{1}>; rel=\"next\"", baseUrl, nextParameters.ToQueryString());

            var links = new List <string>();

            if (includePrevious)
            {
                links.Add(previousLink);
            }
            if (includeNext)
            {
                links.Add(nextLink);
            }

            return(links);
        }
示例#50
0
        public static string GetSchedule(string idgr, string idgrid) // дописать, чтобы получать расписание любой группы, пока что для 3/42 (сделаю, наверное)
        {
            string url = "https://www.isuct.ru/system/ajax";         // туда запрос

            using (var webClient = new WebClient())
            {
                var pars = new NameValueCollection();
                pars.Add("type", "currentstudentsgroups");
                pars.Add("idgr", idgr);
                pars.Add("idaud", "");
                pars.Add("idprep", "");
                pars.Add("idprepid", "");
                pars.Add("idaudid", "");
                pars.Add("idgrid", idgrid);
                pars.Add("form_build_id", "form-WnOwNmk3-tviflUmbW_vrncjxwu82eR14Ky0bydSNa0");
                pars.Add("form_id", "studschedule_form");
                //не раскрывать - много текста
                #region
                pars.Add("_triggering_element_name", "op");
                pars.Add("_triggering_element_value", "Показать расписание");
                pars.Add("ajax_html_ids[]", "visually-impaired-controls");
                pars.Add("ajax_html_ids[]", "id_vi_panel");
                pars.Add("ajax_html_ids[]", "xvi-images");
                pars.Add("ajax_html_ids[]", "vi_widget_link-offs");
                pars.Add("ajax_html_ids[]", "vi-sans-serif");
                pars.Add("ajax_html_ids[]", "vi-serif");
                pars.Add("ajax_html_ids[]", "vi-spacing-small");
                pars.Add("ajax_html_ids[]", "vi-spacing-normal");
                pars.Add("ajax_html_ids[]", "vi-spacing-big");
                pars.Add("ajax_html_ids[]", "vi-height-small");
                pars.Add("ajax_html_ids[]", "vi-height-normal");
                pars.Add("ajax_html_ids[]", "vi-height-big");
                pars.Add("ajax_html_ids[]", "vi-color1");
                pars.Add("ajax_html_ids[]", "vi-color2");
                pars.Add("ajax_html_ids[]", "vi-color3");
                pars.Add("ajax_html_ids[]", "vi-color4");
                pars.Add("ajax_html_ids[]", "vi-color5");
                pars.Add("ajax_html_ids[]", "header_wrapper");
                pars.Add("ajax_html_ids[]", "top");
                pars.Add("ajax_html_ids[]", "topinfo");
                pars.Add("ajax_html_ids[]", "topinfo-left");
                pars.Add("ajax_html_ids[]", "topinfo-center");
                pars.Add("ajax_html_ids[]", "bt_widget-vi-on");
                pars.Add("ajax_html_ids[]", "vi_widget_link-on");
                pars.Add("ajax_html_ids[]", "Copy");
                pars.Add("ajax_html_ids[]", "bt_widget-vi-off");
                pars.Add("ajax_html_ids[]", "vi_widget_link-off");
                pars.Add("ajax_html_ids[]", "topinfo-right");
                pars.Add("ajax_html_ids[]", "block-locale-language");
                pars.Add("ajax_html_ids[]", "block-search-form");
                pars.Add("ajax_html_ids[]", "search-block-form");
                pars.Add("ajax_html_ids[]", "edit-search-block-form--2");
                pars.Add("ajax_html_ids[]", "ui-id-1");
                pars.Add("ajax_html_ids[]", "edit-actions");
                pars.Add("ajax_html_ids[]", "edit-submit--2");
                pars.Add("ajax_html_ids[]", "header");
                pars.Add("ajax_html_ids[]", "logo");
                pars.Add("ajax_html_ids[]", "site-title");
                pars.Add("ajax_html_ids[]", "site-description");
                pars.Add("ajax_html_ids[]", "cbp-hrmenu");
                pars.Add("ajax_html_ids[]", "block-multiblock-2");
                pars.Add("ajax_html_ids[]", "block-multiblock-3");
                pars.Add("ajax_html_ids[]", "block-multiblock-4");
                pars.Add("ajax_html_ids[]", "block-block-39");
                pars.Add("ajax_html_ids[]", "block-multiblock-5");
                pars.Add("ajax_html_ids[]", "block-multiblock-9");
                pars.Add("ajax_html_ids[]", "block-block-37");
                pars.Add("ajax_html_ids[]", "block-multiblock-7");
                pars.Add("ajax_html_ids[]", "block-block-38");
                pars.Add("ajax_html_ids[]", "block-multiblock-8");
                pars.Add("ajax_html_ids[]", "block-block-16");
                pars.Add("ajax_html_ids[]", "main-menu");
                pars.Add("ajax_html_ids[]", "top-area");
                pars.Add("ajax_html_ids[]", "page-wrap");
                pars.Add("ajax_html_ids[]", "container");
                pars.Add("ajax_html_ids[]", "content");
                pars.Add("ajax_html_ids[]", "breadcrumbs");
                pars.Add("ajax_html_ids[]", "post-content");
                pars.Add("ajax_html_ids[]", "block-system-main");
                pars.Add("ajax_html_ids[]", "studschedule-form");
                pars.Add("ajax_html_ids[]", "edit-type");
                pars.Add("ajax_html_ids[]", "edit-type-auditorium");
                pars.Add("ajax_html_ids[]", "edit-type-prepod");
                pars.Add("ajax_html_ids[]", "edit-type-currentstudentsgroups");
                pars.Add("ajax_html_ids[]", "edit-idgr");
                pars.Add("ajax_html_ids[]", "edit-idgr-autocomplete");
                pars.Add("ajax_html_ids[]", "edit-idgr-autocomplete-aria-live");
                pars.Add("ajax_html_ids[]", "edit-idaud");
                pars.Add("ajax_html_ids[]", "edit-idaud-autocomplete");
                pars.Add("ajax_html_ids[]", "edit-idaud-autocomplete-aria-live");
                pars.Add("ajax_html_ids[]", "edit-idprep");
                pars.Add("ajax_html_ids[]", "edit-idprep-autocomplete");
                pars.Add("ajax_html_ids[]", "edit-idprep-autocomplete-aria-live");
                pars.Add("ajax_html_ids[]", "idprepid");
                pars.Add("ajax_html_ids[]", "idaudid");
                pars.Add("ajax_html_ids[]", "idgrid");
                pars.Add("ajax_html_ids[]", "edit-submit");
                pars.Add("ajax_html_ids[]", "form-ajax-node-content");
                pars.Add("ajax_html_ids[]", "undercontent");
                pars.Add("ajax_html_ids[]", "undercontentinfo");
                pars.Add("ajax_html_ids[]", "block-block-79");
                pars.Add("ajax_html_ids[]", "footer");
                pars.Add("ajax_html_ids[]", "footer-area");
                pars.Add("ajax_html_ids[]", "block-block-21");
                pars.Add("ajax_html_ids[]", "block-block-22");
                pars.Add("ajax_html_ids[]", "block-block-27");
                pars.Add("ajax_html_ids[]", "block-block-26");
                pars.Add("ajax_html_ids[]", "copyright");
                pars.Add("ajax_html_ids[]", "backtotop");
                pars.Add("ajax_html_ids[]", "popup-active-overlay");
                pars.Add("ajax_html_ids[]", "cboxOverlay");
                pars.Add("ajax_html_ids[]", "colorbox");
                pars.Add("ajax_html_ids[]", "cboxWrapper");
                pars.Add("ajax_html_ids[]", "cboxTopLeft");
                pars.Add("ajax_html_ids[]", "cboxTopCenter");
                pars.Add("ajax_html_ids[]", "cboxTopRight");
                pars.Add("ajax_html_ids[]", "cboxMiddleLeft");
                pars.Add("ajax_html_ids[]", "cboxContent");
                pars.Add("ajax_html_ids[]", "cboxTitle");
                pars.Add("ajax_html_ids[]", "cboxCurrent");
                pars.Add("ajax_html_ids[]", "cboxPrevious");
                pars.Add("ajax_html_ids[]", "cboxNext");
                pars.Add("ajax_html_ids[]", "cboxSlideshow");
                pars.Add("ajax_html_ids[]", "cboxLoadingOverlay");
                pars.Add("ajax_html_ids[]", "cboxLoadingGraphic");
                pars.Add("ajax_html_ids[]", "cboxMiddleRight");
                pars.Add("ajax_html_ids[]", "cboxBottomLeft");
                pars.Add("ajax_html_ids[]", "cboxBottomCenter");
                pars.Add("ajax_html_ids[]", "cboxBottomRight");
                pars.Add("ajax_page_state[theme]", "isuct");
                pars.Add("ajax_page_state[theme_token]", "mEeQE8PBT5VXCwbL0Nk2K0dN5tE1EVxT8_n_C9P9OFc");
                pars.Add("ajax_page_state[css][0]", "1");
                pars.Add("ajax_page_state[css][1]", "1");
                pars.Add("ajax_page_state[css][2]", "1");
                pars.Add("ajax_page_state[css][modules/system/system.base.css]", "1");
                pars.Add("ajax_page_state[css][modules/system/system.menus.css]", "1");
                pars.Add("ajax_page_state[css][modules/system/system.messages.css]", "1");
                pars.Add("ajax_page_state[css][modules/system/system.theme.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.core.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.theme.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.menu.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.autocomplete.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.accordion.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.button.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.resizable.css]", "1");
                pars.Add("ajax_page_state[css][misc/ui/jquery.ui.dialog.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/audtodayschedule/css/schedule.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/calendar/css/calendar_multiday.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/date/date_api/date.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/date/date_popup/themes/datepicker.1.7.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/date/date_repeat_field/date_repeat_field.css]", "1");
                pars.Add("jax_page_state[css][modules/field/theme/field.css]", "1");
                pars.Add("ajax_page_state[css][modules/node/node.css]", "1");
                pars.Add("ajax_page_state[css][modules/node/node.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/ppslist/css/ppslist.css]", "1");
                pars.Add("ajax_page_state[css][modules/search/search.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/studrating/css/styles.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/studrating/css/jquery.dataTables.min.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/studschedule/css/schedule.css]", "1");
                pars.Add("ajax_page_state[css][modules/user/user.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/visuallyimpaired/css/styles.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/views/css/views.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/back_to_top/css/back_to_top.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/ckeditor/css/ckeditor.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/cctags/cctags.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/libraries/colorbox/example2/colorbox.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/ctools/css/ctools.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/panels/css/panels.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/popup/popup.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/textsize/textsize.css]", "1");
                pars.Add("ajax_page_state[css][modules/locale/locale.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/custom_search/custom_search.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/flexslider/assets/css/flexslider_img.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/libraries/flexslider/flexslider.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/search_autocomplete/css/themes/basic-green.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/search_autocomplete/css/themes/minimal.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/search_autocomplete/css/themes/user-blue.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/modules/eu_cookie_compliance/css/eu_cookie_compliance.css]", "1");
                pars.Add("ajax_page_state[css][https://www.isuct.ru/sites/all/modules/storefront_cps/style.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/themes/isuct/css/font-awesome.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/themes/isuct/css/style.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/themes/isuct/css/media.css]", "1");
                pars.Add("ajax_page_state[css][sites/all/themes/isuct/css/component.css]", "1");
                pars.Add("ajax_page_state[js][0]", "1");
                pars.Add("ajax_page_state[js][1]", "1");
                pars.Add("ajax_page_state[js][2]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/flexslider/assets/js/flexslider.load.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/eu_cookie_compliance/js/eu_cookie_compliance.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/jquery/1.8/jquery.min.js]", "1");
                pars.Add("ajax_page_state[js][misc/jquery-extend-3.4.0.js]", "1");
                pars.Add("ajax_page_state[js][misc/jquery.once.js]", "1");
                pars.Add("ajax_page_state[js][misc/drupal.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.core.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.widget.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.effect.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/eu_cookie_compliance/js/jquery.cookie-1.4.1.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/misc/jquery.form.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.position.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.menu.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.autocomplete.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.accordion.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.button.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.mouse.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.draggable.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.resizable.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.dialog.min.js]", "1");
                pars.Add("ajax_page_state[js][misc/ajax.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jquery_update/js/jquery_update.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/admin_menu/admin_devel/admin_devel.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/audtodayschedule/js/my.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/ppslist/js/my.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/studrating/js/my.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/studrating/js/jquery.dataTables.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/studschedule/js/my.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/visuallyimpaired/js/js.for.the.visually.impaired.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/visuallyimpaired/js/js.cookie.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/webform_steps/webform_steps.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/back_to_top/js/back_to_top.js]", "1");
                pars.Add("ajax_page_state[js][public://languages/ru_rJV0hRSXXwygvsLzqDEmn6qNlLb9lZOMo7QpRnIbSyU.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/autocomplete_post/autocomplete_post.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/libraries/colorbox/jquery.colorbox-min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/colorbox/js/colorbox.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/colorbox/js/colorbox_load.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/colorbox/js/colorbox_inline.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/iframe/iframe.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/jcaption/jcaption.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/popup/popup.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/libraries/jstorage/jstorage.min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/textsize/jquery.textsize.js]", "1");
                pars.Add("ajax_page_state[js][misc/jquery.cookie.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/custom_search/js/custom_search.js]", "1");
                pars.Add("ajax_page_state[js][misc/autocomplete.js]", "1");
                pars.Add("ajax_page_state[js][misc/progress.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/themes/fix/js/colorbox-fix.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/libraries/easing/jquery.easing.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/libraries/flexslider/jquery.flexslider-min.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/modules/search_autocomplete/js/jquery.autocomplete.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/themes/isuct/js/custom.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/themes/isuct/js/cbpHorizontalMenu.js]", "1");
                pars.Add("ajax_page_state[js][sites/all/themes/isuct/js/modernizr.custom.js]", "1");
                pars.Add("ajax_page_state[jquery_version]", "1.8");

                #endregion
                var    response = webClient.UploadValues(url, pars);
                string schedule = System.Text.Encoding.UTF8.GetString(response);

                FileStream   fileWithSchedule = new FileStream("./TimeTabel.json", FileMode.OpenOrCreate); // запишем в файл
                StreamWriter w = new StreamWriter(fileWithSchedule);
                fileWithSchedule.Write(response);
                fileWithSchedule.Close(); // оказывается потоки нужно закрывать, иначе рискуем получить исключение, что файл уже используется
                return(schedule);
            }
        }
示例#51
0
        /// <summary>
        /// Método que hace una consulta al servicio de gobierno y retorna el tipo de Folio
        /// </summary>
        /// <param name="oCuestionario">La peticion que llega</param>
        /// <param name="sToken">El token para gobierno</param>
        /// <param name="sURL">La URL del servicio de gobierno</param>
        /// <returns>Un objeto tipo encuesta</returns>
        public EncuestaDTO TipoFolio(CuestionarioModel oCuestionario, string sToken, string sURL)
        {
            var                sParametros   = new NameValueCollection();
            WebClient          oConsumo      = new WebClient();
            clsTblcodigopostal oCodigoPostal = new clsTblcodigopostal();
            clsTblcatlada      oLada         = new clsTblcatlada();
            EncuestaDTO        encuestaDTO   = new EncuestaDTO();

            AccesoBusiness = new AccesoBusiness();

            try
            {
                if (oCuestionario.sError == null)
                {
                    oCuestionario.sError = "";
                }

                sParametros.Add("unidad_notificante", "MEDITOC");

                foreach (var item in oCuestionario.lstPreguntas)
                {
                    if (item.sNombre != null)
                    {
                        if (item.sParam == "cp")
                        {
                            encuestaDTO.sCP = item.sNombre;
                            oCodigoPostal.ValidarCP(item.sNombre);
                        }

                        if (item.sParam == "telefono")
                        {
                            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["bActivarGeolocalizacion"]))
                            {
                                oLada.ValidarLada(item.sNombre);
                            }

                            int iIdAcceso = AccesoBusiness.UserExist(item.sNombre);

                            if (iIdAcceso == 0)
                            {
                                AccesoDTO accesoDTO = new AccesoDTO
                                {
                                    sTelefono       = item.sNombre,
                                    dtFechaCreacion = DateTime.Now
                                };

                                AccesoBusiness.saveAcceso(accesoDTO);
                            }

                            encuestaDTO.iIdAcceso = iIdAcceso;
                        }

                        sParametros.Add(item.sParam, item.sNombre);
                    }
                    else
                    {
                        sParametros.Add(item.sParam, item.bPrecionado.ToString());
                    }
                }

                oConsumo.Headers.Set("token", sToken);

                var     Json = oConsumo.UploadValues(sURL, "POST", sParametros);
                dynamic m    = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(Json));
                encuestaDTO.sFolio     = m.data.FolioApp;
                encuestaDTO.sTipoFolio = m.data.FolioApp == null ? "Tipo 1" : "Tipo 2";//Comprobamos que tipo de folio es
            }
            catch (Exception e)
            {
                throw e;
            }

            return(encuestaDTO);
        }
示例#52
0
    public String UpdatePwd(String SPID, String accessToken, String password, String nPassword)
    {
        StringBuilder strMsg      = new StringBuilder();
        StringBuilder ResponseMsg = new StringBuilder();

        Result = ErrorDefinition.IError_Result_UnknowError_Code;
        ErrMsg = ErrorDefinition.IError_Result_UnknowError_Msg;
        strMsg.AppendFormat("接收参数 SPID:{0},accessToken:{1},password:{2},nPassword:{3}\r\n", SPID, accessToken, password, nPassword);

        #region 数据校验
        if (CommonUtility.IsEmpty(SPID))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "995");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "SPID不能为空!");
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }

        if (CommonUtility.IsEmpty(accessToken) && CommonUtility.IsEmpty(CustID))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "996");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "accessToken和CustID不能为空!");
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }


        if (CommonUtility.IsEmpty(password))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "997");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "password不能为空!");
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }

        if (CommonUtility.IsEmpty(nPassword))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "998");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "nPassword不能为空!");
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }



        #endregion

        String appId       = String.Empty;
        String appSecret   = String.Empty;
        String version     = String.Empty;
        String clientType  = String.Empty;
        String clientIp    = String.Empty;
        String clientAgent = String.Empty;

        #region  获取综合平台接入参数

        try
        {
            appId       = UDBConstDefinition.DefaultInstance.UnifyPlatformAppId;
            appSecret   = UDBConstDefinition.DefaultInstance.UnifyPlatformAppSecret;
            version     = UDBConstDefinition.DefaultInstance.UnifyPlatformVersion;
            clientType  = UDBConstDefinition.DefaultInstance.UnifyPlatformClientType;
            clientIp    = HttpContext.Current.Request.UserHostAddress;
            clientAgent = HttpContext.Current.Request.UserAgent;
            strMsg.AppendFormat("获取综合平台接入参数:appId:{0},appSecret:{1},version:{2},clientType:{3},clientIp:{4},clientAgent:{5}\r\n", appId, appSecret, version, clientType, clientIp, clientAgent);
        }
        catch (Exception e)
        {
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "998");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "获取综合平台参数异常:" + e.ToString());
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }
        #endregion
        String jsonResult = String.Empty;
        string sign       = String.Empty;
        try
        {
            #region

            if (CommonUtility.IsEmpty(accessToken) && !CommonUtility.IsEmpty(CustID))
            {
                Result = CIP2BizRules.FetchAccessTokenFromCustID(CustID, out accessToken, out ErrMsg);
            }

            if (Result != 0 || CommonUtility.IsEmpty(accessToken))
            {
                ResponseMsg.Length = 0;
                ResponseMsg.Append("{");
                ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "-10");
                ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "accesstoken没拿到,修改密码失败");
                ResponseMsg.Append("}");
                return(ResponseMsg.ToString());
            }
            string paras      = String.Empty;
            string format     = "json";
            string parameters = "accessToken=" + accessToken + "&password="******"&nPassword="******"&clientIp=" + clientIp + "&clientAgent=" + clientAgent;
            strMsg.AppendFormat("parameters:={0}\r\n", parameters);
            paras = CryptographyUtil.XXTeaEncrypt(parameters, appSecret);
            strMsg.AppendFormat("paras:={0}\r\n", paras);
            sign = CryptographyUtil.HMAC_SHA1(appId + clientType + format + version + paras, appSecret);
            strMsg.AppendFormat("sign:={0}\r\n", sign);
            NameValueCollection postData = new NameValueCollection();
            postData.Add("appId", appId);
            postData.Add("version", version);
            postData.Add("clientType", clientType);
            postData.Add("paras", paras);
            postData.Add("sign", sign);
            postData.Add("format", format);

            WebClient webclient = new WebClient();
            webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
            byte[] responseData = webclient.UploadValues(UDBConstDefinition.DefaultInstance.UnifyPlatformUpdatePwdUrl, "POST", postData);
            jsonResult = System.Text.Encoding.UTF8.GetString(responseData);
            strMsg.AppendFormat("jsonResult:{0}\r\n", jsonResult);
            #endregion

            Dictionary <string, string> result_dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonResult);
            int    result   = -1;
            String s_result = String.Empty;
            String msg      = String.Empty;
            result_dic.TryGetValue("msg", out msg);
            result_dic.TryGetValue("result", out s_result);
            result             = Convert.ToInt32(s_result);
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "0");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", msg);
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }
        catch (Exception e)
        {
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "-10");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", e.ToString());
            ResponseMsg.Append("}");
            return(ResponseMsg.ToString());
        }


        return(ResponseMsg.ToString());
    }
示例#53
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases = new List <ReleaseInfo>();

            var qc = new NameValueCollection
            {
                { "incldead", "1" }
            };

            if (query.IsImdbQuery)
            {
                qc.Add("search", query.ImdbID);
                qc.Add("sc", "2"); // search in description
            }
            else
            {
                qc.Add("search", query.GetQueryString());
                qc.Add("sc", "1"); // search in title
            }

            foreach (var cat in MapTorznabCapsToTrackers(query))
            {
                qc.Add("c" + cat, "1");
            }

            var searchUrl = SearchUrl + "?" + qc.GetQueryString();
            var response  = await RequestWithCookiesAndRetryAsync(searchUrl, referer : SearchUrl);

            if (response.IsRedirect) // re-login
            {
                await ApplyConfiguration(null);

                response = await RequestWithCookiesAndRetryAsync(searchUrl, referer : SearchUrl);
            }

            try
            {
                var parser = new HtmlParser();
                var dom    = parser.ParseDocument(response.ContentString);
                var rows   = dom.QuerySelectorAll("table > tbody:has(tr > td.colhead) > tr:not(:has(td.colhead))");
                foreach (var row in rows)
                {
                    var release = new ReleaseInfo();
                    var link    = row.QuerySelector("td:nth-of-type(2) a:nth-of-type(2)");
                    release.Guid     = new Uri(SiteLink + link.GetAttribute("href"));
                    release.Comments = release.Guid;
                    release.Title    = link.GetAttribute("title");

                    // There isn't a title attribute if the release name isn't truncated.
                    if (string.IsNullOrWhiteSpace(release.Title))
                    {
                        release.Title = link.FirstChild.TextContent.Trim();
                    }
                    release.Description = release.Title;

                    // If we search an get no results, we still get a table just with no info.
                    if (string.IsNullOrWhiteSpace(release.Title))
                    {
                        break;
                    }

                    // Check if the release has been assigned a category
                    var qCat = row.QuerySelector("td:nth-of-type(1) a");
                    if (qCat != null)
                    {
                        var cat = qCat.GetAttribute("href").Substring(15);
                        release.Category = MapTrackerCatToNewznab(cat);
                    }

                    var qLink = row.QuerySelector("td:nth-of-type(2) a");
                    release.Link = new Uri(SiteLink + qLink.GetAttribute("href"));
                    var added = row.QuerySelector("td:nth-of-type(5)").TextContent.Trim();
                    release.PublishDate = DateTime.ParseExact(added, "yyyy-MM-ddHH:mm:ss", CultureInfo.InvariantCulture);
                    var sizeStr = row.QuerySelector("td:nth-of-type(7)").TextContent.Trim();
                    release.Size    = ReleaseInfo.GetBytes(sizeStr);
                    release.Seeders = ParseUtil.CoerceInt(row.QuerySelector("td:nth-of-type(9)").TextContent.Trim());
                    release.Peers   = ParseUtil.CoerceInt(row.QuerySelector("td:nth-of-type(10)").TextContent.Trim()) +
                                      release.Seeders;
                    var files = row.QuerySelector("td:nth-child(3)").TextContent;
                    release.Files = ParseUtil.CoerceInt(files);
                    var grabs = row.QuerySelector("td:nth-child(8)").TextContent;
                    if (grabs != "----")
                    {
                        release.Grabs = ParseUtil.CoerceInt(grabs);
                    }
                    release.DownloadVolumeFactor =
                        row.QuerySelector("font[color=\"green\"]:contains(\"F\"):contains(\"L\")") != null ? 0 : 1;
                    release.UploadVolumeFactor = 1;
                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(response.ContentString, ex);
            }

            return(releases);
        }
        /// <summary>returns string name / string value pair of all attribs for specified assembly</summary>
        public static NameValueCollection AssemblyAttributes(Assembly a)
        {
            string TypeName;
            string Name;
            string Value;
            NameValueCollection nvc = new NameValueCollection();
            Regex r = new Regex(@"(\.Assembly|\.)(?<Name>[^.]*)Attribute$", RegexOptions.IgnoreCase);

            foreach (object attrib in a.GetCustomAttributes(false))
            {
                TypeName = attrib.GetType().ToString();
                Name     = r.Match(TypeName).Groups["Name"].ToString();
                Value    = string.Empty;
                switch (TypeName)
                {
                case "System.CLSCompliantAttribute":
                    Value = ((CLSCompliantAttribute)attrib).IsCompliant.ToString();
                    break;

                case "System.Diagnostics.DebuggableAttribute":
                    Value = ((System.Diagnostics.DebuggableAttribute)attrib).IsJITTrackingEnabled.ToString();
                    break;

                case "System.Reflection.AssemblyCompanyAttribute":
                    Value = ((AssemblyCompanyAttribute)attrib).Company.ToString();
                    break;

                case "System.Reflection.AssemblyConfigurationAttribute":
                    Value = ((AssemblyConfigurationAttribute)attrib).Configuration.ToString();
                    break;

                case "System.Reflection.AssemblyCopyrightAttribute":
                    Value = ((AssemblyCopyrightAttribute)attrib).Copyright.ToString();
                    break;

                case "System.Reflection.AssemblyDefaultAliasAttribute":
                    Value = ((AssemblyDefaultAliasAttribute)attrib).DefaultAlias.ToString();
                    break;

                case "System.Reflection.AssemblyDelaySignAttribute":
                    Value = ((AssemblyDelaySignAttribute)attrib).DelaySign.ToString();
                    break;

                case "System.Reflection.AssemblyDescriptionAttribute":
                    Value = ((AssemblyDescriptionAttribute)attrib).Description.ToString();
                    break;

                case "System.Reflection.AssemblyInformationalVersionAttribute":
                    Value = ((AssemblyInformationalVersionAttribute)attrib).InformationalVersion.ToString();
                    break;

                case "System.Reflection.AssemblyKeyFileAttribute":
                    Value = ((AssemblyKeyFileAttribute)attrib).KeyFile.ToString();
                    break;

                case "System.Reflection.AssemblyProductAttribute":
                    Value = ((AssemblyProductAttribute)attrib).Product.ToString();
                    break;

                case "System.Reflection.AssemblyTrademarkAttribute":
                    Value = ((AssemblyTrademarkAttribute)attrib).Trademark.ToString();
                    break;

                case "System.Reflection.AssemblyTitleAttribute":
                    Value = ((AssemblyTitleAttribute)attrib).Title.ToString();
                    break;

                case "System.Resources.NeutralResourcesLanguageAttribute":
                    Value = ((System.Resources.NeutralResourcesLanguageAttribute)attrib).CultureName.ToString();
                    break;

                case "System.Resources.SatelliteContractVersionAttribute":
                    Value = ((System.Resources.SatelliteContractVersionAttribute)attrib).Version.ToString();
                    break;

                case "System.Runtime.InteropServices.ComCompatibleVersionAttribute":
                {
                    System.Runtime.InteropServices.ComCompatibleVersionAttribute x;
                    x     = ((System.Runtime.InteropServices.ComCompatibleVersionAttribute)attrib);
                    Value = x.MajorVersion + "." + x.MinorVersion + "." + x.RevisionNumber + "." + x.BuildNumber;
                    break;
                }

                case "System.Runtime.InteropServices.ComVisibleAttribute":
                    Value = ((System.Runtime.InteropServices.ComVisibleAttribute)attrib).Value.ToString();
                    break;

                case "System.Runtime.InteropServices.GuidAttribute":
                    Value = ((System.Runtime.InteropServices.GuidAttribute)attrib).Value.ToString();
                    break;

                case "System.Runtime.InteropServices.TypeLibVersionAttribute":
                {
                    System.Runtime.InteropServices.TypeLibVersionAttribute x;
                    x     = ((System.Runtime.InteropServices.TypeLibVersionAttribute)attrib);
                    Value = x.MajorVersion + "." + x.MinorVersion;
                    break;
                }

                case "System.Security.AllowPartiallyTrustedCallersAttribute":
                    Value = "(Present)";
                    break;

                default:
                    // debug.writeline("** unknown assembly attribute '" + TypeName + "'")
                    Value = TypeName;
                    break;
                }
                if (nvc[Name] == null)
                {
                    nvc.Add(Name, Value);
                }
            }
            // add some extra values that are not in the AssemblyInfo, but nice to have
            // codebase
            try
            {
                nvc.Add("CodeBase", a.CodeBase.Replace("file:///", string.Empty));
            }
            catch (NotSupportedException)
            {
                nvc.Add("CodeBase", "(not supported)");
            }
            // build date
            DateTime dt = AssemblyBuildDate(a, false);

            if (dt == DateTime.MaxValue)
            {
                nvc.Add("BuildDate", "(unknown)");
            }
            else
            {
                nvc.Add("BuildDate", dt.ToString("yyyy-MM-dd hh:mm tt"));
            }
            // location
            try
            {
                nvc.Add("Location", a.Location);
            }
            catch (NotSupportedException)
            {
                nvc.Add("Location", "(not supported)");
            }
            // version
            try
            {
                if (a.GetName().Version.Major == 0 && a.GetName().Version.Minor == 0)
                {
                    nvc.Add("Version", "(unknown)");
                }
                else
                {
                    nvc.Add("Version", a.GetName().Version.ToString());
                }
            }
            catch (Exception)
            {
                nvc.Add("Version", "(unknown)");
            }
            nvc.Add("FullName", a.FullName);
            return(nvc);
        }
示例#55
0
 private NameValueCollection GetAuthHeaders()
 {
     NameValueCollection headers = new NameValueCollection();
     headers.Add("Authorization", "Bearer " + AuthInfo.Token.access_token);
     return headers;
 }
示例#56
0
 private void OnHeader(object sender, HeaderEventArgs e)
 {
     _headers.Add(e.Name, e.Value);
 }
示例#57
0
        private void SubmitUser_Click(object sender, RoutedEventArgs e)
        {
            NameValueCollection UserInfo = new NameValueCollection();

            UserInfo.Add("register", "");
            UserInfo.Add("user_name", user_name.Text);
            UserInfo.Add("user_mail", user_mail.Text);
            UserInfo.Add("user_pass", user_pass.Password);
            var     InsertUser     = client.UploadValues(Login.server, "POST", UserInfo);
            var     responseString = Encoding.UTF8.GetString(InsertUser);
            dynamic stuff          = JsonConvert.DeserializeObject(responseString);
            String  cases          = stuff.msg;

            switch (cases)
            {
            case "register successfully!":
            {
                Login log = new Login();
                log.UserMail.Text         = user_mail.Text;
                log.UserPassword.Password = user_pass.Password;
                log.Label_message.Content = "Your account has been created successfully please login!";
                Close();
                log.Show();
                break;
            }

            case "invalid username!":
            {
                Label_message.Content = "Invalid username! you can use letters, numbers and periods!";
                break;
            }

            case "invalid email!":
            {
                Label_message.Content = "Invalid email!\nYou can use letters, numbers and periods\nFormat example [email protected]!";
                break;
            }

            case "invalid username!invalid email!":
            {
                Label_message.Content = "Invalid username and email,\nYou can use letters, numbers and periods!";
                break;
            }

            case "Sorry username already taken!":
            {
                Label_message.Content = "Sorry username already taken!";
                break;
            }

            case "Sorry email id already taken!":
            {
                Label_message.Content = "Sorry email id already taken!";
                break;
            }

            default:
            {
                Label_message.Content = "Server error!";
                break;
            }
            }
        }
示例#58
0
        public async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases     = new List <ReleaseInfo>();
            var searchUrl    = BrowseUrl;
            var searchString = query.GetQueryString();

            var    cats = MapTorznabCapsToTrackers(query);
            string cat  = "0";

            if (cats.Count == 1)
            {
                cat = cats[0];
            }

            var queryCollection = new NameValueCollection();

            if (query.ImdbID != null)
            {
                queryCollection.Add("search", query.ImdbID);
            }
            else if (!string.IsNullOrWhiteSpace(searchString))
            {
                queryCollection.Add("search", searchString);
            }

            queryCollection.Add("cat", cat);
            queryCollection.Add("searchin", "0");
            queryCollection.Add("sort", "0");

            searchUrl += "?" + queryCollection.GetQueryString();

            var response = await RequestStringWithCookiesAndRetry(searchUrl, null, BrowseUrl);

            var results = response.Content;

            try
            {
                CQ  dom             = results;
                var globalFreeLeech = dom.Find("div.globalFreeLeech").Any();
                var rows            = dom[".torrentrow"];
                foreach (var row in rows)
                {
                    var release    = new ReleaseInfo();
                    var qRow       = row.Cq();
                    var qTitleLink = qRow.Find(".torrenttable:eq(1) a").First();
                    release.Title = qRow.Find(".torrenttable:eq(1) a").Attr("title");

                    if (query.ImdbID == null && !query.MatchQueryStringAND(release.Title))
                    {
                        continue;
                    }

                    release.Description = qRow.Find(".torrenttable:eq(1) > span > font.small").First().Text();

                    release.Guid     = new Uri(SiteLink + qTitleLink.Attr("href"));
                    release.Comments = release.Guid;

                    //22:05:3716/02/2013
                    var dateStr = qRow.Find(".torrenttable:eq(5)").Text().Trim() + " +0200";
                    release.PublishDate = DateTime.ParseExact(dateStr, "H:mm:ssdd/MM/yyyy zzz", CultureInfo.InvariantCulture);

                    var qLink = qRow.Find("a[href^=\"download.php?id=\"]").First();
                    release.Link = new Uri(SiteLink + qLink.Attr("href"));

                    var sizeStr = qRow.Find(".torrenttable:eq(6)").Text().Trim();
                    release.Size = ReleaseInfo.GetBytes(sizeStr);

                    release.Seeders = ParseUtil.CoerceInt(qRow.Find(".torrenttable:eq(8)").Text().Trim());
                    release.Peers   = ParseUtil.CoerceInt(qRow.Find(".torrenttable:eq(9)").Text().Trim()) + release.Seeders;

                    var catId = qRow.Find(".torrenttable:eq(0) a").First().Attr("href").Substring(15);
                    release.Category = MapTrackerCatToNewznab(catId);

                    var grabs = qRow.Find(".torrenttable:eq(7)").First().Get(0).FirstChild;
                    release.Grabs = ParseUtil.CoerceLong(catId);

                    if (globalFreeLeech || row.Cq().Find("img[alt=\"FreeLeech\"]").Any())
                    {
                        release.DownloadVolumeFactor = 0;
                    }
                    else
                    {
                        release.DownloadVolumeFactor = 1;
                    }

                    release.UploadVolumeFactor = 1;

                    // Skip Romanian releases
                    if (release.Category == TorznabCatType.MoviesForeign.ID && !configData.IncludeRomanianReleases.Value)
                    {
                        continue;
                    }

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results, ex);
            }

            return(releases);
        }
示例#59
0
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // only cache view results, but don't return already as we still need to process redirections
            if (!(filterContext.Result is ViewResultBase) && !(AuthorizedContentTypes.Contains(filterContext.HttpContext.Response.ContentType)))
            {
                _filter = null;
            }

            // ignore error results from cache
            if (filterContext.HttpContext.Response.StatusCode != (int)HttpStatusCode.OK)
            {
                // Never cache non-200 responses.
                filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                filterContext.HttpContext.Response.Cache.SetNoStore();
                filterContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0));

                _filter = null;
                return;
            }

            // if the result of a POST is a Redirect, remove any Cache Item for this url
            // so that the redirected client gets a fresh result
            // also add a random token to the query string so that public cachers (IIS, proxies, ...) don't return cached content
            // i.e., Comment creation

            // ignore in admin
            if (AdminFilter.IsApplied(new RequestContext(filterContext.HttpContext, new RouteData())))
            {
                return;
            }

            _workContext = _workContextAccessor.GetContext();

            // ignore authenticated requests
            if (_workContext.CurrentUser != null)
            {
                return;
            }

            // todo: look for RedirectToRoute to, or intercept 302s

            if (filterContext.HttpContext.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
                filterContext.Result is RedirectResult)
            {
                Logger.Debug("Redirect on POST");
                var redirectUrl = ((RedirectResult)filterContext.Result).Url;

                if (!VirtualPathUtility.IsAbsolute(redirectUrl))
                {
                    var applicationRoot = filterContext.HttpContext.Request.ToRootUrlString();
                    if (redirectUrl.StartsWith(applicationRoot, StringComparison.OrdinalIgnoreCase))
                    {
                        redirectUrl = redirectUrl.Substring(applicationRoot.Length);
                    }
                }

                // querystring invariant key
                var invariantCacheKey = ComputeCacheKey(
                    _shellSettings.Name,
                    redirectUrl,
                    () => _workContext.CurrentCulture,
                    _themeManager.GetRequestTheme(filterContext.RequestContext).Id,
                    null
                    );

                _cacheService.RemoveByTag(invariantCacheKey);

                // adding a refresh key so that the next request will not be cached
                var epIndex = redirectUrl.IndexOf('?');
                var qs      = new NameValueCollection();
                if (epIndex > 0)
                {
                    qs = HttpUtility.ParseQueryString(redirectUrl.Substring(epIndex));
                }

                var refresh = _now.Ticks;
                qs.Remove(RefreshKey);

                qs.Add(RefreshKey, refresh.ToString("x"));
                var querystring = "?" + string.Join("&", Array.ConvertAll(qs.AllKeys, k => string.Format("{0}={1}", HttpUtility.UrlEncode(k), HttpUtility.UrlEncode(qs[k]))));

                if (epIndex > 0)
                {
                    redirectUrl = redirectUrl.Substring(0, epIndex) + querystring;
                }
                else
                {
                    redirectUrl = redirectUrl + querystring;
                }

                filterContext.Result = new RedirectResult(redirectUrl, ((RedirectResult)filterContext.Result).Permanent);
                filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
        }
示例#60
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 3, 5, DayOfWeek.Sunday);
            TimeZoneInfo.TransitionTime endTransition   = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 5, DayOfWeek.Sunday);
            TimeSpan delta = new TimeSpan(1, 0, 0);

            TimeZoneInfo.AdjustmentRule   adjustment  = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition);
            TimeZoneInfo.AdjustmentRule[] adjustments = { adjustment };
            TimeZoneInfo germanyTz = TimeZoneInfo.CreateCustomTimeZone("W. Europe Standard Time", new TimeSpan(1, 0, 0), "(GMT+01:00) W. Europe Standard Time", "W. Europe Standard Time", "W. Europe DST Time", adjustments);

            var releases = new List <ReleaseInfo>();

            var searchString    = query.GetQueryString();
            var searchUrl       = BrowseUrl;
            var queryCollection = new NameValueCollection();

            queryCollection.Add("showsearch", "1");
            queryCollection.Add("incldead", "1");
            queryCollection.Add("orderby", "added");
            queryCollection.Add("sort", "desc");

            if (!string.IsNullOrWhiteSpace(searchString))
            {
                queryCollection.Add("search", searchString);
            }

            foreach (var cat in MapTorznabCapsToTrackers(query))
            {
                queryCollection.Add("c" + cat, "1");
            }
            searchUrl += "?" + queryCollection.GetQueryString();

            var response = await RequestStringWithCookies(searchUrl);

            var results = response.Content;

            try
            {
                CQ  dom             = results;
                var globalFreeleech = dom.Find("div > img[alt=\"Only Upload\"][title^=\"ONLY UPLOAD \"]").Any();
                var rows            = dom["table.tableinborder > tbody > tr:has(td.tableb)"];

                foreach (var row in rows)
                {
                    var release = new ReleaseInfo();
                    var qRow    = row.Cq();

                    var qDetailsLink = qRow.Find("a[href^=details.php?id=]").First();
                    release.Title = qDetailsLink.Attr("title");

                    if (!query.MatchQueryStringAND(release.Title))
                    {
                        continue;
                    }

                    var qCatLink    = qRow.Find("a[href^=browse.php?cat=]").First();
                    var qDLLink     = qRow.Find("a[href^=download.php?torrent=]").First();
                    var qSeeders    = qRow.Find("span:contains(Seeder) > b:eq(0)");
                    var qLeechers   = qRow.Find("span:contains(Seeder) > b:eq(1)");
                    var qDateStr    = qRow.Find("td > table > tbody > tr > td:eq(7)").First();
                    var qSize       = qRow.Find("span:contains(Volumen) > b:eq(0)").First();
                    var qOnlyUpload = qRow.Find("img[title=OnlyUpload]");

                    if (qOnlyUpload.Any())
                    {
                        release.MinimumRatio    = 2;
                        release.MinimumSeedTime = 144 * 60 * 60;
                    }
                    else
                    {
                        release.MinimumRatio    = 1;
                        release.MinimumSeedTime = 72 * 60 * 60;
                    }

                    var catStr = qCatLink.Attr("href").Split('=')[1];
                    release.Category = MapTrackerCatToNewznab(catStr);

                    release.Link     = new Uri(SiteLink + qDLLink.Attr("href"));
                    release.Comments = new Uri(SiteLink + qDetailsLink.Attr("href"));
                    release.Guid     = release.Link;

                    var sizeStr = qSize.Text();
                    release.Size = ReleaseInfo.GetBytes(sizeStr);

                    release.Seeders = ParseUtil.CoerceInt(qSeeders.Text());
                    release.Peers   = ParseUtil.CoerceInt(qLeechers.Text()) + release.Seeders;

                    var      dateStr    = qDateStr.Text().Trim().Replace('\xA0', ' ');
                    DateTime dateGerman = DateTime.SpecifyKind(DateTime.ParseExact(dateStr, "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture), DateTimeKind.Unspecified);

                    DateTime pubDateUtc = TimeZoneInfo.ConvertTimeToUtc(dateGerman, germanyTz);
                    release.PublishDate = pubDateUtc.ToLocalTime();

                    var files = qRow.Find("a[href*=\"&filelist=1\"] ~ font ~ b").Text();
                    release.Files = ParseUtil.CoerceInt(files);

                    var grabs = qRow.Find("a[href*=\"&tosnatchers=1\"] ~ font ~ b").Text();
                    release.Grabs = ParseUtil.CoerceInt(grabs);

                    if (globalFreeleech)
                    {
                        release.DownloadVolumeFactor = 0;
                    }
                    else if (qRow.Find("img[alt=\"OU\"]").Length >= 1)
                    {
                        release.DownloadVolumeFactor = 0;
                    }
                    else
                    {
                        release.DownloadVolumeFactor = 1;
                    }

                    release.UploadVolumeFactor = 1;

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results, ex);
            }

            return(releases);
        }