Esempio n. 1
0
        public static string Api(string Temperature,string Humidity)
        {
            string url = (string)Properties.Settings.Default["ApiAddress"];
            string resText = "";
            try {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                ps.Add("MachineName", (string)Properties.Settings.Default["MachineName"]);
                ps.Add("Temperature", Temperature);
                ps.Add("Humidity", Humidity);

                byte[] ResData = wc.UploadValues(url, ps);
                wc.Dispose();
                resText = System.Text.Encoding.UTF8.GetString(ResData);
                if (resText != "OK")
                {
                    return "APIエラー";
                }
            }
            catch (Exception ex){
                return ex.ToString();
            }

            return null;
        }
        public bool UpdateDNSIP(string rec_id, string IP, string name, string service_mode, string ttl)
        {
            string url = "https://www.cloudflare.com/api_json.html";

            System.Net.WebClient wc = new System.Net.WebClient();
            //NameValueCollectionの作成
            System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();
            //送信するデータ(フィールド名と値の組み合わせ)を追加
            ps.Add("a", "rec_edit");
            ps.Add("tkn", KEY);
            ps.Add("id", rec_id);
            ps.Add("email", EMAIL);
            ps.Add("z", DOMAIN);
            ps.Add("type", "A");
            ps.Add("name", name);
            ps.Add("content", IP);
            ps.Add("service_mode", service_mode);
            ps.Add("ttl", ttl);

            //データを送信し、また受信する
            byte[] resData = wc.UploadValues(url, ps);
            wc.Dispose();
            string resText = System.Text.Encoding.UTF8.GetString(resData);
            Clipboard.SetText(resText);
            return false;
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            using (WebClient client = new WebClient())
            {
                System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
                reqparm.Add("username", "Matija");
                reqparm.Add("passwd", "1234");
                byte[] bytes = client.UploadValues("http://ates-test.algebra.hr/iis/testSubmit.aspx", "POST", reqparm);
                string body = Encoding.UTF8.GetString(bytes);
                Console.WriteLine(body);

                WebHeaderCollection wcHeaderCollection = client.ResponseHeaders;
                Console.WriteLine("\nHeaders:\n");

                for (int i = 0; i < wcHeaderCollection.Count; i++)
                {
                    Console.WriteLine(wcHeaderCollection.GetKey(i) + " = " + wcHeaderCollection.Get(i));
                }
            }
            Console.WriteLine();

            using (WebClient client = new WebClient())
            {
                string reply = client.DownloadString(@"http://ates-test.algebra.hr/iis/testSubmit.aspx?username=Matija&passwd=1234");
                Console.WriteLine(reply);
                WebHeaderCollection wcHeaderCollection = client.ResponseHeaders;
                Console.WriteLine("\nHeaders:\n");

                for (int i = 0; i < wcHeaderCollection.Count; i++)
                {
                    Console.WriteLine(wcHeaderCollection.GetKey(i) + " = " + wcHeaderCollection.Get(i));
                }
                Console.ReadKey();
            }
        }
Esempio n. 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Authentication
            if ((textBox2.Text == "") || (textBox7.Text == "") || (textBox8.Text == ""))
            {
                MessageBox.Show("Check Parameters");
                return;
            }
            DOMAIN = textBox2.Text;
            ADMIN_USER = textBox7.Text;
            ADMIN_PWD = textBox8.Text;

            System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();
            ps.Add("accountType", "HOSTED");
            ps.Add("Email", ADMIN_USER + "@" + DOMAIN);
            ps.Add("Passwd", ADMIN_PWD);
            ps.Add("service", "apps");
            WebClient wc = new WebClient();
            try
            {
                byte[] resData = wc.UploadValues(@"https://www.google.com/accounts/ClientLogin", ps);
                wc.Dispose();
                string[] a = System.Text.Encoding.UTF8.GetString(resData).Split('\n');
                foreach (string str in a)
                {
                    if (str.StartsWith("Auth="))
                    {
                        label1.Text = str;
                        AuthNToken = str.Substring(5);
                    }
                }
                button4.Enabled = true;
                button5.Enabled = true;
                button6.Enabled = true;
                button7.Enabled = true;
                button8.Enabled = true;
                button9.Enabled = true;
                checkBox1.Enabled = true;
                checkBox2.Enabled = true;
                textBox1.Text = "operation completed";
                button1.Enabled = false;
            }
            catch (System.Net.WebException ex)
            {
                //HttpWebResponseを取得
                System.Net.HttpWebResponse errres =
                    (System.Net.HttpWebResponse)ex.Response;
                textBox1.Text =
                    errres.StatusCode.ToString() + ":" + errres.StatusDescription;

            }
            finally
            {
                wc.Dispose();
            }
        }
        // 登录
        protected void ibLogin_Click(object sender, ImageClickEventArgs e)
        {
            // 记录其IP地址,下次登录时验证,IP为空则记录,IP不为空则验证
            string uname = this.tbUname.Value;
            string upwd = this.tbPwd.Value;
            string uid = new JumbotOA.BLL.UserBLL().Existslongin(uname, JumbotOA.Utils.MD5.Lower32(upwd));
            if (uid != "")
            {
                JumbotOA.Entity.UserEntity model = new JumbotOA.Entity.UserEntity();
                model = new JumbotOA.BLL.UserBLL().GetEntity(int.Parse(uid));
                if (model.Uipaddress != "")
                {
                    if (model.Uipaddress != Page.Request.UserHostAddress)
                    {
                        Response.Write("<script>alert('非法IP,请在本机登陆!');</script>");
                        Response.End();
                    }
                }
                int iExpires = 0;
                //设置Cookies
                System.Collections.Specialized.NameValueCollection myCol = new System.Collections.Specialized.NameValueCollection();
                myCol.Add("id", uid.ToString());
                myCol.Add("name", uname);
                myCol.Add("ip", Request.UserHostAddress);
                new BLL.UserBLL().UpdateTime(model.Uid);
                int pid = model.Pid;
                myCol.Add("Powerid",pid.ToString());
                JumbotOA.Utils.Cookie.SetObj("oa_user", 60 * 60 * 15 * iExpires, myCol, "", "/");

                switch (pid)
                {
                    case 1:
                        Response.Redirect("Home1.aspx");//管理员
                        break;
                    case 2:
                        Response.Redirect("Home2.aspx");//管理组织层
                        break;
                    case 3:
                        Response.Redirect("Home3.aspx");//网站编辑
                        break;
                    case 4:
                        Response.Redirect("Home4.aspx");//美工和程序员
                        break;
                }
            }
            else
            {
                this.tbUname.Value = "";
                this.tbPwd.Value = "";
                System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
                page.ClientScript.RegisterStartupScript(page.GetType(), "clientScript", "<script language='javascript'>alert('请正确填写用户名和密码!');</script>");
            }
        }
Esempio n. 6
0
 public string GetWebContent(string Url, string pagenum, string cat)
 {
     string strResult = "";
     try
     {
         WebClient WebClientObj = new WebClient();
         System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
         PostVars.Add("Cat", cat);
         PostVars.Add("mnonly", "0");
         PostVars.Add("newproducts", "0");
         PostVars.Add("ColumnSort", "0");
         PostVars.Add("page", pagenum);
         PostVars.Add("stock", "0");
         PostVars.Add("pbfree", "0");
         PostVars.Add("rohs", "0");
         byte[] byRemoteInfo = WebClientObj.UploadValues(Url, "POST", PostVars);
         //StreamReader streamRead = new StreamReader(byRemoteInfo.ToString(), Encoding.Default);
         //FileStream fs = new FileStream(@"D:\\gethtml.txt", FileMode.Create);
         //BinaryWriter sr = new BinaryWriter(fs);
         //sr.Write(byRemoteInfo, 0, byRemoteInfo.Length);
         //sr.Close();
         //fs.Close();
         strResult = Encoding.Default.GetString(byRemoteInfo);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     return strResult;
 }
 protected override bool OnBeforePopup(CefBrowser browser, CefFrame frame, string targetUrl, string targetFrameName, CefPopupFeatures popupFeatures, CefWindowInfo windowInfo, ref CefClient client, CefBrowserSettings settings, ref bool noJavascriptAccess)
 {
     bool res = false;
     if (!string.IsNullOrEmpty(targetUrl))
     {
         if (webBrowser.selfRequest != null)
         {
             CefRequest req = CefRequest.Create();
             req.FirstPartyForCookies = webBrowser.selfRequest.FirstPartyForCookies;
             req.Options = webBrowser.selfRequest.Options;
             /*CefPostData postData = CefPostData.Create();
             CefPostDataElement element = CefPostDataElement.Create();
             int index = targetUrl.IndexOf("?");
             string url = targetUrl.Substring(0, index);
             string data = targetUrl.Substring(index + 1);
             byte[] bytes = Encoding.UTF8.GetBytes(data);
             element.SetToBytes(bytes);
             postData.Add(element);
             */
             System.Collections.Specialized.NameValueCollection h = new System.Collections.Specialized.NameValueCollection();
             h.Add("Content-Type", "application/x-www-form-urlencoded");
             req.Set(targetUrl, webBrowser.selfRequest.Method, null, webBrowser.selfRequest.GetHeaderMap());
             webBrowser.selfRequest = req;
         }
         //webBrowser.selfRequest.Set(targetUrl, webBrowser.selfRequest.Method, webBrowser.selfRequest.PostData, webBrowser.selfRequest.GetHeaderMap());
         res = webBrowser.OnNewWindow(targetUrl);
         if (res)
             return res;
     }
     res = base.OnBeforePopup(browser, frame, targetUrl, targetFrameName, popupFeatures, windowInfo, ref client, settings, ref noJavascriptAccess);
     return res;
 }
Esempio n. 8
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";

            string prefFilter = context.Request["pref"] ?? "全て";
            string cityFilter = context.Request["city"] ?? "全て";
            string categoryFilter = context.Request["category"] ?? "全て";
            string productFilter = context.Request["product"] ?? "全て";
            string publishDayFilter = context.Request["publish"] ?? "全て";
            string pickDayFilter = context.Request["pick"] ?? "全て";
            string sortItem = context.Request["sort"] ?? "1";
            string widthString = context.Request["width"] ?? "";
            string heightString = context.Request["height"] ?? "";

            int width, height;
            if (Int32.TryParse(widthString, out width) == false) width = 600;
            if (Int32.TryParse(heightString, out height) == false) height = 300;
            width = Math.Min(1000, Math.Max(300, width));
            height = Math.Min(600, Math.Max(150, height));

            var list = Common.GetQuery(prefFilter, cityFilter, categoryFilter, productFilter, publishDayFilter, pickDayFilter, sortItem);
            var param = list.Item1.ToList().PrepareChartParam(width, height);

            using (var cl = new System.Net.WebClient())
            {
                var values = new System.Collections.Specialized.NameValueCollection();
                foreach (var item in param)
                {
                    values.Add(item.Substring(0, item.IndexOf('=')), item.Substring(item.IndexOf('=') + 1));
                }
                var resdata = cl.UploadValues("http://chart.googleapis.com/chart?chid=1", values);
                context.Response.OutputStream.Write(resdata, 0, resdata.Length);
            }
        }
Esempio n. 9
0
        private System.Collections.Specialized.NameValueCollection GetAssemblyEventMapping(System.Reflection.Assembly assembly, Hl7Package package)
        {
            System.Collections.Specialized.NameValueCollection structures = new System.Collections.Specialized.NameValueCollection();
            using (System.IO.Stream inResource = assembly.GetManifestResourceStream(package.EventMappingResourceName))
            {
                if (inResource != null)
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(inResource))
                    {
                        string line = sr.ReadLine();
                        while (line != null)
                        {
                            if ((line.Length > 0) && ('#' != line[0]))
                            {
                                string[] lineElements = line.Split(' ', '\t');
                                structures.Add(lineElements[0], lineElements[1]);
                            }
                            line = sr.ReadLine();

                        }
                    }
                }
            }
            return structures;
        }
Esempio n. 10
0
 public static System.Collections.Specialized.NameValueCollection Decode(string markString)
 {
     System.Text.RegularExpressions.MatchCollection _matckresult = _decodeReg.Matches(markString);
     if (_matckresult.Count > 0) {
         System.Collections.Specialized.NameValueCollection marks = new System.Collections.Specialized.NameValueCollection();
         for (int i = 0; i < _matckresult.Count; i++) {
             System.Text.RegularExpressions.Match match = _matckresult[i];
             string tempname, tempvalue;
             if (match.Value.IndexOf('=') > 0) {
                 tempname = match.Value.Substring(0, match.Value.IndexOf('='));
                 tempvalue = match.Value.Substring(match.Value.IndexOf('=') + 1);
             } else {
                 tempname = match.Value;
                 tempvalue = string.Empty;
             }
             tempname = tempname.Trim();
             if (!string.IsNullOrEmpty(tempvalue)) {
                 tempvalue = tempvalue.Trim(' ', tempvalue[0]);
             }
             marks.Add(tempname, tempvalue);
         }
         return marks;
     } else {
         throw new Exception(string.Format("Can not analyze \"{0}\"", markString));
     }
 }
Esempio n. 11
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="userAgent"></param>
		/// <param name="initialCapabilities"></param>
		/// <returns></returns>
		public System.Web.Configuration.CapabilitiesResult Process(string userAgent, System.Collections.IDictionary initialCapabilities)
		{
			System.Collections.Specialized.NameValueCollection header;
			header = new System.Collections.Specialized.NameValueCollection(1);
			header.Add("User-Agent", userAgent);
			return Process(header, initialCapabilities);
		}
Esempio n. 12
0
        public Proxy(DBPostPlugin plugin)
        {
            this.plugin = plugin;
            this.SortWorker = new RecordSortWorker();
            this.Records = new List<Record>();

            var proxy = KanColleClient.Current.Proxy;

            var apis = Enum.GetValues(typeof(Api)).Cast<Api>().ToList();
            foreach (var api in apis)
            {
                var url = api.GetUrl();
                proxy.ApiSessionSource.Where(x => x.Request.PathAndQuery
                    .StartsWith("/kcsapi/" + url))
                    .Subscribe(x =>
                    {
                        if (ToolSettings.SendDb && !string.IsNullOrEmpty(ToolSettings.DbAccessKey))
                        {
                            System.Collections.Specialized.NameValueCollection post
                                = new System.Collections.Specialized.NameValueCollection();
                            post.Add("token", ToolSettings.DbAccessKey);
                            post.Add("agent", "LZXNXVGPejgSnEXLH2ur");
                            post.Add("url", x.Request.PathAndQuery);
                            string requestBody = System.Text.RegularExpressions.Regex.Replace(
                                x.Request.BodyAsString,
                                @"&api(_|%5F)token=[0-9a-f]+|api(_|%5F)token=[0-9a-f]+&?", "");
                            post.Add("requestbody", requestBody);
                            post.Add("responsebody", x.Response.BodyAsString);
            #if DEBUG
                            MessageBox.Show(
                                string.Join(
                                    "\n", post.AllKeys.Select(key => key + ": " + post[key])),
                                    "この内容を送信します");
            #else
                            System.Net.WebClient wc = new System.Net.WebClient();
                            wc.UploadValuesAsync(new Uri("http://api.kancolle-db.net/2/"), post);
            #endif
                            Records.Add(new Record(DateTime.Now, api, x));
                            this.UpdateRows();

                            if (ToolSettings.NotifyLog)
                                this.Notify(Notification.Types.Test, "送信しました", x.Request.PathAndQuery);
                        }
                    });
            }
        }
Esempio n. 13
0
 public void FormValidation_Email_ShouldValidate()
 {
     var f = new DynaForm("form")
         .AddFormField("emailaddress", email: true);
     var formMock = new System.Collections.Specialized.NameValueCollection();
     formMock.Add("emailaddress", "*****@*****.**");
     f.TryUpdateModel(formMock);
     Assert.IsTrue(f.Validation.IsValid);
 }
Esempio n. 14
0
 public void FormValidation_Minimum_ShouldNotValidate()
 {
     var f = new DynaForm("form2")
         .AddFormField("number", numeric: true, min:4);
     var formMock = new System.Collections.Specialized.NameValueCollection();
     formMock.Add("number", "2");
     f.TryUpdateModel(formMock);
     Assert.IsFalse(f.Validation.IsValid);
 }
Esempio n. 15
0
 public void Start()
 {
     String URI = registry.URL + "/api.php";
     this.client = new WebClient();
     System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
     reqparm.Add();
     byte[] responsebytes = client.UploadValues(URI, "POST", reqparm);
     string responsebody = Encoding.UTF8.GetString(responsebytes);
 }
Esempio n. 16
0
        /// <summary>
        /// Execute an 'im mem' preview request of the provided page and content. The execution depends on the hosting environment.
        /// Then running in pipeline mode the current HttpContext is 
        /// </summary>
        /// <param name="selectedPage">Page to render. Functionality reading the rendered page ID will get the ID from this object.</param>
        /// <param name="contents">Content to render on the page</param>
        /// <param name="renderingReason">The rendering reason</param>
        /// <returns>The page html as a string when running in classic mode. In Pipeline mode the content is written directly to the HttpContext and an empty string is returned.</returns>
        public static string RenderPreview(IPage selectedPage, IList<IPagePlaceholderContent> contents, RenderingReason renderingReason)
        {
            HttpContext ctx = HttpContext.Current;
            string key = Guid.NewGuid().ToString();
            string query = "previewKey=" + key;

            ctx.Cache.Add(key + "_SelectedPage", selectedPage, null, Cache.NoAbsoluteExpiration, PreviewExpirationTimeSpan, CacheItemPriority.NotRemovable, null);
            ctx.Cache.Add(key + "_SelectedContents", contents, null, Cache.NoAbsoluteExpiration, PreviewExpirationTimeSpan, CacheItemPriority.NotRemovable, null);
            ctx.Cache.Add(key + "_RenderingReason", renderingReason, null, Cache.NoAbsoluteExpiration, PreviewExpirationTimeSpan, CacheItemPriority.NotRemovable, null);

            if (HttpRuntime.UsingIntegratedPipeline)
            {
                // The header trick here is to work around (what seems to be) a bug in .net 4.5, where preserveForm=false is ignored
                // asp.net 4.5 request validation will see the 'page edit http post' data and start bitching. It really should not.
                var headers = new System.Collections.Specialized.NameValueCollection();
                headers.Add("Content-Length", "0");

                string cookieHeader = ctx.Request.Headers["Cookie"];
                if (!string.IsNullOrEmpty(cookieHeader))
                {
                    headers.Add("Cookie", cookieHeader);
                }

                ctx.Server.TransferRequest("~/Renderers/Page.aspx?" + query, false, "GET", headers);
            }
            else
            {
                var sb = new StringBuilder();
                var writer = new StringWriter(sb);

                var wr = new PreviewWorkerRequest(query, ctx, writer);

                AllowChildRequestSessionAccess(ctx);
                HttpRuntime.ProcessRequest(wr);

                // Preview <iframe /> has source "~/Composite/content/flow/FlowUi.aspx" and page is rendered from "~/Renderers/Page.aspx"
                // The following line fixes style references processed by ASP.NET-s Control.ResolveClientUrl()
                sb = sb.Replace("href=\"../", "href=\"../../../");

                return sb.ToString();
            }

            return String.Empty;
        }
Esempio n. 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Collections.Specialized.NameValueCollection p = new System.Collections.Specialized.NameValueCollection();
            p.Add("id", ReportNumber.Text);
            Snowball.Common.PostSubmitter submitter = new Snowball.Common.PostSubmitter(
                "http://www.bloodlinesresurgence.com/error_reports/get.php", p);
            string content = submitter.Post();

            Report.Text = ResurgenceLib.Compression.StringDecompress(content);
        }
        public static System.Collections.Specialized.NameValueCollection ToNameValueCollection(this Dictionary<string, string> map)
        {
            if (map == null) return new System.Collections.Specialized.NameValueCollection();

            var nameValues = new System.Collections.Specialized.NameValueCollection();
            foreach (var item in map)
            {
                nameValues.Add(item.Key, item.Value);
            }
            return nameValues;
        }
        public dynamic getDNSINFO()
        {
            string url = "https://www.cloudflare.com/api_json.html";

            System.Net.WebClient wc = new System.Net.WebClient();
            //NameValueCollectionの作成
            System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();
            //送信するデータ(フィールド名と値の組み合わせ)を追加
            ps.Add("a", "rec_load_all");
            ps.Add("tkn", KEY);
            ps.Add("email", EMAIL);
            ps.Add("z", DOMAIN);
            //データを送信し、また受信する
            byte[] resData = wc.UploadValues(url, ps);
            wc.Dispose();

            //受信したデータを表示する
            string resText = System.Text.Encoding.UTF8.GetString(resData);

            var model = new JavaScriptSerializer().Deserialize<dynamic>(resText);

            for (int i = 0; i < model["response"]["recs"]["count"]; i++)
            {
                string type = model["response"]["recs"]["objs"][i]["type"];

                if (type == "A")
                {
                    return new
                    {
                        rec_id = model["response"]["recs"]["objs"][i]["rec_id"],
                        content = model["response"]["recs"]["objs"][i]["content"],
                        name = model["response"]["recs"]["objs"][i]["name"],
                        service_mode = model["response"]["recs"]["objs"][i]["service_mode"],
                        ttl = model["response"]["recs"]["objs"][i]["ttl"]
                    };
                }

            }

            return null;
        }
Esempio n. 20
0
        public ActionResult Check()
        {
            var code = Request.Form["code"];
            var text = Request.Form["text"];

            var wc = new xWebClient();
            if (Session["cookies"] != null)
                wc.CookieContainer = Session["cookies"] as CookieContainer;

            var values = new System.Collections.Specialized.NameValueCollection();
            values.Add("code", code);
            values.Add("textfield", text);

            var str = wc.UploadValues("http://gsxt.gdgs.gov.cn/aiccips/CheckEntContext/checkCode.html", values);
            var json = JObject.Parse(str);

            if ((int)json["flag"] != 1)
                return Content("验证码错误");

            values.Clear();
            values.Add("code", code);
            values.Add("textfield", (string)json["textfield"]);
            var htmlStr = wc.UploadValues("http://gsxt.gdgs.gov.cn/aiccips/CheckEntContext/showInfo.html", values);

            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlStr);

            var nodes = doc.DocumentNode.SelectNodes("//div[@class='list']/ul");
            var list = new List<object>();
            foreach (var node in nodes)
            {
                var li1 = node.SelectSingleNode("li[1]/a");
                var li2 = node.SelectSingleNode("li[2]");

                var o = new { name = li1.InnerText, brief = li2.InnerText, data = li1.Attributes["href"].Value };
                list.Add(o);
            }

            return Content(JsonConvert.SerializeObject(list));
        }
 public void uploadToWebServer()
 {
     System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
     reqparm.Add("temp1", temps[0].ToString());
     reqparm.Add("temp2", temps[1].ToString());
     reqparm.Add("temp3", temps[2].ToString());
     reqparm.Add("power1", power[0].ToString());
     reqparm.Add("power2", power[1].ToString());
     reqparm.Add("power3", power[2].ToString());
     reqparm.Add("startTime", startTime);
     reqparm.Add("elapsedTime", elapsedTime);
     reqparm.Add("status", status);
     reqparm.Add("brazeTime", brazeTime);
     reqparm.Add("brazeName", brazeName);
     reqparm.Add("latestStep", latestStep);
     reqparm.Add("mode", mode);
     reqparm.Add("logfile", mode);
     if (!bw.IsBusy)
     {
         bw.RunWorkerAsync(reqparm);
     }
 }
 public void uploadHistoryToWebServer()
 {
     System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
     reqparm.Add("startTime", startTime);
     reqparm.Add("elapsedTime", elapsedTime);
     reqparm.Add("status", status);
     reqparm.Add("brazeTime", brazeTime);
     reqparm.Add("brazeName", brazeName);
     reqparm.Add("latestStep", latestStep);
     reqparm.Add("mode", mode);
     reqparm.Add("logfile", mode);
     if (!bwh.IsBusy)
     {
         bwh.RunWorkerAsync(reqparm);
     }
 }
Esempio n. 23
0
        private static System.Collections.Specialized.NameValueCollection CheckEntityUpdateField(CurrentValueRecord entry)
        {
            System.Collections.Specialized.NameValueCollection returnResult = new System.Collections.Specialized.NameValueCollection(4);
              returnResult.Add("creator_id", "false");
              returnResult.Add("created_at", "false");
              returnResult.Add("updater_id", "false");
              returnResult.Add("updated_at", "false");

              foreach (var field in entry.DataRecordInfo.FieldMetadata)
              {
              switch (field.FieldType.Name)
              {
                  case "creator_id":
                  case "created_at":
                  case "updater_id":
                  case "updated_at":
                      returnResult[field.FieldType.Name] = "true";
                      break;
              }
              }

              return returnResult;
        }
Esempio n. 24
0
        /// <summary>
        /// Split DSN parameters
        /// </summary>
        /// <param name="dsn">DSN to split</param>
        /// <returns>Values</returns>
        public static System.Collections.Specialized.NameValueCollection SplitDsnParams(string dsn)
        {
            var arr = new System.Collections.Specialized.NameValueCollection();
            Match m = sm_regexDSNSplit.Match(dsn);
            while (m.Success)
            {
                string name = m.Groups["Keyword"].Value;
                string value = m.Groups["Vaue"].Value;

                arr.Add(name, value);
                m = m.NextMatch();
            }
            return arr;
        }
Esempio n. 25
0
        /// <summary>
        /// Updates the card field specified.
        /// </summary>
        /// <returns><c>true</c>, if card field was updated, <c>false</c> otherwise.</returns>
        /// <param name="authToken">Auth token, from SSA passed from mtgdb.info</param>
        /// <param name="mvid">Mvid.</param>
        /// <param name="field">Field.</param>
        /// <param name="value">Value.</param>
        public bool UpdateCardField(Guid authToken, int mvid, string field, string value)
        {
            bool end = false;

            using(WebClient client = new WebClient())
            {
                System.Collections.Specialized.NameValueCollection reqparm = 
                    new System.Collections.Specialized.NameValueCollection();
                    
                reqparm.Add("AuthToken", authToken.ToString());
                reqparm.Add("Field", field);
                reqparm.Add("Value", value);

                string responsebody = "";

                try
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                    byte[] responsebytes = 
                        client.UploadValues(string.Format("{0}/cards/{1}",_apiUrl, mvid), 
                            "Post", reqparm);

                    responsebody = Encoding.UTF8.GetString(responsebytes);

                }
                catch(WebException e) 
                {
                    throw e;
                }

                end = JsonConvert.DeserializeObject<bool>(responsebody);
            }

            return end;
        }
Esempio n. 26
0
        public String[] TestTcpClientCreation()
        {
            System.Collections.Specialized.NameValueCollection props =
                new System.Collections.Specialized.NameValueCollection();
            props.Add("port", "3131");

            using(MConnector connector = MConnectorFactory.CreateConnector( "provider:tcp:binary:test.rem", props ))
            {
                Assertion.AssertNotNull( connector );
                Assertion.AssertNotNull( connector.ServerConnection );

                MServer server = (MServer) connector.ServerConnection;
                Assertion.AssertNotNull( server.GetDomains() );
                return server.GetDomains();
            }
        }
 private static System.Collections.Specialized.NameValueCollection GenerateNvc(OauthMember m)
 {
     var nvc = new System.Collections.Specialized.NameValueCollection();
     nvc.Add("provider", m.Provider);
     nvc.Add("oauthId", m.OauthId);
     nvc.Add("accessToken", m.AccessToken);
     nvc.Add("firstName", m.FirstName);
     nvc.Add("lastName", m.LastName);
     nvc.Add("picture", m.Picture);
     return nvc;
 }
Esempio n. 28
0
        public void GetBanggoData()
        {
            System.Collections.Specialized.NameValueCollection nc =
                new System.Collections.Specialized.NameValueCollection();
            nc.Add("Host", "act.banggo.com");
            nc.Add("Connection", "keep-alive");
            nc.Add("Accept", "*/*");
            nc.Add("User-Agent",
                   "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
            nc.Add("Referer", "http://metersbonwe.banggo.com/Goods/238395.shtml");
            nc.Add("Accept-Encoding", "gzip,deflate,sdch");
            nc.Add("Accept-Language", "zh-CN,zh;q=0.8");
            nc.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            nc.Add("Cookie",
                   "stati_client_mark_code=1364310301869; PHPSESSID=fb3bc93284e0c7213c6711f91a38c60a; bg_uid=33a7f71a44e72aa2efad64724317ce56; bg_user_ip=8%7C118.113.147.218%7C%E5%9B%9B%E5%B7%9D%7C0%7C%E6%88%90%E9%83%BD%7C101270101%7C%E6%88%90%E9%83%BD%7C101270101; banggo_think_language=zh-CN; bg_time=1368356787; __utma=4343212.1532128941.1364310301.1368256305.1368351505.11; __utmb=4343212.11.10.1368351505; __utmc=4343212; __utmz=4343212.1368351505.11.3.utmcsr=search.banggo.com|utmccn=(referral)|utmcmd=referral|utmcct=/Search/a_22_a_a_a_a_a_a_a_a_a_a_a_a.shtml; NSC_58.215.174.167*80=ffffffff0958156645525d5f4f58455e445a4a423660");

               string result = HttpHelper.GETDataToUrl(
                "http://act.banggo.com/Ajax/cartAjax?time=0.4682253187056631&callback=jsonp1368356786991&ajaxtype=color_size&type=size&code=23852&r_code=91&goods_sn=238395",
                nc, System.Text.Encoding.UTF8);

            Console.WriteLine(result);
        }
Esempio n. 29
0
        //TODO:  Add in config section handlers for encryption
        public static System.Collections.Specialized.NameValueCollection GetQuartzConfig()
        {
            System.Collections.Specialized.NameValueCollection props = new System.Collections.Specialized.NameValueCollection();

            object oCAPSSection = System.Configuration.ConfigurationManager.AppSettings;
            foreach (string key in System.Configuration.ConfigurationManager.AppSettings.Keys)
            {
                if (key.StartsWith("quartz"))
                {
                    props.Add(key, System.Configuration.ConfigurationManager.AppSettings[key]);
                }
            }
            
            /*
            if (oCAPSSection is CAPSConfigSection)
            {
                ConfigurationElementCollection cec = ((CAPSConfigSection)oCAPSSection).ElementCollection;
                foreach (CAPSConfigSection.CAPSConfigElement el in cec)
                {
                    if (el.Key.StartsWith("quartz"))
                    {
                        props.Add(el.Key, el.Value);
                    }


                }

            }
            else if (oCAPSSection is CAPSEncryptedConfigSection)
            {
                ConfigurationElementCollection cec = ((CAPSEncryptedConfigSection)oCAPSSection).ElementCollection;
                foreach (CAPSEncryptedConfigElement el in cec)
                {
                    if (el.Key.StartsWith("quartz"))
                    {
                        props.Add(el.Key, el.Value);
                    }


                }
            }
             * */

            return props;
        }
Esempio n. 30
0
        public UrlAnalyzer(string url)
        {
            originalUrl = url;
            if (url.IndexOf("://") > 0) {
                Protocol = url.Substring(0, url.IndexOf("://"));
                Domain = url.Substring(Protocol.Length + 3, url.IndexOf("/", Protocol.Length + 3) - (Protocol.Length + 3));
                Site = Protocol + "://" + Domain + "/";
            } else {
                Protocol = string.Empty;
                Domain = url.Substring(0, url.IndexOf("/"));
                if (!string.IsNullOrEmpty(Domain)) {
                    Site = Domain;
                } else {
                    Site = "/";
                }
            }

            if (url.IndexOf('?') > 0) {
                HasParam = true;
                Path = url.Substring(Site.Length - 1, url.IndexOf('?') - Site.Length + 1);
                Param = url.Substring(url.IndexOf('?'));
                string[] temp = Param.Substring(1).Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                Params = new System.Collections.Specialized.NameValueCollection();
                for (int i = 0; i < temp.Length; i++) {
                    string _temp = System.Web.HttpUtility.UrlDecode(temp[i]);
                    int equalIndex = _temp.IndexOf('=');
                    string key, value;
                    if (equalIndex > 0) {
                        key = _temp.Substring(0, equalIndex);
                        value = _temp.Substring(equalIndex + 1);
                    } else {
                        key = _temp;
                        value = string.Empty;
                    }
                    Params.Add(key, value);
                }
            } else {
                HasParam = false;
                Path = url.Substring(Site.Length - 1);
                Param = string.Empty;
            }
            Dir = Path.Substring(0, Path.LastIndexOf('/') + 1);
            File = Path.Substring(Dir.Length);
        }
Esempio n. 31
0
        private static string UploadImage(string imageURL)
        {
            string    ClientId = "0ad329854c9fb71";
            WebClient w        = new WebClient();

            w.Headers.Add("Authorization", "Client-ID " + ClientId);
            System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection();
            try
            {
                Keys.Add("image", Convert.ToBase64String(File.ReadAllBytes(imageURL)));
                byte[]  responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys);
                dynamic result        = Encoding.ASCII.GetString(responseArray);
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("link\":\"(.*?)\"");
                Match  match = reg.Match(result);
                string url   = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/");
                return(url);
            }
            catch (Exception s)
            {
                WPFMessageBox.MessageBox.ShowWarning("Имахме проблем с качаването на изображението.\nМоля опитайте по-късно\n" + s.Message);
                return(null);
            }
        }
Esempio n. 32
0
 /// <summary>
 /// 同步培训平台人员素质意识值
 /// </summary>
 /// <param name="userid"></param>
 /// <param name="fileName"></param>
 public dynamic UpdatePoint(string userAccount)
 {
     try
     {
         var       trainserviceurl = new ERCHTMS.Busines.SystemManage.DataItemDetailBLL().GetItemValue("TrainServiceUrl");
         WebClient wc = new WebClient();
         wc.Credentials = CredentialCache.DefaultCredentials;
         //发送请求到web api并获取返回值,默认为post方式
         System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection();
         string queryJson = Newtonsoft.Json.JsonConvert.SerializeObject(new
         {
             Business    = "GetQualityObj",
             userAccount = userAccount
         });
         nc.Add("json", queryJson);
         byte[] arr = wc.UploadValues(new Uri(trainserviceurl), nc);
         return(JsonConvert.DeserializeObject <ExpandoObject>(System.Text.Encoding.Default.GetString(arr)));
     }
     catch (Exception e)
     {
         return(null);
     }
 }
Esempio n. 33
0
        public void getClientCredentialsAuthToken()
        {
            var spotifyClient = "secret";
            var spotifySecret = "secret";

            var webClient = new WebClient();

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

            postparams.Add("grant_type", "client_credentials");

            var authHeader = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes($"{spotifyClient}:{spotifySecret}"));

            webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authHeader);

            var tokenResponse = webClient.UploadValues("https://accounts.spotify.com/api/token", postparams);

            var    textResponse = Encoding.UTF8.GetString(tokenResponse);
            SpotAu au           = new SpotAu();

            au    = JsonConvert.DeserializeObject <SpotAu>(textResponse);
            token = au.access_token;
        }
Esempio n. 34
0
        private static NameValueCollection CopyCollection(HttpCookieCollection cookies)
        {
            if (cookies == null || cookies.Count == 0)
            {
                return(null);
            }

            NameValueCollection copy = new NameValueCollection(cookies.Count);

            for (int i = 0; i < cookies.Count; i++)
            {
                HttpCookie cookie = cookies[i];

                //
                // NOTE: We drop the Path and Domain properties of the
                // cookie for sake of simplicity.
                //

                copy.Add(cookie.Name, cookie.Value);
            }

            return(copy);
        }
Esempio n. 35
0
        private void backgroundWorkerSearch_DoWork(object sender, DoWorkEventArgs e)
        {
            string result = "";


            try
            {
                using (WebClient client = new WebClient())
                {
                    string srt = "";// manager.getCats();
                    if (srt == "")
                    {
                        var collection = new System.Collections.Specialized.NameValueCollection();
                        collection.Add("serial-number", "1111-1111-1111-1111");
                        byte[] response =
                            client.UploadValues("http://Arvandfile.com/api/v2/collections", collection);
                        result = System.Text.Encoding.UTF8.GetString(response);
                        manager.saveCats(result);
                        srt = result;
                    }



                    //CatsAndAreasObject CATS = new CatsAndAreasObject();
                    //CATS = JsonConvert.DeserializeObject<CatsAndAreasObject>(srt);
                    GlobalVariable.newCatsAndAreas = srt;
                }

                //this.Close();
            }
            catch (Exception eror)
            {
                e.Result = eror;
                // loadingIMG.Visible = false;
                backgroundWorkerSearch.CancelAsync();
            }
        }
Esempio n. 36
0
        /// <summary>
        /// 分析url链接,返回参数集合
        /// </summary>
        /// <param name="url">url链接</param>
        /// <param name="baseUrl"></param>
        /// <returns></returns>
        public static System.Collections.Specialized.NameValueCollection?ParseUrl(this string?url, out string?baseUrl)
        {
            baseUrl = "";
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            var nvc = new System.Collections.Specialized.NameValueCollection();

            try
            {
                var questionMarkIndex = url.IndexOf('?');

                if (questionMarkIndex == -1)
                {
                    baseUrl = url;
                    return(null);
                }
                baseUrl = url.Substring(0, questionMarkIndex);

                var ps = url.Substring(questionMarkIndex + 1);

                // 开始分析参数对
                var re = new System.Text.RegularExpressions.Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", System.Text.RegularExpressions.RegexOptions.Compiled);
                var mc = re.Matches(ps);

                foreach (System.Text.RegularExpressions.Match m in mc)
                {
                    nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
                }
            }
            catch
            {
                // ignored
            }
            return(nvc);
        }
Esempio n. 37
0
        /// <summary>
        /// HttpPost
        /// </summary>
        /// <param name="url"></param>
        /// <param name="vals"></param>
        /// <returns></returns>
        public virtual byte[] HttpPostByte(string url, List <KeyValue> vals)
        {
            if (ReportUrl)
            {
                ReportManage.Report(this, "POST " + url, true, true);
            }
            try
            {
                Sleep();
                wc.Referer            = referer;
                wc.UserAgent          = userAgent;
                wc.BasicAuthorization = BasicAuthorization;

                System.Collections.Specialized.NameValueCollection list = new System.Collections.Specialized.NameValueCollection();
                foreach (var item in vals)
                {
                    list.Add(item.Key, item.Value);
                }
                var data2 = wc.UploadValues(url, list);
                return(data2);
            }
            catch (Exception e)
            {
                if (visbleErr)
                {
                    ReportManage.ErrReport(this, "Url:" + url + " " + e.Message);
                }
                //if (e is System.UriFormatException)
                //{
                //    ReportManage.ErrReport(this,"["+url+"]は無効なURLです。");
                //}
                ErrMessage = e.Message;

                //                throw new Exception("HttpGet:"+url+"に失敗しました");
            }
            return(null);
        }
Esempio n. 38
0
        /// <summary>
        /// 提交Http数据
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="mothod">方式</param>
        /// <param name="parms">参数</param>
        /// <returns></returns>
        public static string PostHttpData(string url, string mothod, Dictionary <string, string> parms)
        {
            var wc = new WebClient();

            try
            {
                var PostVars = new System.Collections.Specialized.NameValueCollection();
                var uri      = new Uri(url);
                if (parms != null)
                {
                    foreach (var k in parms.Keys)
                    {
                        PostVars.Add(k, parms[k]);
                    }
                }
                var data     = wc.UploadValues(uri, mothod.ToUpper(), PostVars);
                var str_back = Encoding.UTF8.GetString(data);
                Console.WriteLine(str_back);
                return(str_back);
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    var sr = new StreamReader(ex.Response.GetResponseStream());
                    Loger.Error(sr.ReadToEnd());
                    sr.Close();
                }
                else
                {
                    Loger.Error(ex);
                }
                throw;
            }
            catch (Exception) { throw; }
            finally { wc.Dispose(); }
        }
 private System.Collections.Specialized.NameValueCollection GetAssemblyEventMapping(System.Reflection.Assembly assembly, Hl7Package package)
 {
     System.Collections.Specialized.NameValueCollection structures = new System.Collections.Specialized.NameValueCollection();
     using (System.IO.Stream inResource = assembly.GetManifestResourceStream(package.EventMappingResourceName))
     {
         if (inResource != null)
         {
             using (System.IO.StreamReader sr = new System.IO.StreamReader(inResource))
             {
                 string line = sr.ReadLine();
                 while (line != null)
                 {
                     if ((line.Length > 0) && ('#' != line[0]))
                     {
                         string[] lineElements = line.Split(' ', '\t');
                         structures.Add(lineElements[0], lineElements[1]);
                     }
                     line = sr.ReadLine();
                 }
             }
         }
     }
     return(structures);
 }
Esempio n. 40
0
        /*************************************************************************
        * Initialization
        *************************************************************************/

        /// <summary>
        /// Initialize the RoleProvider
        /// </summary>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "SnitzRoleProvider";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Snitz Role Provider");
            }

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

            _applicationName = GetConfigValue(config["applicationName"],
                                              System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
        }
Esempio n. 41
0
        void GenerateImage(object str)
        {
            MSG msg = (MSG)str;

            msg.message = msg.message.Replace(".decode ", "");
            WebClient wc = new WebClient();

            System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
            nvc.Add("url", msg.message);
            wc.Headers.Set(HttpRequestHeader.UserAgent, "buckey-11");
            string ret = Encoding.ASCII.GetString(wc.UploadValues("https://firebwall.com/decoding/index.php", "POST", nvc));

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<META HTTP-EQUIV=REFRESH CONTENT=\"1; URL=(?<URL>[^\"]+)\"");
            foreach (string line in ret.Split("\n".ToCharArray()))
            {
                if (regex.IsMatch(line))
                {
                    System.Text.RegularExpressions.Match m = regex.Match(line);
                    irc.SendMessage(msg.to, "Decoded at: " + m.Groups["URL"]);
                    return;
                }
            }
            irc.SendMessage(msg.to, "Failed to get decoded results");
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="name"></param>
        /// <param name="config"></param>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "LineNoiseAutoInputProtectionImageProvider";
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Line Noise Auto-Input Protection Image Provider");
            }

            VerificationCodeProviderHelper helper = new VerificationCodeProviderHelper(config);

            colors.AddRange(helper.ParseCollection <Color>("colors", false, true, false, ','));

            base.Initialize(name, config);

            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);

                if (!String.IsNullOrEmpty(attr))
                {
                    throw new ProviderException(string.Format(System.Globalization.CultureInfo.CurrentUICulture,
                                                              "Errors.UnrecognizedAttribute", attr));
                }
            }
        }
Esempio n. 43
0
        /// <summary>
        /// 获取人员来自培训平台培训档案
        /// </summary>
        /// <param name="userAccount"></param>
        /// <returns></returns>
        public string GetTrainRecord(string userId, string userAccount, string deptId, string idCard = "")
        {
            string fileName = "Train_" + DateTime.Now.ToString("yyyyMMdd") + ".log";

            try
            {
                if (string.IsNullOrEmpty(deptId))
                {
                    object obj = BaseRepository().FindObject(string.Format("select px_deptid from XSS_USER  where userid='{0}'", userId));
                    if (obj != null)
                    {
                        deptId = obj.ToString();
                    }
                    else
                    {
                        return("");
                    }
                }
                WebClient wc = new WebClient();
                wc.Credentials = CredentialCache.DefaultCredentials;
                wc.Headers.Add("Content-Type", "text/json; charset=utf-8");
                System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection();
                //发送请求到web api并获取返回值,默认为post方式
                string url  = new DataItemDetailService().GetItemValue("TrainServiceUrl");
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { business = "GetTrainRecord", idcard = idCard, DeptId = deptId, userAccount = userAccount });
                nc.Add("json", json);
                string result = wc.DownloadString(new Uri(url + "?json=" + json));
                System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/logs/" + fileName), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :获取人员培训档案,远程服务器返回信息:" + result + "\r\n");
                return(result);
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/logs/" + fileName), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :获取人员培训档案异常,信息:" + ex.Message + "\r\n");
                return("");
            }
        }
        public void Add_CheckReturnsEntity()
        {
            // Arrange
            var entity = new Stuff {
                StuffId = 99, One = "Brand New"
            };

            var stuff = CollectionHelpers.GetStandardStuffList().AsQueryable();

            MockHelpers.SetUpMockStuffSet(_dbContext, stuff, entity);

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

            tokenHeader.Add("ApiToken", "foo");
            _httpContext.Setup(h => h.Request.Headers).Returns(tokenHeader);

            // Act
            var result = _repository.Add(entity);

            // Assert
            Assert.True(result != null);
            Assert.Equal(entity.StuffId, result.StuffId);
            Assert.Equal("foo", result.EntityOwner);
        }
        protected override bool OnBeforePopup(CefBrowser browser, CefFrame frame, string targetUrl, string targetFrameName, CefPopupFeatures popupFeatures, CefWindowInfo windowInfo, ref CefClient client, CefBrowserSettings settings, ref bool noJavascriptAccess)
        {
            bool res = false;

            if (!string.IsNullOrEmpty(targetUrl))
            {
                if (webBrowser.selfRequest != null)
                {
                    CefRequest req = CefRequest.Create();
                    req.FirstPartyForCookies = webBrowser.selfRequest.FirstPartyForCookies;
                    req.Options = webBrowser.selfRequest.Options;

                    /*CefPostData postData = CefPostData.Create();
                     * CefPostDataElement element = CefPostDataElement.Create();
                     * int index = targetUrl.IndexOf("?");
                     * string url = targetUrl.Substring(0, index);
                     * string data = targetUrl.Substring(index + 1);
                     * byte[] bytes = Encoding.UTF8.GetBytes(data);
                     * element.SetToBytes(bytes);
                     * postData.Add(element);
                     */
                    System.Collections.Specialized.NameValueCollection h = new System.Collections.Specialized.NameValueCollection();
                    h.Add("Content-Type", "application/x-www-form-urlencoded");
                    req.Set(targetUrl, webBrowser.selfRequest.Method, null, webBrowser.selfRequest.GetHeaderMap());
                    webBrowser.selfRequest = req;
                }
                //webBrowser.selfRequest.Set(targetUrl, webBrowser.selfRequest.Method, webBrowser.selfRequest.PostData, webBrowser.selfRequest.GetHeaderMap());
                res = webBrowser.OnNewWindow(targetUrl);
                if (res)
                {
                    return(res);
                }
            }
            res = base.OnBeforePopup(browser, frame, targetUrl, targetFrameName, popupFeatures, windowInfo, ref client, settings, ref noJavascriptAccess);
            return(res);
        }
Esempio n. 46
0
 private static void Add(string controlName, string assembly, string classFullName)
 {
     assembly = Xy.AppSetting.BinDir + assembly + ".dll";
     if (!_assemblies.Contains(assembly))
     {
         _assemblies.Add(assembly);
     }
     switch (controlName)
     {
     case "Procedure":
     case "Data":
     case "Request":
     case "XML":
         throw new Exception("\"Procedure\", \"Data\", \"Request\", \"XML\" are XYFrame default data builder " + controlName);
     }
     if (string.IsNullOrEmpty(_dataBuilders[controlName]))
     {
         _dataBuilders.Add(controlName, classFullName);
     }
     else
     {
         throw new Exception("already has a data builder named " + controlName);
     }
 }
Esempio n. 47
0
        /// <summary>
        /// Sends a port request to url with parameters and values
        /// </summary>
        public static string WebRequest(string url, List <string> postParams, List <string> postValues)
        {
            if (url == null || url.Length == 0)
            {
                throw new ApplicationException("Specify the URI of the resource to retrieve.");
            }
            WebClient client = new WebClient();

            // Add a user agent header in case the
            // requested URI contains a query.

            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            var _postParams = new System.Collections.Specialized.NameValueCollection();

            for (int i = 0; i < postParams.Count; i++)
            {
                _postParams.Add(postParams[i], postValues[i]);
            }
            byte[] responsebytes = client.UploadValues(url, "POST", _postParams);

            string responsebody = Encoding.UTF8.GetString(responsebytes);

            return(responsebody);
        }
Esempio n. 48
0
 public string Post()
 {
     using (WebClient wc = new WebClient())
     {
         string post_url = this._Article.Article_uri +
                           "YediothPortal/Ext/TalkBack/CdaTalkBackTrans/0,2499," +
                           this._Article.Article_id +
                           "-0-68-546-0---0,00.html";
         var reqparm = new System.Collections.Specialized.NameValueCollection();
         reqparm.Add("WSGBRWSR", "FF");
         reqparm.Add("name", this.Name);
         reqparm.Add("email", this.Email);
         reqparm.Add("Location", this.Location);
         reqparm.Add("title", this.Title);
         reqparm.Add("description", this.Text);
         byte[] responsebytes = wc.UploadValues(post_url, "POST", reqparm);
         return(Encoding.UTF8.GetString(responsebytes));
     }
 }
Esempio n. 49
0
        public static System.Collections.Specialized.NameValueCollection GetTimeHTTPHeaders()
        {
            TimeSpan timeTotal  = GetGlobalTime();
            TimeSpan timeData   = GetDataTime();
            TimeSpan timeOther  = timeTotal - timeData;
            TimeSpan timeCustom = GetCustomTime();

            System.Collections.Specialized.NameValueCollection objHeaders = new System.Collections.Specialized.NameValueCollection();
            objHeaders.Add("Debug-Database-Time", Math.Round(timeData.TotalMilliseconds, 0).ToString());
            objHeaders.Add("Debug-Database-Requests", _intDataRequestCount.ToString());
            objHeaders.Add("Debug-Server-Time", Math.Round(timeOther.TotalMilliseconds, 0).ToString());
            if (timeCustom.TotalMilliseconds > 0)
            {
                objHeaders.Add("Debug-Custom-Time", Math.Round(timeCustom.TotalMilliseconds, 0).ToString());
            }
            objHeaders.Add("Debug-Transmission-Start", ParseTimeString(DateTime.Now));
            objHeaders.Add("Debug-Total-Time", ParseTimeString(timeTotal));
            return(objHeaders);
        }
Esempio n. 50
0
        private void btnTemplate_Click(object sender, EventArgs e)
        {
            var kv = new System.Collections.Specialized.NameValueCollection();

            kv.Add("OwnerId", "14263");
            kv.Add("Caption", "关于请求下拨网络安全工作经费的请示");
            kv.Add("Extension", "docx");
            kv.Add("To", "校领导");
            kv.Add("From", "信息化办公室");
            kv.Add("Template", "xngw");

            var fid = Encoding.UTF8.GetString(client.UploadValues(
                                                  String.Format("http://{0}/api/documents/create", tbServer.Text.Trim()),
                                                  kv));

            //client.UploadData(String.Format("http://{0}/api/documents/{1}/contents", tbServer.Text.Trim(), fid), bytes);

            lbFile.Items.Add(fid);
        }
Esempio n. 51
0
        public IActionResult Get()
        {
            string code = Request.Query["code"];

            if (code == null)
            {
                return(new BadRequestResult());
            }

            WebClient client = new WebClient();

            client.Headers.Clear();
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var reqparm = new System.Collections.Specialized.NameValueCollection();

            reqparm.Add("grant_type", "authorization_code");
            reqparm.Add("code", code);
            reqparm.Add("redirect_uri", Core.GlobalConfig.RedirectUri);
            reqparm.Add("client_id", Core.GlobalConfig.OAuthClientId);
            reqparm.Add("client_secret", Core.GlobalConfig.OAuthClientSecret);
            reqparm.Add("scope", "guilds identify");

            try
            {
                byte[] responsebytes = client.UploadValues("https://discordapp.com/api/v6/oauth2/token", "POST", reqparm);
                string responsebody  = Encoding.UTF8.GetString(responsebytes);
                var    responseType  = new
                {
                    access_token = "",
                };
                return(new OkObjectResult(JsonConvert.DeserializeAnonymousType(responsebody, responseType).access_token));
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex));
            }

            return(new BadRequestResult());
        }
Esempio n. 52
0
        protected void ButtonConfirm1_Click(object sender, EventArgs e)
        {
            string xml = string.Empty;

            using (WebClient client = new WebClient())
            {
                var parametros = new System.Collections.Specialized.NameValueCollection();
                parametros.Add("modo", "M");
                parametros.Add("id", tarefa);
                parametros.Add("status", NewStatus.Text);
                parametros.Add("descricao", NewDescription.Text);
                parametros.Add("realizado", NewRealized.Text);
                parametros.Add("atividade", atividade);
                byte[] resposta = client.UploadValues(Request.Url.Scheme + "://localhost:" + Request.Url.Port + "/tarefa_cadastro.ashx", "POST", parametros);
                xml = Encoding.UTF8.GetString(resposta);
            }
            if (!xml.Contains("<mensagem") && xml.Contains("<id>"))
            {
                Response.Clear();
                StringBuilder formPost = new StringBuilder();
                formPost.Append("<html>");
                formPost.AppendFormat(@"<body onload=""document.forms['form'].submit()"">");
                formPost.AppendFormat(@"<form name=""form"" action=""{0}"" method=""post"">", "tarefa.aspx");
                formPost.AppendFormat(@"<input type=""hidden"" name=""pacote"" value=""{0}"">", pacote);
                formPost.AppendFormat(@"<input type=""hidden"" name=""atividade"" value=""{0}"">", atividade);
                formPost.Append("</form>");
                formPost.Append("</body>");
                formPost.Append("</html>");
                Response.Write(formPost.ToString());
                Response.End();
            }
            else
            {
                mensagem = string.Format(Application["MensagemErro"].ToString(), "Tarefa não cadastrada.");
            }
        }
Esempio n. 53
0
        public async Task <object> itexmo(string Number, string Message, string API_CODE = "", string SenderID = "", string Password = "", Boolean isImportant = false)
        {
            object functionReturnValue = null;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                System.Collections.Specialized.NameValueCollection parameter = new System.Collections.Specialized.NameValueCollection();
                string url = _configuration["ItextMo:Url"];
                parameter.Add("1", Number);
                parameter.Add("2", Message);
                parameter.Add("3", _configuration["ItextMo:APICode"]);
                parameter.Add("6", _configuration["ItextMo:SenderID"]);
                parameter.Add("passwd", _configuration["ItextMo:Secret"]);

                if (isImportant)
                {
                    parameter.Add("5", "HIGH");
                }

                dynamic rpb = client.UploadValues(url, "POST", parameter);
                functionReturnValue = (new System.Text.UTF8Encoding()).GetString(rpb);
            }
            return(await Task.FromResult(functionReturnValue));
        }
 public void Add(string name, string value)
 {
     Inputs.Add(name, value);
 }
Esempio n. 55
0
        /// <summary>
        /// 同步用户
        /// </summary>
        public bool ErchtmsSynchronoous(string type, object o, string account)
        {
            var baseUrl = Config.GetValue("ErchtmsApiUrl");

            if (Config.GetValue("SyncBool") == "f")
            {
                return(true);
            }

            string    id = "";
            WebClient wc = new WebClient();

            wc.Credentials = CredentialCache.DefaultCredentials;
            //发送请求到web api并获取返回值,默认为post方式
            try
            {
                System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection();
                if (type == "SaveUser")
                {
                    UserEntity user = (UserEntity)o;
                    id = user.UserId;
                    nc.Add("account", account);
                    nc.Add("json", Newtonsoft.Json.JsonConvert.SerializeObject(user));
                }
                else if (type == "SaveDept")
                {
                    DepartmentEntity d = (DepartmentEntity)o;
                    id = d.DepartmentId;
                    nc.Add("account", BSFramework.Application.Code.OperatorProvider.Provider.Current().Account);
                    nc.Add("json", Newtonsoft.Json.JsonConvert.SerializeObject(d));
                }
                else if (type == "SaveRole")
                {
                    RoleEntity r = (RoleEntity)o;
                    id = r.RoleId;
                    nc.Add("account", BSFramework.Application.Code.OperatorProvider.Provider.Current().Account);
                    nc.Add("json", Newtonsoft.Json.JsonConvert.SerializeObject(r));
                }
                if (type == "DeleteUser")
                {
                    UserEntity user = (UserEntity)o;
                    id = user.UserId;
                    nc.Add("account", account);
                    nc.Add("json", Newtonsoft.Json.JsonConvert.SerializeObject(user));
                }
                else if (type == "DeleteDept")
                {
                    DepartmentEntity d = (DepartmentEntity)o;
                    id = d.DepartmentId;
                    nc.Add("account", BSFramework.Application.Code.OperatorProvider.Provider.Current().Account);
                    nc.Add("json", Newtonsoft.Json.JsonConvert.SerializeObject(d));
                }
                else if (type == "DeleteRole")
                {
                    RoleEntity r = (RoleEntity)o;
                    id = r.RoleId;
                    nc.Add("account", BSFramework.Application.Code.OperatorProvider.Provider.Current().Account);
                    nc.Add("json", Newtonsoft.Json.JsonConvert.SerializeObject(r));
                }
                else if (type == "UpdatePwd")
                {
                    string[] r = (string[])o;
                    nc.Add("userId", r[0]);
                    nc.Add("pwd", r[1]);
                    string path = baseUrl + "syncdata/" + type + "?userId=" + r[0] + "&pwd=" + r[1];
                    wc.UploadValuesCompleted += wc_UploadValuesCompleted;
                    wc.UploadValuesAsync(new Uri(path), nc);
                    return(true);
                }


                wc.UploadValuesCompleted += wc_UploadValuesCompleted;
                string a = baseUrl + "syncdata/" + type + "?keyValue=" + id;
                wc.UploadValuesAsync(new Uri(baseUrl + "syncdata/" + type + "?keyValue=" + id), nc);
            }
            catch (Exception ex)
            {
                //将同步结果写入日志文件
                string fileName = DateTime.Now.ToString("yyyyMMdd") + ".log";
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~/logs")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/logs"));
                }

                System.IO.File.AppendAllText(System.Web.HttpContext.Current.Server.MapPath("~/logs/" + fileName), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":同步数据失败,同步信息" + Newtonsoft.Json.JsonConvert.SerializeObject(o) + ",异常信息:" + ex.Message + "\r\n");
                return(false);
            }
            return(true);
        }
Esempio n. 56
0
        public static string sendPost(string url, string sign)
        {
            //发送数据
            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("merchantCode", merchantCode);
            PostVars.Add("outOrderId", outOrderId);
            PostVars.Add("bankCode", "");
            PostVars.Add("bankName", "");
            PostVars.Add("intoCardName", intoCardName);
            PostVars.Add("intoCardNo", intoCardNo);
            PostVars.Add("intoCardType", intoCardType);
            PostVars.Add("nonceStr", nonceStr);
            PostVars.Add("totalAmount", totalAmount);
            PostVars.Add("type", type);
            PostVars.Add("sign", sign);
            PostVars.Add("notifyUrl", notifyUrl);

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
                string sRemoteInfo  = System.Text.Encoding.Default.GetString(byRemoteInfo);
                //这是获取返回信息
                return(sRemoteInfo);
            }
            catch
            { }
            return("no response");
        }
Esempio n. 57
0
 public void InitializeBrokerProvider()  //amit 18052017
 {
     try
     {
         brokerMemProvider = new BrokerMembershipProvider();
         System.Web.Security.SqlMembershipProvider          ObjSqlMembershipProvider   = new System.Web.Security.SqlMembershipProvider();
         System.Web.Security.SqlRoleProvider                ObjSqlRoleProvider         = new System.Web.Security.SqlRoleProvider();
         System.Collections.Specialized.NameValueCollection ObjNameValueCollRole       = new System.Collections.Specialized.NameValueCollection();
         System.Collections.Specialized.NameValueCollection ObjNameValueCollMembership = new System.Collections.Specialized.NameValueCollection();
         System.Web.Security.MembershipCreateStatus         enMembershipCreateStatus;
         ObjNameValueCollMembership.Add("connectionStringName", "SqlMembershipConn");
         ObjNameValueCollMembership.Add("applicationName", "AMS.Broker.WatchDogService");
         //these items are assumed to be Default and dont care..Should be given a look later stage.
         ObjNameValueCollMembership.Add("enablePasswordRetrieval", "false");
         ObjNameValueCollMembership.Add("enablePasswordReset", "false");
         ObjNameValueCollMembership.Add("requiresQuestionAndAnswer", "false");
         ObjNameValueCollMembership.Add("requiresUniqueEmail", "false");
         ObjNameValueCollMembership.Add("passwordFormat", "Hashed");
         ObjNameValueCollMembership.Add("maxInvalidPasswordAttempts", "5");
         ObjNameValueCollMembership.Add("minRequiredPasswordLength", "1");
         ObjNameValueCollMembership.Add("minRequiredNonalphanumericCharacters", "0");
         ObjNameValueCollMembership.Add("passwordAttemptWindow", "10");
         ObjNameValueCollMembership.Add("passwordStrengthRegularExpression", "");
         // ObjSqlMembershipProvider.Initialize("AspNetSqlMembershipProvider", ObjNameValueCollMembership);
         //System.Web.Security.MembershipUser user = ObjSqlMembershipProvider.CreateUser("admin,"password","*****@*****.**");
         //hard coded the Provider Name,This function just need one that is present. I tried other names and it throws error. I found this using Reflector ..all the rest are take care by the above
         //name value pairs
         brokerMemProvider.Initialize("BrokerMembershipProvider", ObjNameValueCollMembership);
     }
     catch (Exception ex)
     {
     }
 }
Esempio n. 58
0
        private void cmdReport_Click(object sender, System.EventArgs e)
        {
            if (this.txtName.Text.Trim() == "")
            {
                MessageBox.Show(this, "Please fill in your name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (this.txtEMail.Text.Trim() == "")
            {
                MessageBox.Show(this, "Please fill in your e-mail address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (this.cboReproducable.SelectedIndex == -1)
            {
                MessageBox.Show(this, "Please select a reproducability type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (this.txtDescr.Text.Trim() == "")
            {
                MessageBox.Show(this, "Please fill in any steps to reproduce this error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // We're sending all of this data to the TorqueDev website
            this.cmdReport.Enabled = false;
            this.Refresh();

            WebClient wc = new WebClient();

            System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();

            nvc.Add("email", this.txtEMail.Text);
            nvc.Add("name", this.txtName.Text);
            nvc.Add("repro", this.cboReproducable.Text);
            nvc.Add("descr", this.txtDescr.Text);
            nvc.Add("e_msg", this.ThrownExc.Message);
            nvc.Add("e_stack", this.ThrownExc.StackTrace);
            nvc.Add("e_source", this.ThrownExc.Source);
            nvc.Add("misc",
                    "sp: " + Application.StartupPath + "\n" +
                    "cp: " + System.IO.Directory.GetCurrentDirectory() + "\n" +
                    "pr: " +
                    ((g.Project == null) ? "{none open}" : g.Project.ProjectName + " / " +
                     g.Project.ProjectPath + " / " + g.Project.ProjectType.ToString()) + "\n" +
                    "fm: " + ((g.Main != null) ? g.Main.Text : "{null}") + "\n" +
                    "vr: " + Application.ProductVersion + "\n"
                    );

            if (this.ThrownExc.InnerException != null)
            {
                nvc.Add("ei_msg", this.ThrownExc.InnerException.Message);
                nvc.Add("ei_stack", this.ThrownExc.InnerException.StackTrace);
                nvc.Add("ei_source", this.ThrownExc.InnerException.Source);
            }

            // Upload the data
            try {
                wc.QueryString.Add("op", "report");
                wc.UploadValues("http://www.torquedev.com/_client/report_exception.php", "POST", nvc);
            } catch {
                MessageBox.Show(this, "Unable to contact the TorqueDev website to report this exception.  Please visit www.torquedev.com and click on the \"Bug Reports\" link at the top to report this error.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.cmdReport.Enabled = true;
                return;
            }

            // Say we've succeeded
            MessageBox.Show(this,
                            "Thank you for your report!\n\n" +
                            "If this problem keeps occuring, filing a bug report on the bug report system at www.torquedev.com" +
                            " would be helpful to us.\n\n" +
                            "Clicking 'OK' will shut down the program.  Sorry for any inconvenience this may have caused.", "Report Successful",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);

            this.Close();
        }
        /// <summary>
        /// Initialise the session state store.
        /// </summary>
        /// <param name="name">session state store name. Defaults to "MongoSessionStateStore" if not supplied</param>
        /// <param name="config">configuration settings</param>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            // Initialize values from web.config.
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (name.Length == 0)
            {
                name = "MongoSessionStateStore";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "MongoDB Session State Store provider");
            }

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

            // Initialize the ApplicationName property.
            _applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            // Get <sessionState> configuration element.
            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);

            _config = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            // Initialize connection string.
            _connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

            if (_connectionStringSettings == null || _connectionStringSettings.ConnectionString.Trim() == "")
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            _connectionString = _connectionStringSettings.ConnectionString;

            // Initialize WriteExceptionsToEventLog
            _writeExceptionsToEventLog = false;

            if (config["writeExceptionsToEventLog"] != null)
            {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
                {
                    _writeExceptionsToEventLog = true;
                }
            }


            // Write concern options j (journal) and w (write ack #)

            bool journal = false;

            //if (config["Journal"] != null)
            //{
            //    if (!bool.TryParse(config["Journal"], out journal))
            //        throw new Exception("Journal must be a valid value (true or false)");

            //    if (journal)
            //        _writeConcern = WriteConcern.WMajority;
            //}

            // If journal (j) is true, write ack # param (w) not applies.
            // Only the primary node will confirm the journal writing

            if (!journal)
            {
                _writeConcern = WriteConcern.W1;
                if (config["WriteConcern"] != null)
                {
                    string WCStr = config["WriteConcern"];
                    WCStr = WCStr.ToUpper();
                    switch (WCStr)
                    {
                    case "W1":
                        _writeConcern = WriteConcern.W1;
                        break;

                    case "W2":
                        _writeConcern = WriteConcern.W2;
                        break;

                    case "W3":
                        _writeConcern = WriteConcern.W3;
                        break;

                    //case "W4":
                    //    _writeConcern = WriteConcern.W4;
                    //    break;
                    case "WMAJORITY":
                        _writeConcern = WriteConcern.WMajority;
                        break;

                    default:
                        throw new Exception("WriteConcern must be a valid value W1, W2, W3 or WMAJORITY");
                    }
                }
            }

            // Initialize maxUpsertAttempts
            _maxUpsertAttempts = 220;
            if (config["maxUpsertAttempts"] != null)
            {
                if (!int.TryParse(config["maxUpsertAttempts"], out _maxUpsertAttempts))
                {
                    throw new Exception("maxUpsertAttempts must be a valid integer");
                }
            }

            //initialize msWaitingForAttempt
            _msWaitingForAttempt = 500;
            if (config["msWaitingForAttempt"] != null)
            {
                if (!int.TryParse(config["msWaitingForAttempt"], out _msWaitingForAttempt))
                {
                    throw new Exception("msWaitingForAttempt must be a valid integer");
                }
            }

            //Initialize AutoCreateTTLIndex
            _autoCreateTTLIndex = true;
            if (config["AutoCreateTTLIndex"] != null)
            {
                if (!bool.TryParse(config["AutoCreateTTLIndex"], out _autoCreateTTLIndex))
                {
                    throw new Exception("AutoCreateTTLIndex must be true or false");
                }
            }

            //Create TTL index if AutoCreateTTLIndex config parameter is true.
            if (_autoCreateTTLIndex)
            {
                var conn = GetConnection();
                var sessionCollection = GetSessionCollection(conn);
                MongoSessionStateStoreHelpers.CreateTTLIndex(sessionCollection);
            }
        }
        //public int ExtractData(NetworkTcpSession tcpSession, NetworkHost sourceHost, NetworkHost destinationHost, IEnumerable<Packets.AbstractPacket> packetList) {
        public int ExtractData(NetworkTcpSession tcpSession, bool transferIsClientToServer, IEnumerable <PacketParser.Packets.AbstractPacket> packetList)
        {
            /*
             * NetworkHost sourceHost, destinationHost;
             * if (transferIsClientToServer) {
             *  sourceHost = tcpSession.Flow.FiveTuple.ClientHost;
             *  destinationHost = tcpSession.Flow.FiveTuple.ServerHost;
             * }
             * else {
             *  sourceHost = tcpSession.Flow.FiveTuple.ServerHost;
             *  destinationHost = tcpSession.Flow.FiveTuple.ClientHost;
             * }*/

            Packets.TcpPacket tcpPacket = null;
            Packets.FtpPacket ftpPacket = null;

            foreach (Packets.AbstractPacket p in packetList)
            {
                if (p.GetType() == typeof(Packets.TcpPacket))
                {
                    tcpPacket = (Packets.TcpPacket)p;
                }
                else if (p.GetType() == typeof(Packets.FtpPacket))
                {
                    ftpPacket = (Packets.FtpPacket)p;
                }
            }

            FtpSession ftpSession = null;//we can only have one FtpSession per packet...
            //bool returnValue=false;
            int parsedBytes = 0;


            if (tcpSession.SynPacketReceived && tcpSession.SynAckPacketReceived)
            {
                //start by checking if this is an incoming file transfer through FTP
                if (!tcpSession.SessionEstablished)
                {
                    //we now have an upcoming session

                    //see if it matches the pending FTP data sessions
                    if (this.pendingFileTransferList.ContainsKey(PendingFileTransfer.GetKey(tcpSession.ClientHost, tcpSession.ClientTcpPort, tcpSession.ServerHost, tcpSession.ServerTcpPort)))
                    {
                        PendingFileTransfer pending = this.pendingFileTransferList[PendingFileTransfer.GetKey(tcpSession.ClientHost, tcpSession.ClientTcpPort, tcpSession.ServerHost, tcpSession.ServerTcpPort)];
                        pending.FileTransferSessionEstablished = true;
                        ftpSession = pending.FtpControlSession;
                        //returnValue=true;//we managed to get some data out of this!
                        parsedBytes = tcpPacket.PayloadDataLength;
                    }
                    //see if the client port was unknown
                    else if (this.pendingFileTransferList.ContainsKey(PendingFileTransfer.GetKey(tcpSession.ClientHost, null, tcpSession.ServerHost, tcpSession.ServerTcpPort)))
                    {
                        PendingFileTransfer pending = this.pendingFileTransferList[PendingFileTransfer.GetKey(tcpSession.ClientHost, null, tcpSession.ServerHost, tcpSession.ServerTcpPort)];
                        this.pendingFileTransferList.Remove(pending.GetKey());
                        pending.DataSessionClientPort          = tcpSession.ClientTcpPort;//the Key will now be changed!
                        pending.FileTransferSessionEstablished = true;
                        this.pendingFileTransferList.Add(pending.GetKey(), pending);
                        ftpSession = pending.FtpControlSession;
                        //returnValue=true;
                        parsedBytes = tcpPacket.PayloadDataLength;
                    }
                }//end check for new FTP DATA sessions
                else if (tcpPacket != null && tcpPacket.FlagBits.Fin)
                {
                    //check if there is an FTP data session being closed
                    if (this.MainPacketHandler.FileStreamAssemblerList.ContainsAssembler(tcpSession.Flow.FiveTuple, transferIsClientToServer, true, PacketParser.FileTransfer.FileStreamTypes.FTP))
                    {
                        PacketParser.FileTransfer.FileStreamAssembler assembler = this.MainPacketHandler.FileStreamAssemblerList.GetAssembler(tcpSession.Flow.FiveTuple, transferIsClientToServer);
                        if (assembler.FileContentLength == -1 && assembler.FileSegmentRemainingBytes == -1)
                        {
                            //TODO: see if all data has been received or if the FIN arrived before the final data packet
                            assembler.FinishAssembling();
                        }
                    }
                }
            }

            if (ftpPacket != null && tcpPacket != null)
            {
                //returnValue=true;
                parsedBytes = ftpPacket.PacketLength;

                if (ftpSessionList.ContainsKey(tcpSession))
                {
                    ftpSession = ftpSessionList[tcpSession];
                }
                else
                {
                    ftpSession = new FtpSession(tcpSession.ClientHost, tcpSession.ServerHost);
                    this.ftpSessionList.Add(tcpSession, ftpSession);
                }

                /*
                 * NetworkHost sourceHost, destinationHost;
                 * if (transferIsClientToServer) {
                 *  sourceHost = tcpSession.Flow.FiveTuple.ClientHost;
                 *  destinationHost = tcpSession.Flow.FiveTuple.ServerHost;
                 * }
                 * else {
                 *  sourceHost = tcpSession.Flow.FiveTuple.ServerHost;
                 *  destinationHost = tcpSession.Flow.FiveTuple.ClientHost;
                 * }
                 */
                if (ftpPacket.ClientToServer)
                {
                    if (ftpPacket.RequestCommand != null)
                    {
                        if (ftpPacket.RequestArgument != null)
                        {
                            System.Collections.Specialized.NameValueCollection tmpCol = new System.Collections.Specialized.NameValueCollection();
                            tmpCol.Add(ftpPacket.RequestCommand, ftpPacket.RequestArgument);
                            base.MainPacketHandler.OnParametersDetected(new Events.ParametersEventArgs(ftpPacket.ParentFrame.FrameNumber, tcpSession.Flow.FiveTuple, transferIsClientToServer, tmpCol, ftpPacket.ParentFrame.Timestamp, "FTP Request"));
                        }
                        if (ftpPacket.RequestCommand.ToUpper() == "USER")//username
                        {
                            ftpSession.Username = ftpPacket.RequestArgument;
                        }
                        else if (ftpPacket.RequestCommand.ToUpper() == "PASS")//password
                        {
                            ftpSession.Password = ftpPacket.RequestArgument;
                            if (ftpSession.Username != null && ftpSession.Password != null)
                            {
                                base.MainPacketHandler.AddCredential(new NetworkCredential(tcpSession.ClientHost, tcpSession.ServerHost, ftpPacket.PacketTypeDescription, ftpSession.Username, ftpSession.Password, ftpPacket.ParentFrame.Timestamp));
                            }
                        }
                        else if (ftpPacket.RequestCommand.ToUpper() == "PORT")
                        {
                            ushort clientListeningOnPort;
                            if (TryGetPort(ftpPacket.RequestArgument, out clientListeningOnPort))
                            {
                                //ftpSession.ActiveMode=true;
                                //ftpSession.ClientDataListenerTcpPort=this.GetPort(ftpPacket.RequestArgument);

                                //ftpSession.PendingFileTransfer=new PendingFileTransfer(ftpSession.ServerHost, (ushort)20, ftpSession.ClientHost, clientListeningOnPort, false, ftpSession);
                                ftpSession.PendingFileTransfer = new PendingFileTransfer(ftpSession.ServerHost, null, ftpSession.ClientHost, clientListeningOnPort, false, ftpSession);
                                if (this.pendingFileTransferList.ContainsKey(ftpSession.PendingFileTransfer.GetKey()))
                                {
                                    this.pendingFileTransferList.Remove(ftpSession.PendingFileTransfer.GetKey());
                                }
                                this.pendingFileTransferList.Add(ftpSession.PendingFileTransfer.GetKey(), ftpSession.PendingFileTransfer);
                            }
                        }
                        else if (ftpPacket.RequestCommand.ToUpper() == "STOR")//file upload (client -> server)

                        //set filename and file direction
                        {
                            if (ftpSession.PendingFileTransfer != null)
                            {
                                ftpSession.PendingFileTransfer.Filename = ftpPacket.RequestArgument;
                                ftpSession.PendingFileTransfer.FileDirectionIsDataSessionServerToDataSessionClient = !ftpSession.PendingFileTransfer.DataSessionIsPassive;
                                ftpSession.PendingFileTransfer.Details = ftpPacket.RequestCommand + " " + ftpPacket.RequestArgument;
                            }
                            else
                            {
                                //ftpPacket.ParentFrame.Errors.Add(new Frame.Error(ftpPacket.ParentFrame, ftpPacket.PacketStartIndex, ftpPacket.PacketEndIndex, "STOR command without a pending ftp data session"));
                                this.MainPacketHandler.OnAnomalyDetected("STOR command without a pending ftp data session. Frame: " + ftpPacket.ParentFrame.ToString(), ftpPacket.ParentFrame.Timestamp);
                                //System.Diagnostics.Debugger.Break();//this should not occur!
                            }
                        }
                        else if (ftpPacket.RequestCommand.ToUpper() == "RETR")//file download (server -> client)
                        {
                            if (ftpSession.PendingFileTransfer != null)
                            {
                                ftpSession.PendingFileTransfer.Filename = ftpPacket.RequestArgument;
                                ftpSession.PendingFileTransfer.FileDirectionIsDataSessionServerToDataSessionClient = ftpSession.PendingFileTransfer.DataSessionIsPassive;
                                ftpSession.PendingFileTransfer.Details = ftpPacket.RequestCommand + " " + ftpPacket.RequestArgument;
                            }
                            else
                            {
                                //System.Diagnostics.Debugger.Break();//this should not iccur
                                //ftpPacket.ParentFrame.Errors.Add(new Frame.Error(ftpPacket.ParentFrame, ftpPacket.PacketStartIndex, ftpPacket.PacketEndIndex, "RETR command without a pending ftp data session"));
                                this.MainPacketHandler.OnAnomalyDetected("RETR command without a pending ftp data session. Frame: " + ftpPacket.ParentFrame.ToString(), ftpPacket.ParentFrame.Timestamp);
                            }
                        }
                        else if (ftpPacket.RequestCommand.ToUpper() == "SIZE")
                        {
                            ftpSession.PendingSizeRequestFileName = ftpPacket.RequestArgument;
                        }
                    }
                }
                else  //server to client packet
                {
                    if (ftpPacket.ResponseCode != 0 && ftpPacket.ResponseArgument != null)
                    {
                        System.Collections.Specialized.NameValueCollection tmpCol = new System.Collections.Specialized.NameValueCollection();
                        tmpCol.Add(ftpPacket.ResponseCode.ToString(), ftpPacket.ResponseArgument);
                        MainPacketHandler.OnParametersDetected(new Events.ParametersEventArgs(ftpPacket.ParentFrame.FrameNumber, tcpSession.Flow.FiveTuple, transferIsClientToServer, tmpCol, ftpPacket.ParentFrame.Timestamp, "FTP Response"));

                        //look for an FTP banner
                        if (ftpPacket.ResponseCode == 220 && ftpPacket.ResponseArgument.ToLower().Contains("ftp"))
                        {
                            tcpSession.Flow.FiveTuple.ServerHost.AddFtpServerBanner(ftpPacket.ResponseArgument, tcpPacket.SourcePort);
                        }
                    }
                    if (ftpPacket.ResponseCode == 213 && ftpSession.PendingSizeRequestFileName != null)//File size response
                    {
                        int fileSize;
                        if (Int32.TryParse(ftpPacket.ResponseArgument, out fileSize))
                        {
                            ftpSession.FileSizes[ftpSession.PendingSizeRequestFileName] = fileSize;
                        }
                        //ftpSession.FileSizes.Add(ftpSession.PendingSizeRequestFileName, fileSize);
                        ftpSession.PendingSizeRequestFileName = null;
                    }
                    if (ftpPacket.ResponseCode == 226)//File receive OK
                    //close file stream assembler?
                    {
                    }
                    else if (ftpPacket.ResponseCode == 227)  //Entering Passive Mode - Response to client "PASV" command

                    //From: http://cr.yp.to/ftp/retr.html
                    //Many servers put different strings before h1 and after p2.
                    //I recommend that clients use the following strategy to parse the
                    //response line: look for the first digit after the initial space;
                    //look for the fourth comma after that digit; read two (possibly negative)
                    //integers, separated by a comma; the TCP port number is p1*256+p2,
                    //where p1 is the first integer modulo 256 and p2 is the second integer
                    //modulo 256.

                    //it is probably simpler to do this with RegEx, but this is simple enough so I wont bother with RegEx for now...
                    {
                        char[] digits    = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
                        string ipAndPort = ftpPacket.ResponseArgument.Substring(ftpPacket.ResponseArgument.IndexOfAny(digits));
                        //string ipAndPort=ftpPacket.ResponseArgument.Substring(ftpPacket.ResponseArgument.IndexOf('(')+1);
                        ipAndPort = ipAndPort.Substring(0, ipAndPort.LastIndexOfAny(digits) + 1);
                        //ipAndPort=ipAndPort.Substring(0, ipAndPort.IndexOf(')'));
                        ushort serverListeningOnPort;
                        if (this.TryGetPort(ipAndPort, out serverListeningOnPort))
                        {
                            ftpSession.PendingFileTransfer = new PendingFileTransfer(ftpSession.ClientHost, null, ftpSession.ServerHost, serverListeningOnPort, true, ftpSession);
                            if (this.pendingFileTransferList.ContainsKey(ftpSession.PendingFileTransfer.GetKey()))
                            {
                                this.pendingFileTransferList.Remove(ftpSession.PendingFileTransfer.GetKey());
                            }
                            this.pendingFileTransferList.Add(ftpSession.PendingFileTransfer.GetKey(), ftpSession.PendingFileTransfer);
                        }
                    }
                    else if (ftpPacket.ResponseCode == 230)//Login successful
                    //ftpSession.=ftpPacket.RequestArgument;
                    {
                        if (ftpSession.Username != null && ftpSession.Password != null)
                        {
                            base.MainPacketHandler.AddCredential(new NetworkCredential(tcpSession.ClientHost, tcpSession.ServerHost, ftpPacket.PacketTypeDescription, ftpSession.Username, ftpSession.Password, true, ftpPacket.ParentFrame.Timestamp));
                        }
                    }
                    else if (ftpPacket.ResponseCode == 234)  //server response to an 'AUTH TLS' command rfc4217 and rfc2228

                    /**
                     * If the server is willing to accept the named security mechanism,
                     * and does not require any security data, it must respond with reply
                     * code 234.
                     **/
                    //Unfortunately we haven't stored the request, so we can't know if the client was asking for TLS or some other security measure
                    {
                        if (ftpPacket.ResponseArgument.Contains("TLS") || ftpPacket.ResponseArgument.Contains("SSL"))
                        {
                            tcpSession.ProtocolFinder.SetConfirmedApplicationLayerProtocol(ApplicationLayerProtocol.Ssl, false);
                        }
                    }
                }//end server to client
            }
            if (ftpSession != null && ftpSession.PendingFileTransfer != null)
            {
                //I guess returnValue is already set to true by now, but I'll do it again just to be sure...
                if (parsedBytes == 0)
                {
                    parsedBytes = tcpPacket.PayloadDataLength;
                }
                //returnValue=true;
                PendingFileTransfer pending = ftpSession.PendingFileTransfer;
                //see if the pending file transfer could be transformed into a real file stream assembler
                if (pending.FileTransferSessionEstablished && pending.FileDirectionIsDataSessionServerToDataSessionClient != null && pending.DataSessionClientPort != null)
                {
                    //Server->Client ?

                    FileTransfer.FileStreamAssembler.FileAssmeblyRootLocation fileAssemblyLocation;
                    if ((ftpSession.ServerHost == pending.DataSessionServer) == pending.FileDirectionIsDataSessionServerToDataSessionClient.Value)
                    {
                        fileAssemblyLocation = FileTransfer.FileStreamAssembler.FileAssmeblyRootLocation.source;
                    }
                    else
                    {
                        fileAssemblyLocation = FileTransfer.FileStreamAssembler.FileAssmeblyRootLocation.destination;
                    }
                    FileTransfer.FileStreamAssembler assembler = new FileTransfer.FileStreamAssembler(MainPacketHandler.FileStreamAssemblerList, pending.GetFiveTuple(), !pending.FileDirectionIsDataSessionServerToDataSessionClient.Value, FileTransfer.FileStreamTypes.FTP, pending.Filename, "/", pending.Details, tcpPacket.ParentFrame.FrameNumber, tcpPacket.ParentFrame.Timestamp, fileAssemblyLocation);

                    string fileCompletePath = "";
                    if (assembler.Filename != null && assembler.FileLocation != null)
                    {
                        fileCompletePath = assembler.FileLocation + "/" + assembler.Filename;
                    }
                    if (ftpSession.FileSizes.ContainsKey(fileCompletePath))
                    {
                        assembler.FileContentLength         = ftpSession.FileSizes[fileCompletePath];
                        assembler.FileSegmentRemainingBytes = ftpSession.FileSizes[fileCompletePath];
                    }
                    else
                    {
                        //-1 is set instead of null if Content-Length is not defined
                        assembler.FileContentLength         = -1;
                        assembler.FileSegmentRemainingBytes = -1;
                    }
                    if (assembler.TryActivate())
                    {
                        MainPacketHandler.FileStreamAssemblerList.Add(assembler);
                    }
                    //assembler.Activate();
                    //the file transfer is no longer pending since the assembler is started!
                    pendingFileTransferList.Remove(pending.GetKey());
                    ftpSession.PendingFileTransfer = null;
                }
            }
            return(parsedBytes);
        }