Esempio n. 1
0
 public void Deserialize(System.IO.TextReader rdr, Serializer serializer)
 {
     string name, value, rigthPart;
     var parameters = new System.Collections.Specialized.NameValueCollection();
     while (rdr.Property(out name, out value, out rigthPart, parameters) && !string.IsNullOrEmpty(name)) {
         switch (name.ToUpper()) {
             case "CLASS": Class = value.ToEnum<Classes>(); break;
             case "STATUS": Status = value.ToEnum<Statuses>(); break;
             case "UID": UID = value; break;
             case "ORGANIZER":
                 Organizer = new Contact();
                 Organizer.Deserialize(value, parameters);
                 break;
             case "CATEGORIES":
                 Categories = value.SplitEscaped().ToList();
                 break;
             case "DESCRIPTION": Description = value; break;
             case "SEQUENCE": Sequence = value.ToInt(); break;
             case "LAST-MODIFIED": LastModified = value.ToDateTime(); break;
             case "DTSTAMP": DTSTAMP = value.ToDateTime(); break;
             case "END": return;
             default:
                 Properties.Add(Tuple.Create(name, value, parameters));
                 break;
         }
     }
 }
Esempio n. 2
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. 3
0
		public void Deserialize(System.IO.TextReader rdr, Serializer serializer) {
			string name, value;
			var parameters = new System.Collections.Specialized.NameValueCollection();
			while (rdr.Property(out name, out value, parameters) && !string.IsNullOrEmpty(name)) {
				switch (name.ToUpper()) {
					case "BEGIN":
						switch (value) {
							case "VALARM":
								var a = serializer.GetService<Alarm>();
								a.Deserialize(rdr, serializer);
								Alarms.Add(a);
								break;
						}
						break;
					case "ATTENDEE":
						var contact = new Contact();
						contact.Deserialize(value, parameters);
						Attendees.Add(contact);
						break;
					case "CATEGORIES":
						Categories = value.SplitEscaped().ToList();
						break;
					case "CLASS": Class = value.ToEnum<Classes>(); break;
					case "CREATED": Created = value.ToDateTime(); break;
					case "DESCRIPTION": Description = value; break;
					case "DTEND": End = value.ToDateTime(); break;
					case "DTSTAMP": DTSTAMP = value.ToDateTime().GetValueOrDefault(); break;
					case "DTSTART": Start = value.ToDateTime(); break;
					case "LAST-MODIFIED": LastModified = value.ToDateTime(); break;
					case "LOCATION": Location = value; break;
					case "ORGANIZER":
						Organizer = serializer.GetService<Contact>();
						Organizer.Deserialize(value, parameters);
						break;
					case "PRIORITY": Priority = value.ToInt(); break;
					case "SEQUENCE": Sequence = value.ToInt(); break;
					case "STATUS": Status = value.ToEnum<Statuses>(); break;
					case "SUMMARY": Summary = value; break;
					case "TRANSP": Transparency = value; break;
					case "UID": UID = value; break;
					case "URL": Url = value.ToUri(); break;
					case "ATTACH":
						var attach = value.ToUri();
						if (attach != null)
							Attachments.Add(attach);
						break;
					case "RRULE":
						var rule = serializer.GetService<Recurrence>();
						rule.Deserialize(null, parameters);
						Recurrences.Add(rule);
						break;
					case "END": return;
					default:
						Properties.Add(Tuple.Create(name, value, parameters));
						break;
				}
			}

			IsAllDay = Start == End;
		}
        public string Get(string url, WebProxy proxy, string publicKey, string secretKey, string upload, string fileName = "", string fileMime = "", string fileContent = "")
        {
            using (var client = new WebClient())
            {
                    if (proxy != null)
                    client.Proxy = proxy;

                client.Encoding = Encoding.UTF8;
                if (String.IsNullOrWhiteSpace(fileContent))
                {
                    var web = url + String.Format("/resources/file?public_key={0}&secret_key={1}&file_name={2}&file_mime={3}", publicKey, secretKey, fileName, fileMime);
                    byte[] json = client.UploadFile(web, upload);
                    return Encoding.UTF8.GetString(json);
                }
                else
                {
                    var web = url + String.Format("/resources/file?public_key={0}&secret_key={1}&file_name={2}&file_mime={3}", publicKey, secretKey, fileName, fileMime);

                    var values = new System.Collections.Specialized.NameValueCollection
                        {
                            {"file_content", fileContent}
                        };
                    return Encoding.Default.GetString(client.UploadValues(web, values));
                }
            }
        }
Esempio n. 5
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. 6
0
		public void Deserialize(System.IO.TextReader rdr, Serializer serializer) {
			string name, value;
			var parameters = new System.Collections.Specialized.NameValueCollection();
			while (rdr.Property(out name, out value, parameters) && !string.IsNullOrEmpty(name)) {
				switch (name.ToUpper()) {
					case "UID": UID = value; break;
					case "ORGANIZER":
						Organizer = new Contact();
						Organizer.Deserialize(value, parameters);
						break;
					case "SEQUENCE": Sequence = value.ToInt(); break;
					case "LAST-MODIFIED": LastModified = value.ToDateTime(); break;
					case "DTSTART": LastModified = value.ToDateTime(); break;
					case "DTEND": LastModified = value.ToDateTime(); break;
					case "DTSTAMP": DTSTAMP = value.ToDateTime(); break;
					case "FREEBUSY":
						var parts = value.Split('/');
						Details.Add(new DateTimeRange {
							From = parts.FirstOrDefault().ToDateTime(),
							To = parts.ElementAtOrDefault(1).ToDateTime()
						});
						break;
					case "END": return;
					default:
						Properties.Add(Tuple.Create(name, value, parameters));
						break;
				}
			}
		}
        public void UsernamePassword(string clientId, string clientSecret, string username, string password, string tokenRequestEndpointUrl)
        {
            if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId");
            if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret");
            if (string.IsNullOrEmpty(username)) throw new ArgumentNullException("username");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");
            if (string.IsNullOrEmpty(tokenRequestEndpointUrl)) throw new ArgumentNullException("tokenRequestEndpointUrl");
            if (!Uri.IsWellFormedUriString(tokenRequestEndpointUrl, UriKind.Absolute)) throw new FormatException("tokenRequestEndpointUrl");

            var content = new System.Collections.Specialized.NameValueCollection
            {
                {"grant_type", "password"},
                {"client_id", clientId},
                {"client_secret", clientSecret},
                {"username", username},
                {"password", password}
            };

            AuthToken = new AuthToken();
            try
            {
                var responseBytes = WebClient.UploadValues(tokenRequestEndpointUrl, "POST", content);
                var responseBody = Encoding.UTF8.GetString(responseBytes);
                AuthToken = JsonConvert.DeserializeObject<AuthToken>(responseBody);
            }
            catch (Exception ex)
            {
                AuthToken.Errors = ex.Message;
            }
        }
Esempio n. 8
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;
        }
 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. 10
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. 11
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));
     }
 }
        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. 13
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;
 }
Esempio n. 14
0
 public static Catalog GetCatalogInfo(string catalogUrl, string token)
 {
     try
     {
         using (System.Net.WebClient client = new System.Net.WebClient())
         {
             client.Headers["Content-type"] = "application/x-www-form-urlencoded";
             client.Encoding = System.Text.Encoding.UTF8;
             var collection = new System.Collections.Specialized.NameValueCollection
             {
                 {"f", "json"},
                 {"token",token}
             };
             byte[] response = client.UploadValues(catalogUrl, "POST", collection);
             MemoryStream stream = new MemoryStream(response);
             StreamReader reader = new StreamReader(stream);
             string aRespStr = reader.ReadToEnd();
             JavaScriptSerializer jss = new JavaScriptSerializer();
             Catalog catalog = jss.Deserialize<Catalog>(aRespStr);
             if (catalog != null)
             {
                 return catalog;
             }
             return null;
         }
     }
     catch
     {
         return null;
     }
 }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) {
            // Validate arguments
            if (config == null) throw new ArgumentNullException("config");
            if (string.IsNullOrEmpty(name)) name = "SimpleSqlProfileProvider";
            if (String.IsNullOrEmpty(config["description"])) {
                config.Remove("description");
                config.Add("description", "PAB simple SQL profile provider");
            }

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

            // Basic init
            this.configuration = config;
            this.applicationName = GetConfig("applicationName", "");

            // Initialize connection string
            ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
            if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "") throw new ProviderException("Connection string cannot be blank.");
            this.connectionString = ConnectionStringSettings.ConnectionString;

            // Initialize table name
            this.tableName = GetConfig("tableName", "Profiles");
            if (!IsValidDbObjectName(this.tableName)) throw new ProviderException("Table name contains illegal characters.");

            // Initialize key column name
            this.keyColumnName = GetConfig("keyColumnName", "UserName");
            if (!IsValidDbObjectName(this.keyColumnName)) throw new ProviderException("Key column name contains illegal characters.");

            // Initialize last update column name
            this.lastUpdateColumnName = GetConfig("lastUpdateColumnName", "LastUpdate");
            if (!IsValidDbObjectName(this.lastUpdateColumnName)) throw new ProviderException("Last update column name contains illegal characters.");
        }
Esempio n. 16
0
 static DataBuilderFactory()
 {
     _dataBuilders = new System.Collections.Specialized.NameValueCollection();
     _assemblies = new List<string>();
     _assemblies.Add(Xy.AppSetting.BinDir + "Xy.Web.dll");
     LoadControl(ControlFactory.GetConfig("Data"));
 }
Esempio n. 17
0
        //private HtmlHelper CreateHelper()
        //{
        //    return new HtmlHelper(new ViewContext(ControllerContext, new DummyView(), new ViewDataDictionary(), new TempDataDictionary(), new StringWriter()), new CustomViewDataContainer());
        //}
        private static ControllerContext CreateControllerContext()
        {
            string host = "www.google.com";
            string proto = "http";
            string userIP = "127.0.0.1";

            var headers = new System.Collections.Specialized.NameValueCollection {
                                {"Host", host},
                                {"X-Forwarded-Proto", proto},
                                {"X-Forwarded-For", userIP}
                        };

            var httpRequest = Substitute.For<HttpRequestBase>();
            httpRequest.Url.Returns(new Uri(proto + "://" + host));
            httpRequest.Headers.Returns(headers);

            var httpContext = Substitute.For<HttpContextBase>();
            httpContext.Request.Returns(httpRequest);

            var controllerContext = new ControllerContext
            {
                HttpContext = httpContext
            };

            return controllerContext;
        }
Esempio n. 18
0
		public RegistrationUser()
		{
			PresentationId = (int)UserPresentation.Mister;
			ExtendedParameters = new System.Collections.Specialized.NameValueCollection();
			VatMandatory = true;
			// this.CreationDate = DateTime.Now;
		}
Esempio n. 19
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. 20
0
 static ControlFactory()
 {
     _controls = new System.Collections.Specialized.NameValueCollection();
     _assemblies = new List<string>();
     _config = new Dictionary<string, System.Xml.XmlNodeList>();
     LoadControl();
 }
Esempio n. 21
0
		/// <summary>
		/// Executes commands from Query parameters. This query API must match the CoffeeScript code.
		/// </summary>
		/// <param name="query">Query.</param>
		void DoCommands(NameValueCollection query)
		{
			// Gear flags and Signal flags
			int gear = 0, sigs = 0;
			Int32.TryParse(query["gear"], out gear);
			Int32.TryParse(query["signals"], out sigs);
			this.Manager.HandleUserInput((Solar.Gear)gear, (Solar.Signals)sigs);
		}
Esempio n. 22
0
 public CapturedHttpContext(System.Web.HttpContext httpContext)
 {
     Url = httpContext.Request.Url;
     UrlReferrer = httpContext.Request.UrlReferrer;
     User = httpContext.User;
     HttpMethod = httpContext.Request.HttpMethod;
     Headers = new System.Collections.Specialized.NameValueCollection(httpContext.Request.Headers);
 }
 public DefaultLoggerFactory()
 {
     var properties = new System.Collections.Specialized.NameValueCollection();
     properties["showDateTime"] = "true";
     //Common.Logging.LogManager.Adapter = new Common.Logging.Simple.TraceLoggerFactoryAdapter(properties);
     //TODO:正确自动配置common.logging
     Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(properties);
 }
Esempio n. 24
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. 25
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. 26
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. 27
0
 public static RouteValueDictionary ReturnUrlToRouteValues(NameValueCollection source, object additionalProperties)
 {
     var result = ReturnUrlToRouteValues(source);
     foreach (var property in additionalProperties.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
     {
         result.Add(property.Name, property.GetValue(additionalProperties, null));
     }
     return result;
 }
Esempio n. 28
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();
            }
        }
Esempio n. 29
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 override void Execute(CommandContext context)
        {
            var item = context.Items[0];

            var parameters = new System.Collections.Specialized.NameValueCollection();
            parameters["database"] = item.Database.Name;
            parameters["itemid"] = item.ID.ToString();
            parameters["language"] = item.Language.Name;
            Sitecore.Context.ClientPage.Start(this, "Run", parameters);
        }
Esempio n. 31
0
        static HttpWebRequest Http_Core(string _type, string _url, Encoding _encoding, List <TItem> _header, object _conmand = null)
        {
            #region 启动HTTP请求之前的初始化操作
            bool isget = false;
            if (_type == "GET")
            {
                isget = true;
            }

            if (isget)
            {
                if (_conmand is List <TItem> )
                {
                    List <TItem> _conmand_ = (List <TItem>)_conmand;

                    string param = "";
                    foreach (TItem item in _conmand_)
                    {
                        if (string.IsNullOrEmpty(param))
                        {
                            if (_url.Contains("?"))
                            {
                                param += "&" + item.Name + "=" + item.Value;
                            }
                            else
                            {
                                param = "?" + item.Name + "=" + item.Value;
                            }
                        }
                        else
                        {
                            param += "&" + item.Name + "=" + item.Value;
                        }
                    }
                    _url += param;
                }
            }
            Uri uri = null;
            try
            {
                uri = new Uri(_url);
            }
            catch { }
            #endregion
            if (uri != null)
            {
                //string _scheme = uri.Scheme.ToUpper();
                try
                {
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
                    req.Proxy             = null;
                    req.Host              = uri.Host;
                    req.Method            = _type;
                    req.AllowAutoRedirect = false;
                    bool isContentType = true;
                    #region 设置请求头
                    if (_header != null && _header.Count > 0)
                    {
                        bool isnotHeader = true;
                        System.Collections.Specialized.NameValueCollection collection = null;

                        foreach (TItem item in _header)
                        {
                            string _Lower_Name = item.Name.ToLower();
                            switch (_Lower_Name)
                            {
                            case "host":
                                req.Host = item.Value;
                                break;

                            case "accept":
                                req.Accept = item.Value;
                                break;

                            case "user-agent":
                                req.UserAgent = item.Value;
                                break;

                            case "referer":
                                req.Referer = item.Value;
                                break;

                            case "content-type":
                                isContentType   = false;
                                req.ContentType = item.Value;
                                break;

                            case "cookie":
                                #region 设置COOKIE
                                string          _cookie          = item.Value;
                                CookieContainer cookie_container = new CookieContainer();
                                if (_cookie.IndexOf(";") >= 0)
                                {
                                    string[] arrCookie = _cookie.Split(';');
                                    //加载Cookie
                                    //cookie_container.SetCookies(new Uri(url), cookie);
                                    foreach (string sCookie in arrCookie)
                                    {
                                        if (string.IsNullOrEmpty(sCookie))
                                        {
                                            continue;
                                        }
                                        if (sCookie.IndexOf("expires") > 0)
                                        {
                                            continue;
                                        }
                                        cookie_container.SetCookies(uri, sCookie);
                                    }
                                }
                                else
                                {
                                    cookie_container.SetCookies(uri, _cookie);
                                }
                                req.CookieContainer = cookie_container;
                                #endregion
                                break;

                            default:
                                if (isnotHeader && collection == null)
                                {
                                    var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                                    if (property != null)
                                    {
                                        collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
                                    }
                                    isnotHeader = false;
                                }
                                //设置对象的Header数据
                                if (collection != null)
                                {
                                    collection[item.Name] = item.Value;
                                }
                                break;
                            }
                        }
                    }
                    #endregion

                    #region 设置POST数据
                    if (!isget)
                    {
                        if (_conmand != null)
                        {
                            if (_conmand is List <TItem> )
                            {
                                List <TItem> _conmand_ = (List <TItem>)_conmand;
                                //POST参数
                                if (isContentType)
                                {
                                    req.ContentType = "application/x-www-form-urlencoded";
                                }
                                string param = "";
                                foreach (TItem item in _conmand_)
                                {
                                    if (string.IsNullOrEmpty(param))
                                    {
                                        param = item.Name + "=" + item.Value;
                                    }
                                    else
                                    {
                                        param += "&" + item.Name + "=" + item.Value;
                                    }
                                }

                                byte[] bs = _encoding.GetBytes(param);

                                req.ContentLength = bs.Length;

                                using (Stream reqStream = req.GetRequestStream())
                                {
                                    reqStream.Write(bs, 0, bs.Length);
                                    reqStream.Close();
                                }
                            }
                            else if (_conmand is string[])
                            {
                                try
                                {
                                    string boundary      = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                                    byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                                    byte[] endbytes      = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                                    req.ContentType = "multipart/form-data; boundary=" + boundary;


                                    using (Stream reqStream = req.GetRequestStream())
                                    {
                                        string[] files = (string[])_conmand;

                                        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                                        byte[] buff           = new byte[1024];
                                        for (int i = 0; i < files.Length; i++)
                                        {
                                            string file = files[i];
                                            reqStream.Write(boundarybytes, 0, boundarybytes.Length);
                                            string contentType = System.Web.MimeMapping.GetMimeMapping(file);

                                            //string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(file), contentType);
                                            string header      = string.Format(headerTemplate, "media", Path.GetFileName(file), contentType);//微信
                                            byte[] headerbytes = _encoding.GetBytes(header);
                                            reqStream.Write(headerbytes, 0, headerbytes.Length);

                                            using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                                            {
                                                int contentLen = fileStream.Read(buff, 0, buff.Length);

                                                int Value = contentLen;
                                                //文件上传开始
                                                //tProgress.Invoke(new Action(() =>
                                                //{
                                                //    tProgress.Maximum = (int)fileStream.Length;
                                                //    tProgress.Value = Value;
                                                //}));

                                                while (contentLen > 0)
                                                {
                                                    //文件上传中

                                                    reqStream.Write(buff, 0, contentLen);
                                                    contentLen = fileStream.Read(buff, 0, buff.Length);
                                                    Value     += contentLen;

                                                    //tProgress.Invoke(new Action(() =>
                                                    //{
                                                    //    tProgress.Value = Value;
                                                    //}));
                                                }
                                            }
                                        }

                                        //文件上传结束
                                        reqStream.Write(endbytes, 0, endbytes.Length);
                                    }
                                }
                                catch
                                {
                                    if (isContentType)
                                    {
                                        req.ContentType = null;
                                    }
                                    req.ContentLength = 0;
                                }
                            }
                            else
                            {
                                //POST参数
                                if (isContentType)
                                {
                                    req.ContentType = "application/x-www-form-urlencoded";
                                }
                                string param = _conmand.ToString();

                                byte[] bs = _encoding.GetBytes(param);

                                req.ContentLength = bs.Length;

                                using (Stream reqStream = req.GetRequestStream())
                                {
                                    reqStream.Write(bs, 0, bs.Length);
                                    reqStream.Close();
                                }
                            }
                        }
                        else
                        {
                            req.ContentLength = 0;
                        }
                    }
                    #endregion

                    return(req);
                }
                catch
                {
                }
            }
            return(null);
        }
Esempio n. 32
0
        public static string Old_HttpGet(string _url, string _header = "", string _cookie = "")
        {
            string _result = null;

            try
            {
                Uri            uri = new Uri(_url);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                req.Proxy             = null;
                req.KeepAlive         = true;
                req.AllowAutoRedirect = true;
                if (_cookie != "")
                {
                    CookieContainer cookie_container = new CookieContainer();
                    if (_cookie.IndexOf(";") >= 0)
                    {
                        string[] arrCookie = _cookie.Split(';');
                        //加载Cookie
                        //cookie_container.SetCookies(new Uri(url), cookie);
                        foreach (string sCookie in arrCookie)
                        {
                            if (sCookie.IndexOf("expires") > 0)
                            {
                                continue;
                            }
                            cookie_container.SetCookies(uri, sCookie);
                        }
                    }
                    else
                    {
                        cookie_container.SetCookies(uri, _cookie);
                    }
                    req.CookieContainer = cookie_container;
                }
                if (_header != "")
                {
                    System.Collections.Specialized.NameValueCollection collection = null;
                    var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    if (property != null)
                    {
                        collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
                    }
                    if (collection != null)
                    {
                        foreach (string str in GetData(_header, "(.*?):(.*?)\n", "$1@$2|").Split('|'))
                        {
                            if (str != "")
                            {
                                string[] po = str.Split('@');

                                //设置对象的Header数据
                                if (collection != null)
                                {
                                    collection[po[0]] = po[1];
                                }
                            }
                        }
                    }
                }
                HttpWebResponse result         = (HttpWebResponse)req.GetResponse();
                Stream          receviceStream = result.GetResponseStream();
                StreamReader    readerOfStream = new StreamReader(receviceStream, Encoding.UTF8);
                string          strHTML        = readerOfStream.ReadToEnd();
                _result = strHTML;
                readerOfStream.Dispose();
                receviceStream.Dispose();
                readerOfStream.Close();
                receviceStream.Close();
                result.Close();
            }
            catch (WebException err)
            {
                var rsp = err.Response as HttpWebResponse;
                if (rsp != null)
                {
                    rsp.Close(); rsp.Dispose();
                }
            }
            return(_result);
        }
Esempio n. 33
0
 public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v, System.Collections.Specialized.NameValueCollection identity)
 {
     return(BuildUpdateSql(v, identity, 0));
 }
Esempio n. 34
0
        public int ExtractData(NetworkHost sourceHost, NetworkHost destinationHost, IEnumerable <PacketParser.Packets.AbstractPacket> packetList)
        {
            //Packets.UdpPacket udpPacket = null;
            int parsedBytes = 0;

            Packets.ITransportLayerPacket transportLayerPacket = null;
            FiveTuple ft = null;

            foreach (Packets.AbstractPacket p in packetList)
            {
                if (p is Packets.ITransportLayerPacket)
                {
                    transportLayerPacket = (Packets.ITransportLayerPacket)p;
                    if (transportLayerPacket is Packets.UdpPacket)
                    {
                        ft = new FiveTuple(sourceHost, transportLayerPacket.SourcePort, destinationHost, transportLayerPacket.DestinationPort, FiveTuple.TransportProtocol.UDP);
                    }
                    else if (transportLayerPacket is Packets.TcpPacket)
                    {
                        ft = new FiveTuple(sourceHost, transportLayerPacket.SourcePort, destinationHost, transportLayerPacket.DestinationPort, FiveTuple.TransportProtocol.TCP);
                    }
                }
                if (p.GetType() == typeof(Packets.SipPacket))
                {
                    Packets.SipPacket sipPacket = (Packets.SipPacket)p;
                    if (sipPacket.MessageLine.StartsWith(INVITE))
                    {
                        string to   = null;
                        string from = null;
                        if (sipPacket.To != null && sipPacket.To.Length > 0)
                        {
                            to = sipPacket.To;
                            if (to.Contains(";"))
                            {
                                to = to.Substring(0, to.IndexOf(';'));
                            }
                            destinationHost.AddNumberedExtraDetail("SIP User", to);
                            //destinationHost.ExtraDetailsList["SIP User"]=to;
                        }
                        if (sipPacket.From != null && sipPacket.From.Length > 0)
                        {
                            from = sipPacket.From;
                            if (from.Contains(";"))
                            {
                                from = from.Substring(0, from.IndexOf(';'));
                            }
                            //destinationHost.AddNumberedExtraDetail("SIP User", from);
                            sourceHost.AddNumberedExtraDetail("SIP User", from);
                            //sourceHost.ExtraDetailsList["SIP User"]=from;
                        }
                        if (ft != null && to != null && from != null && !String.IsNullOrEmpty(sipPacket.CallID))
                        {
                            System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection {
                                { "From", sipPacket.From },
                                { "To", sipPacket.To },
                                { "Call-ID", sipPacket.CallID }
                            };
                            this.MainPacketHandler.OnParametersDetected(new Events.ParametersEventArgs(sipPacket.ParentFrame.FrameNumber, ft, true, nvc, sipPacket.ParentFrame.Timestamp, "SIP session " + ft.ToString()));
                        }
                    }
                    if (!String.IsNullOrEmpty(sipPacket.UserAgent))
                    {
                        sourceHost.AddHttpUserAgentBanner(sipPacket.UserAgent);
                    }
                    if (sipPacket.SDP != null)
                    {
                        if (sipPacket.SDP.Port != null && sipPacket.SDP.IP != null && sipPacket.CallID != null && ft != null)
                        {
                            lock (callEndPoints) {
                                Tuple <System.Net.IPAddress, ushort, FiveTuple> endPoint = new Tuple <System.Net.IPAddress, ushort, FiveTuple>(sipPacket.SDP.IP, sipPacket.SDP.Port.Value, ft);
                                if (this.callEndPoints.ContainsKey(sipPacket.CallID))
                                {
                                    Tuple <System.Net.IPAddress, ushort, FiveTuple> matchedTuple = null;
                                    foreach (var previousEndPoint in this.callEndPoints[sipPacket.CallID])
                                    {
                                        if (previousEndPoint.Item3.EqualsIgnoreDirection(ft))
                                        {
                                            //Tuple<System.Net.IPAddress, ushort, FiveTuple> previousEndPoint = ;
                                            if (!(previousEndPoint.Item1.Equals(endPoint.Item1) && previousEndPoint.Item2.Equals(endPoint.Item2)))
                                            {
                                                //this.callEndPoints.Remove(sipPacket.CallID);
                                                matchedTuple = previousEndPoint;
                                                if (sipPacket.From != null && sipPacket.To != null)
                                                {
                                                    this.MainPacketHandler.OnVoipCallDetected(sipPacket.SDP.IP, sipPacket.SDP.Port.Value, previousEndPoint.Item1, previousEndPoint.Item2, sipPacket.CallID, sipPacket.From, sipPacket.To);

                                                    if (ft != null)
                                                    {
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    if (matchedTuple == null)
                                    {
                                        this.callEndPoints[sipPacket.CallID].Add(endPoint);
                                    }
                                    if (matchedTuple != null)
                                    {
                                        this.callEndPoints[sipPacket.CallID].Remove(matchedTuple);
                                    }
                                }
                                else
                                {
                                    this.callEndPoints.Add(sipPacket.CallID, new List <Tuple <System.Net.IPAddress, ushort, FiveTuple> >()
                                    {
                                        endPoint
                                    });
                                }
                            }
                        }
                    }
                    parsedBytes += sipPacket.PacketLength;
                }
            }
            return(parsedBytes);
        }
Esempio n. 35
0
 public static ActionResult AddRouteValues(this ActionResult result, System.Collections.Specialized.NameValueCollection nameValueCollection)
 {
     // Copy all the values from the NameValueCollection into the route dictionary
     nameValueCollection.CopyTo(result.GetRouteValueDictionary());
     return(result);
 }
Esempio n. 36
0
        public List <ShipmentReportView> GetUserReportData(int userId, List <UserReportColumn> userColumns, System.Collections.Specialized.NameValueCollection requestParams, int skipCount, int takeCount)
        {
            string searchFromShipDate = requestParams["search_ship_date_from"];
            string searchToShipDate   = requestParams["search_ship_date_to"];
            string searchQuote        = requestParams["search_quote"];
            string searchService      = requestParams["search_service"];
            string searchTerminal     = requestParams["search_terminal"];

            var reportQuery = (from shipment in entities.ShipmentReportViews
                               select shipment);

            if (!string.IsNullOrEmpty(searchFromShipDate))
            {
                DateTime fromShipDate = DateTime.Parse(searchFromShipDate);
                reportQuery = reportQuery.Where(o => o.CreateDate >= fromShipDate);
            }
            if (!string.IsNullOrEmpty(searchToShipDate))
            {
                DateTime toShipDate = DateTime.Parse(searchToShipDate);
                reportQuery = reportQuery.Where(o => o.CreateDate <= toShipDate);
            }
            if (!string.IsNullOrEmpty(searchQuote))
            {
                reportQuery = reportQuery.Where(o => o.IsQuote == (searchQuote == "true" ? true : false));
            }
            if (!string.IsNullOrEmpty(searchService) && searchService != "NONE")
            {
                reportQuery = reportQuery.Where(o => o.ServiceDesc == searchService);
            }
            if (!string.IsNullOrEmpty(searchTerminal))
            {
                reportQuery = reportQuery.Where(o => o.Terminal.Contains(searchTerminal.ToUpper()));
            }


            for (int i = 0; i < userColumns.Count; i++)
            {
                if (requestParams["bSortable_" + i] == "true" && !string.IsNullOrEmpty(requestParams["iSortCol_0"]) && Convert.ToInt32(requestParams["iSortCol_0"]) == i)
                {
                    switch (userColumns[i].ColumnCode)
                    {
                    case "HAWB":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.HAWB);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.HAWB);
                        }
                        break;

                    case "ABCLogisticsTRACKING":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ABCLogisticsTracking);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ABCLogisticsTracking);
                        }
                        break;

                    case "SHIPPERNAME":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ShipperName);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ShipperName);
                        }
                        break;

                    case "SHIPPERADDRESS":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ShipperAddress);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ShipperAddress);
                        }
                        break;

                    case "SHIPPERCITY":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ShipperCity);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ShipperCity);
                        }
                        break;

                    case "SHIPPERSTATE":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ShipperState);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ShipperState);
                        }
                        break;

                    case "RECEIVERNAME":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ReceiverName);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ReceiverName);
                        }
                        break;

                    case "RECEIVERADDRESS":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ReceiverAddress);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ReceiverAddress);
                        }
                        break;

                    case "RECEIVERCITY":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ReceiverCity);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ReceiverCity);
                        }
                        break;

                    case "RECEIVERSTATE":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ReceiverState);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ReceiverState);
                        }
                        break;

                    case "SERVICEDESC":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.ServiceDesc);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.ServiceDesc);
                        }
                        break;

                    case "TERMINAL":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.Terminal);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.Terminal);
                        }
                        break;

                    case "CREATEDATE":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.CreateDate);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.CreateDate);
                        }
                        break;

                    case "ISQUOTE":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.IsQuote);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.IsQuote);
                        }
                        break;

                    case "PUAREA":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.PUArea);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.PUArea);
                        }
                        break;

                    case "DELAREA":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.DELArea);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.DELArea);
                        }
                        break;

                    case "FUELSURCHARGE":
                        if (requestParams["sSortDir_0"] == "asc")
                        {
                            reportQuery = reportQuery.OrderBy(o => o.NoFuelSurcharge);
                        }
                        else
                        {
                            reportQuery = reportQuery.OrderByDescending(o => o.NoFuelSurcharge);
                        }
                        break;
                    }
                }
            }

            return(reportQuery.Skip(skipCount).Take(takeCount).ToList());
        }
Esempio n. 37
0
        protected void handleRequest(Dictionary <string, object> request)
        {
            processRequestThreads.Add(System.Threading.Thread.CurrentThread);
            if (!request.ContainsKey(idKey) || !request.ContainsKey(pathKey))
            {
                return;
            }
            int id = (int)request[idKey];

            object responceObj = null;

            try
            {
                WebServerRequest webServerRequest = new WebServerRequest();
                webServerRequest.Path = (string)request[pathKey];

                if (request.ContainsKey(dataKey))
                {
                    if (request[dataKey] is string)
                    {
                        webServerRequest.Data = (string)request[dataKey];
                    }
                    else if (request[dataKey] != null)
                    {
                        webServerRequest.Data = request[dataKey];
                    }
                }
                if (request.ContainsKey(cookiesKey) && request[cookiesKey] is Dictionary <string, object> )
                {
                    System.Collections.Specialized.NameValueCollection cookies = new System.Collections.Specialized.NameValueCollection();
                    foreach (KeyValuePair <string, object> cookie in (Dictionary <string, object>)request[cookiesKey])
                    {
                        if (!(cookie.Value is string))
                        {
                            continue;
                        }
                        cookies.Add(cookie.Key, (string)cookie.Value);
                    }
                    webServerRequest.Cookies = cookies;
                }


                WebServerResponse response = _webServer.generateResponse(webServerRequest);
                List <SerializableKeyValuePair <string, string> > headers = new List <SerializableKeyValuePair <string, string> >();
                for (int i = 0; i < response.Headers.AllKeys.Length; i++)
                {
                    string key = response.Headers.Keys[i];
                    foreach (string value in response.Headers.GetValues(i))
                    {
                        headers.Add(new SerializableKeyValuePair <string, string>(key, value));
                    }
                }
                responceObj = new { id = id, status = response.StatusCode, body = response.BodyString, headers = headers };
            }
            catch (HttpException ex)
            {
                responceObj = new { id = id, status = ex.GetHttpCode().ToString() + " " + ex.Message };
            }
            catch
            {
                responceObj = new { id = id, status = "500 Internal Server Error" };
            }
            reply(responceObj);
            processRequestThreads.Remove(System.Threading.Thread.CurrentThread);
        }
Esempio n. 38
0
 public void Add(System.Collections.Specialized.NameValueCollection c)
 {
 }
 /// <inheritdoc />
 protected override void Initialize(string providerName, System.Collections.Specialized.NameValueCollection config, Type managerType)
 {
 }
Esempio n. 40
0
 public NameValueCollection(System.Collections.Specialized.NameValueCollection col)
 {
 }
Esempio n. 41
0
 public NameValueCollection(int capacity, System.Collections.Specialized.NameValueCollection col)
 {
 }
Esempio n. 42
0
 public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
 {
     base.Initialize(name, config);
 }
Esempio n. 43
0
        private void Search()
        {
            if (txtSearchKeyword.Enabled)
            {
                SearchCategoryID SearchIndex = (SearchCategoryID)Enum.Parse(typeof(SearchCategoryID), cboSearchID.SelectedItem.Value.ToString());
                string           stParam     = "?task=" + Common.Encrypt("list", Session.SessionID) + "&search=" + Common.Encrypt(Server.UrlEncode(txtSearchKeyword.Text), Session.SessionID);

                System.Collections.Specialized.NameValueCollection querystrings = Request.QueryString;
                foreach (string querystring in querystrings.AllKeys)
                {
                    if (querystring.ToLower() != "task" && querystring.ToLower() != "search")
                    {
                        stParam += "&" + querystring + "=" + querystrings[querystring].ToString();
                    }
                    //else if (querystring.ToLower() == "task")
                    //    stParam = stParam.Replace(Common.Encrypt("list", Session.SessionID), Common.Encrypt(querystrings[querystring].ToString(), Session.SessionID));
                }

                switch (SearchIndex)
                {
                case SearchCategoryID.AllSources:
                    break;

                case SearchCategoryID.AccessGroups:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/AdminFiles/Security/_AccessGroup/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.AccessUsers:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/AdminFiles/Security/_AccessUser/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Contacts:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Contact/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ContactGroups:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_ContactGroup/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Countries:
                    break;

                case SearchCategoryID.Products:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Product/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Variations:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Variation/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductVariations:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Product/_Variations/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductGroups:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_ProductGroup/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ChargeType:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_ChargeType/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductSubGroups:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_ProductSubGroup/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Units:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Unit/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Discounts:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Discount/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.InventoryList:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.StockTypes:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/_StockType/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.StockTrans:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/_Stock/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Promos:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Promo/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductGroupVariations:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_ProductGroup/_Variations/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductGroupVariationsMatrix:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_ProductGroup/_VariationsMatrix/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductGroupAdditionalCharges:
                    break;

                case SearchCategoryID.CardTypes:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_CardType/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ProductVariationsMatrix:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/MasterFiles/_Product/_VariationsMatrix/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Branch:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/_Branch/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.PurchaseOrders:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/PurchasesAndPayables/_PO/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Vendors:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/PurchasesAndPayables/_Vendor/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.PurchaseJournals:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/PurchasesAndPayables/_PurchaseJournals/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.AccountSummary:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/GeneralLedger/_AccountSummary/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.AccountCategory:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/GeneralLedger/_AccountCategory/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.ChartOfAccounts:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/GeneralLedger/_ChartOfAccounts/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.PaymentJournals:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/PurchasesAndPayables/_Payments/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.PurchaseReturns:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/PurchasesAndPayables/_Returns/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.PurchaseDebitMemo:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/PurchasesAndPayables/_DebitMemo/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Customers:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/SalesAndReceivables/_Customer/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.SalesOrders:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/SalesAndReceivables/_SO/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.SalesJournals:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/SalesAndReceivables/_SalesJournals/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.SalesReturns:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/SalesAndReceivables/_Returns/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.SalesCreditMemo:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/SalesAndReceivables/_CreditNote/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.TransferIn:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/_TransferIn/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.TransferOut:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/_TransferOut/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.InvAdjustment:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/_InvAdjustment/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.CloseInventory:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Inventory/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.RewardMembers:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/Rewards/_Members/Default.aspx" + stParam);
                    break;

                case SearchCategoryID.Banks:
                    Response.Redirect(Constants.ROOT_DIRECTORY + "/GeneralLedger/_Bank/Default.aspx" + stParam);
                    break;

                default:
                    break;
                }
            }
        }
Esempio n. 44
0
        /// <summary>
        /// 生成update语句
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="v"></param>
        /// <param name="type">0=空值以null替代;1=空值转换(字符型为'',数值型为0,日期型为null);2=空值跳过</param>
        /// <returns></returns>
        public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v
                                     , System.Collections.Specialized.NameValueCollection identity, int type)
        {
            if (ct == null || ct.Table.Rows.Count == 0)
            {
                throw new Exception("要操作的表或字段不存在!");
            }

            //将V name全部改成小写
            System.Collections.Specialized.NameValueCollection lowerv = new System.Collections.Specialized.NameValueCollection();
            for (int x = 0; x < v.Count; x++)
            {
                string vn = v.GetKey(x).ToLower();
                string vv = "";
                if (v[x] != null)
                {
                    vv = v[x].ToString();
                }
                lowerv.Add(vn, vv);
            }
            v = lowerv;

            //将V name全部改成小写
            System.Collections.Specialized.NameValueCollection lowerid = new System.Collections.Specialized.NameValueCollection();
            for (int x = 0; x < identity.Count; x++)
            {
                string vn = identity.GetKey(x).ToLower();
                string vv = "";
                if (identity[x] != null)
                {
                    vv = identity[x].ToString();
                }
                lowerid.Add(vn, vv);
            }
            identity = lowerid;

            string setvalues = "", identitycolumns = "";
            int    idcount = 0
            , colcount     = 0;

            string vKeys = Key2String(v).ToLower()
            , idKeys     = Key2String(identity).ToLower();

            #region 生成Set串
            for (int i = 0; i < ct.Table.Rows.Count; i++)
            {
                string coln = ct.Table.Rows[i]["name"].ToString();

                if (identity != null && idKeys.IndexOf("," + coln.ToLower() + ",") != -1)
                {
                    idcount++;

                    string colv    = identity[coln.ToLower()].ToString();
                    int    coltype = int.Parse(ct.Table.Rows[i]["xtype"].ToString());

                    if (colv == null)
                    {
                        throw new Exception("指定的条件没有给出匹配值!");
                    }

                    //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
                    if (coltype == 0 || coltype == 4)
                    {
                        identitycolumns += (identitycolumns.Equals(string.Empty)) ? " [" + coln + "]=" + colv + " " : "and [" + coln + "]=" + colv + " ";
                    }
                    else if (coltype == 1 || coltype == 3)
                    {
                        colv             = colv.Replace("'", "''");
                        identitycolumns += (identitycolumns.Equals(string.Empty)) ? " [" + coln + "]='" + colv + "' " : "and [" + coln + "]='" + colv + "' ";
                    }
                    else if (coltype == 2)
                    {
                        colv             = colv.Replace("'", "''");
                        identitycolumns += (identitycolumns.Equals(string.Empty)) ? " [" + coln + "]=N'" + colv + "' " : "and [" + coln + "]=N'" + colv + "' ";
                    }

                    //这里存在一个小缺陷,多个条件间只能是与操作
                }

                if (v != null && vKeys.IndexOf("," + coln.ToLower() + ",") != -1)
                {
                    colcount++;
                    string colv   = v[coln.ToLower()].ToString();
                    int    collen = int.Parse(ct.Table.Rows[i]["length"].ToString())
                    , coltype     = int.Parse(ct.Table.Rows[i]["xtype"].ToString());

                    //coltype
                    //0=数据
                    //1=字符型
                    //2=日期型
                    //-1=不支持的类型


                    if (coltype == -1)
                    {
                        throw new Exception("出现不支持的数据类型!");
                    }

                    if (colv == null || colv == "")
                    {
                        #region 空值
                        //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
                        if (type == 0)
                        {
                            setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=null " : ", [" + coln + "]=null ";
                        }
                        else if (type == 1)
                        {
                            if (coltype == 0)
                            {
                                setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=0 " : ", [" + coln + "]=0 ";
                            }
                            else if (coltype == 1)
                            {
                                setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]='' " : ", [" + coln + "]='' ";
                            }
                            else if (coltype == 2)
                            {
                                setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=N'' " : ", [" + coln + "]=N'' ";
                            }
                            else
                            {
                                setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=null " : ", [" + coln + "]=null ";
                            }
                        }

                        #endregion
                    }
                    else
                    {
                        #region 代入字段值

                        //简单判断字符型的长度,可以加其它的判断
                        //                        if (coltype==1 && colv.Length>collen)
                        //                        {
                        //                            throw new Exception("要插入的字符串长度超过数据库设置!");
                        //                        }

                        //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
                        if (coltype == 0 || coltype == 4)
                        {
                            setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=" + colv + " " : ", [" + coln + "]=" + colv + " ";
                        }
                        else if (coltype == 1 || coltype == 3)
                        {
                            colv       = colv.Replace("'", "''");
                            setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]='" + colv + "' " : ", [" + coln + "]='" + colv + "' ";
                        }
                        else if (coltype == 2)
                        {
                            colv       = colv.Replace("'", "''");
                            setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=N'" + colv + "' " : ", [" + coln + "]=N'" + colv + "' ";
                        }

                        #endregion
                    }
                }
            }
            #endregion

            if (identity != null && idcount != identity.Count)
            {
                throw new Exception("指定的更新条件中某些字段不存在!");
            }

            if (v != null && colcount != v.Count)
            {
                throw new Exception("指定的字段列表中某些字段不存在!");
            }


            if (!setvalues.Equals(string.Empty))
            {
                string sql = "";
                if (identity != null && identity.Count > 0)
                {
                    sql = "update {0} set {1} where {2}";
                    sql = string.Format(sql, _tableName, setvalues, identitycolumns);
                }
                else
                {
                    sql = "update {0} set {1}";
                    sql = string.Format(sql, _tableName, setvalues);
                }
                return(sql);
            }
            else
            {
                return(string.Empty);
            }
        }
Esempio n. 45
0
 /// <summary>
 /// 生成没有Where条件的Update语句
 /// </summary>
 /// <param name="v"></param>
 /// <returns></returns>
 public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v)
 {
     return(BuildUpdateSql(v, null, 0));
 }
Esempio n. 46
0
 public string BuildInsertSql(System.Collections.Specialized.NameValueCollection v)
 {
     return(BuildInsertSql(v, 0));
 }
 public bool LoadPostData(string val, System.Collections.Specialized.NameValueCollection data)
 {
     return(true);
 }
Esempio n. 48
0
        protected override Colosoft.Reports.IReportDocument LoadReport(ref LocalReport report, ref List <ReportParameter> lstParam,
                                                                       HttpRequest PageRequest, System.Collections.Specialized.NameValueCollection Request, object[] outrosParametros, LoginUsuario login, string diretorioLogotipos)
        {
            Glass.Data.RelModel.Recibo recibo;

            // Verifica qual relatório será chamado
            switch (Request["rel"])
            {
            case "recibo":
                if (string.IsNullOrEmpty(outrosParametros[0].ToString()) || string.IsNullOrEmpty(outrosParametros[1].ToString()))
                {
                    return(null);
                }

                var idOrcamento = Request["idOrcamento"] != "0" && Request["idOrcamento"] != "" ? Request["idOrcamento"].StrParaUint() : 0;
                var idPedido    = Request["idPedido"] != "0" && Request["idPedido"] != "" ? Request["idPedido"].StrParaUint() : 0;
                var idLiberacao = Request["idLiberacao"] != "0" && Request["idLiberacao"] != "" ? Request["idLiberacao"].StrParaUint() : 0;
                var idsContaR   = outrosParametros[1].ToString();

                if (idsContaR == null || idsContaR == "0")
                {
                    if (PedidoConfig.LiberarPedido)
                    {
                        var contasRec = ContasReceberDAO.Instance.GetByLiberacaoPedido(idLiberacao, true);
                        if (contasRec != null && contasRec.Count > 0)
                        {
                            idsContaR = string.Join(",", contasRec.Select(f => f.IdContaR.ToString()));
                        }
                    }
                    else
                    {
                        var contasRec = ContasReceberDAO.Instance.GetByPedido(null, idPedido, false, true);
                        if (contasRec != null && contasRec.Count > 0)
                        {
                            idsContaR = string.Join(",", contasRec.Select(f => f.IdContaR.ToString()));
                        }
                    }
                }

                var orcamento = new Data.Model.Orcamento();
                var pedido    = new Data.Model.Pedido();
                var liberacao = new LiberarPedido();

                var nomeCliente  = string.Empty;
                var nomeVendedor = string.Empty;
                var idLoja       = new uint();
                var total        = new decimal();

                #region Orçamento

                // Recupera os dados do orçamento.
                if (idOrcamento > 0)
                {
                    orcamento = OrcamentoDAO.Instance.GetElementByPrimaryKey(idOrcamento);

                    if (orcamento.IdCliente > 0)
                    {
                        nomeCliente = ClienteDAO.Instance.GetNome(orcamento.IdCliente.Value);
                    }
                    else
                    {
                        nomeCliente = orcamento.NomeCliente;
                    }

                    nomeVendedor = orcamento.IdFuncionario > 0 ? FuncionarioDAO.Instance.GetNome(orcamento.IdFuncionario.Value) : login.Nome;
                    idLoja       = orcamento.IdLoja > 0 ? orcamento.IdLoja.Value : login.IdLoja;
                    total        = orcamento.Total;

                    idPedido    = 0;
                    idLiberacao = 0;
                }

                #endregion

                #region Pedido

                // Recupera os dados do pedido.
                else if (idPedido > 0)
                {
                    pedido       = PedidoDAO.Instance.GetElementByPrimaryKey(idPedido);
                    nomeCliente  = ClienteDAO.Instance.GetNome(pedido.IdCli);
                    nomeVendedor = pedido.IdFunc > 0 ? FuncionarioDAO.Instance.GetNome(pedido.IdFunc) : login.Nome;
                    idLoja       = pedido.IdPedido > 0 ? pedido.IdLoja : login.IdLoja;
                    total        = pedido.Total;

                    // Se houver pcp, usa o total do mesmo
                    var totalEspelho = PedidoEspelhoDAO.Instance.ObtemTotal(idPedido);
                    if (totalEspelho > 0)
                    {
                        total = totalEspelho;
                    }

                    idLiberacao = 0;
                }

                #endregion

                #region Liberação

                // Recupera os dados da liberação.
                else if (idLiberacao > 0)
                {
                    liberacao    = LiberarPedidoDAO.Instance.GetElement(idLiberacao);
                    nomeCliente  = ClienteDAO.Instance.GetNome(liberacao.IdCliente);
                    nomeVendedor = !string.IsNullOrEmpty(liberacao.NomeFunc) ? liberacao.NomeFunc : login.Nome;
                    idLoja       = (uint)FuncionarioDAO.Instance.GetElementByPrimaryKey(liberacao.IdFunc).IdLoja;
                    total        = liberacao.Total;
                }

                #endregion

                recibo                 = new Data.RelModel.Recibo();
                recibo.Tipo            = Conversoes.StrParaInt(Request["referente"]);
                recibo.IdOrcamento     = orcamento.IdOrcamento;
                recibo.IdPedido        = pedido.IdPedido;
                recibo.IdLiberarPedido = liberacao.IdLiberarPedido;
                recibo.Cliente         = nomeCliente;
                recibo.IdLoja          = idLoja;
                recibo.SinalPedido     = pedido.IdPedido > 0 ? pedido.ValorEntrada + pedido.ValorPagamentoAntecipado : 0;
                recibo.Total           = total;
                recibo.Vendedor        = nomeVendedor;
                recibo.Items           = outrosParametros[0].ToString();
                recibo.NumParcelas     = idsContaR;
                recibo.ValorReferente  = Request["valorRef"];
                recibo.MotivoReferente = Request["motivoRef"];
                report.ReportPath      = Data.Helper.Utils.CaminhoRelatorio("Relatorios/Genericos/ModeloRecibo/rptRecibo{0}.rdlc");

                if (report.ReportPath == "Relatorios/Genericos/ModeloRecibo/rptReciboVidrosEVidros.rdlc")
                {
                    lstParam.Add(new ReportParameter("ImagemCabecalho",
                                                     "file:///" + PageRequest.PhysicalApplicationPath.Replace('\\', '/') + "Images/cabecalhoOrcamentoVivrosEVidros.jpg"));
                }

                if (ReciboConfig.Relatorio.UsarParcelasPedido && pedido.IdPedido > 0)
                {
                    report.DataSources.Add(new ReportDataSource("ParcelasPedido", pedido.NumParc > 0 ? ParcelasPedidoDAO.Instance.GetByPedido(pedido.IdPedido) :
                                                                new ParcelasPedido[0]));
                }

                report.DataSources.Add(new ReportDataSource("Recibo", new Data.RelModel.Recibo[] { recibo }));
                break;

            case "reciboPgAntec":
                Sinal   sinal       = SinalDAO.Instance.GetSinalDetails(Glass.Conversoes.StrParaUint(Request["idPgAntecipado"]));
                Cliente clientePgto = ClienteDAO.Instance.GetElementByPrimaryKey(sinal.IdCliente);

                recibo                 = new Data.RelModel.Recibo();
                recibo.Tipo            = Glass.Conversoes.StrParaInt(Request["referente"]);
                recibo.IdSinal         = sinal.IdSinal;
                recibo.Cliente         = clientePgto.Nome;
                recibo.IdLoja          = (uint)FuncionarioDAO.Instance.GetElementByPrimaryKey(sinal.UsuCad).IdLoja;
                recibo.Total           = sinal.TotalSinal;
                recibo.Vendedor        = FuncionarioDAO.Instance.GetNome(sinal.UsuCad);
                recibo.Items           = outrosParametros[0].ToString();
                recibo.NumParcelas     = outrosParametros[1].ToString();
                recibo.ValorReferente  = Request["valorRef"];
                recibo.MotivoReferente = Request["motivoRef"];
                report.ReportPath      = Glass.Data.Helper.Utils.CaminhoRelatorio("Relatorios/Genericos/ModeloRecibo/rptRecibo{0}.rdlc");

                report.DataSources.Add(new ReportDataSource("Recibo", new Data.RelModel.Recibo[] { recibo }));
                break;

            case "reciboAcerto":

                uint idAcerto = Request["idAcerto"] != "0" && Request["idAcerto"] != "" ? Glass.Conversoes.StrParaUint(Request["idAcerto"]) : 0;

                if (idAcerto > 0 && !AcertoDAO.Instance.Exists(idAcerto))
                {
                    Response.Write("O acerto informado não existe.");
                    return(null);
                }

                Acerto acerto = AcertoDAO.Instance.GetByCliList(Convert.ToInt32(idAcerto), 0, 0, 0, null, null, 0, 0, 0, 0, null, 0, 10)[0];

                recibo                 = new Data.RelModel.Recibo();
                recibo.Tipo            = Glass.Conversoes.StrParaInt(Request["referente"]);
                recibo.IdAcerto        = acerto.IdAcerto;
                recibo.Cliente         = ClienteDAO.Instance.GetNome(acerto.IdCli);
                recibo.IdLoja          = (uint)FuncionarioDAO.Instance.GetElementByPrimaryKey(acerto.UsuCad).IdLoja;
                recibo.Total           = acerto.TotalAcerto;
                recibo.Vendedor        = FuncionarioDAO.Instance.GetNome(acerto.UsuCad);
                recibo.Items           = outrosParametros[0].ToString();
                recibo.NumParcelas     = outrosParametros[1].ToString();
                recibo.ValorReferente  = Request["valorRef"];
                recibo.MotivoReferente = Request["motivoRef"];
                report.ReportPath      = Glass.Data.Helper.Utils.CaminhoRelatorio("Relatorios/Genericos/ModeloRecibo/rptRecibo{0}.rdlc");

                report.DataSources.Add(new ReportDataSource("Recibo", new Data.RelModel.Recibo[] { recibo }));

                break;

            case "termoaceitacao":
                if (!PedidoDAO.Instance.PedidoExists(Glass.Conversoes.StrParaUint(Request["ped"])))
                {
                    Response.Write("O pedido informado não existe.");
                    return(null);
                }

                Glass.Data.Model.Pedido pedTermo = PedidoDAO.Instance.GetElement(Glass.Conversoes.StrParaUint(Request["ped"]));

                if (pedTermo.IdOrcamento == null)
                {
                    pedTermo.IdOrcamento = 0;
                }

                pedTermo.InfoAdicional = Request["infAdic"]?.Replace("\\n", "\n") ?? string.Empty;

                report.ReportPath = Data.Helper.Utils.CaminhoRelatorio("Relatorios/Genericos/rptAceitacao{0}.rdlc");

                report.DataSources.Add(new ReportDataSource("PedidoRpt", PedidoRptDAL.Instance.CopiaLista(new Glass.Data.Model.Pedido[] { pedTermo }, PedidoRpt.TipoConstrutor.TermoAceitacao, false, login)));
                break;

            case "riscoquebra":
                // Verifica se pedido passado existe
                if (!PedidoDAO.Instance.PedidoExists(Glass.Conversoes.StrParaUint(Request["idPedido"])))
                {
                    Response.Write("O pedido informado não existe.");
                    return(null);
                }

                var risco = new Data.RelModel.RiscoQuebra();
                Glass.Data.Model.Pedido ped = PedidoDAO.Instance.GetElementByPrimaryKey(Glass.Conversoes.StrParaUint(Request["idPedido"]));
                Cliente cli = ClienteDAO.Instance.GetElementByPrimaryKey(ped.IdCli);
                cli.Cidade       = CidadeDAO.Instance.GetNome((uint?)cli.IdCidade);
                risco.IdPedido   = ped.IdPedido;
                risco.NomeLoja   = LojaDAO.Instance.GetElementByPrimaryKey(ped.IdLoja).NomeFantasia;
                risco.CidadeData = LojaDAO.Instance.GetElement(ped.IdLoja).Cidade + " " + Formatacoes.DataExtenso(DateTime.Now);
                risco.Cliente    = cli.Nome;
                risco.Endereco   = !string.IsNullOrEmpty(ped.LocalizacaoObra) ? ped.LocalizacaoObra : cli.EnderecoCompleto;
                risco.Telefone   = cli.Telefone;
                risco.Texto      = Request["texto"];

                report.ReportPath = Data.Helper.Utils.CaminhoRelatorio("Relatorios/Genericos/rptRiscoQuebra{0}.rdlc");

                report.DataSources.Add(new ReportDataSource("RiscoQuebra", new Data.RelModel.RiscoQuebra[] { risco }));
                break;

            case "reciboContaPagar":
            {
                var idContaPagar = Request["idContaPagar"] != "0" && Request["idContaPagar"] != "" ? Glass.Conversoes.StrParaInt(Request["idContaPagar"]) : 0;
                var contaPg      = ContasPagarDAO.Instance.GetPagasForRpt(idContaPagar, 0, null, 0, 0, 0, 0, null, null, null, null, null, null, null, null, 0, 0, 0, false, true, false, null, false,
                                                                          false, 0, 0, null, null);

                if (contaPg.Length == 0)
                {
                    throw new Exception("A conta a pagar informada não existe ou não está paga.");
                }

                recibo = new Data.RelModel.Recibo();
                recibo.IdContaPagar    = idContaPagar;
                recibo.IdLoja          = contaPg[0].IdLoja.GetValueOrDefault(0);
                recibo.Total           = contaPg[0].ValorPago;
                recibo.Cliente         = FornecedorDAO.Instance.GetElementByPrimaryKey(contaPg[0].IdFornec.GetValueOrDefault(0)).Nome;
                recibo.MotivoReferente = contaPg[0].DescrPlanoConta;

                report.ReportPath = Glass.Data.Helper.Utils.CaminhoRelatorio("Relatorios/Genericos/ModeloRecibo/rptRecibo{0}.rdlc");
                recibo.Tipo       = Glass.Conversoes.StrParaInt(Request["referente"]);

                report.DataSources.Add(new ReportDataSource("Recibo", new Data.RelModel.Recibo[] { recibo }));

                break;
            }
            }

            // Atribui parâmetros ao relatório
            lstParam.Add(new ReportParameter("Logotipo", Logotipo.GetReportLogoColor(PageRequest)));
            lstParam.Add(new ReportParameter("TextoRodape", Geral.TextoRodapeRelatorio(login.Nome)));
            lstParam.Add(new ReportParameter("CorRodape", "DimGray"));

            return(null);
        }
Esempio n. 49
0
 public virtual new void TransferRequest(string path, bool preserveForm, string method, System.Collections.Specialized.NameValueCollection headers)
 {
 }
Esempio n. 50
0
        /// <summary>
        /// 生成Insert语句
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="v"></param>
        /// <param name="type">0=空值以null替代;1=空值转换(字符型为'',数值型为0,日期型为null);2=空值跳过(这时值取决于数据库的默认值设置)</param>
        /// <returns></returns>
        public string BuildInsertSql(System.Collections.Specialized.NameValueCollection v, int type)
        {
            if (ct == null || ct.Table.Rows.Count == 0)
            {
                throw new Exception("要操作的表或字段不存在!");
            }
            //将V name全部改成小写
            System.Collections.Specialized.NameValueCollection lowerv = new System.Collections.Specialized.NameValueCollection();
            for (int x = 0; x < v.Count; x++)
            {
                string vn = v.GetKey(x).ToLower();
                string vv = "";
                if (v[x] != null)
                {
                    vv = v[x].ToString();
                }
                lowerv.Add(vn, vv);
            }
            v = lowerv;

            int colcount = 0;

            string columns = "", values = "";

            string vKeys = Key2String(v).ToLower();

            for (int i = 0; i < ct.Table.Rows.Count; i++)
            {
                string coln = ct.Table.Rows[i]["name"].ToString();

                if (v != null && vKeys.IndexOf("," + coln.ToLower() + ",") != -1)
                {
                    colcount++;

                    string colv   = v[coln.ToLower()].ToString();
                    int    collen = int.Parse(ct.Table.Rows[i]["length"].ToString())
                    , coltype     = int.Parse(ct.Table.Rows[i]["xtype"].ToString());

                    //coltype
                    //0=数据
                    //1=字符型
                    //2=日期型
                    //-1=不支持的类型


                    if (coltype == -1)
                    {
                        throw new Exception("出现不支持的数据类型!");
                    }

                    if (colv == null || colv == "")
                    {
                        #region 空值
                        if (type == 0)
                        {
                            columns += (columns.Equals(string.Empty)) ? " [" + coln + "] " : ", [" + coln + "] ";
                            values  += (values.Equals(string.Empty)) ? " null " : ", null ";
                        }
                        else if (type == 1)
                        {
                            columns += (columns.Equals(string.Empty)) ? " [" + coln + "] " : ", [" + coln + "] ";

                            if (coltype == 0)
                            {
                                values += (values.Equals(string.Empty)) ? " 0 " : ", 0 ";
                            }
                            else if (coltype == 1)
                            {
                                values += (values.Equals(string.Empty)) ? " '' " : ", '' ";
                            }
                            else if (coltype == 2)
                            {
                                values += (values.Equals(string.Empty)) ? " N'' " : ", N'' ";
                            }
                            else
                            {
                                values += (values.Equals(string.Empty)) ? " null " : ", null ";
                            }
                        }
                        else
                        {
                            continue;
                        }
                        #endregion
                    }
                    else
                    {
                        #region 代入字段值

                        //简单判断字符型的长度,可以自己加其它的判断
                        //                        if (coltype==1 && colv.Length>collen)
                        //                        {
                        //                            throw new Exception("要插入的字符串长度超过数据库设置!");
                        //                        }

                        //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
                        if (coltype == 0 || coltype == 4)
                        {
                            columns += (columns.Equals(string.Empty)) ? " [" + coln + "] " : ", [" + coln + "] ";
                            values  += (values.Equals(string.Empty)) ? " " + colv + " " : ", " + colv + " ";
                        }
                        else if (coltype == 1 || coltype == 3)
                        {
                            colv     = colv.Replace("'", "''");
                            columns += (columns.Equals(string.Empty)) ? " [" + coln + "] " : ", [" + coln + "] ";
                            values  += (values.Equals(string.Empty)) ? " '" + colv + "' " : ", '" + colv + "' ";
                        }
                        else if (coltype == 2)
                        {
                            colv     = colv.Replace("'", "''");
                            columns += (columns.Equals(string.Empty)) ? " [" + coln + "] " : ", [" + coln + "] ";
                            values  += (values.Equals(string.Empty)) ? " N'" + colv + "' " : ", N'" + colv + "' ";
                        }
                        else
                        {
                            continue;
                        }

                        #endregion
                    }
                }
            }

            if (v != null && colcount != v.Count)
            {
                throw new Exception("指定的字段列表中某些字段不存在!");
            }

            if (!columns.Equals(string.Empty) && !values.Equals(string.Empty))
            {
                string sql = "Insert into {0} ({1}) values ({2})";
                return(string.Format(sql, _tableName, columns, values));
            }
            else
            {
                return(string.Empty);
            }
        }
Esempio n. 51
0
        static void Main(string[] args)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["TWSE_ConnStr"].ToString()))
            {
                using (NpgsqlCommand comm = new NpgsqlCommand())
                {
                    comm.Connection = conn;
                    conn.Open();
                    DataTable dt = new DataTable();

                    #region 取出追蹤中的證券代碼
                    comm.CommandText = @"
                        SELECT 
                            code 
                        FROM 
                            stock
                        WHERE 
                            track = true
                    ";
                    using (NpgsqlDataAdapter sda = new NpgsqlDataAdapter(comm))
                    {
                        sda.Fill(dt);
                    }
                    #endregion


                    #region  每個追蹤中的證券,用爬蟲把資料抓回來
                    foreach (DataRow dr in dt.Rows)
                    {
                        //組出證券資訊的網址
                        string stock_code = dr["code"].ToString();
                        //往前抓兩年的資料
                        for (int i = 0; i < 24; i++)
                        {
                            string period = DateTime.Now.AddMonths(-1 * i).ToString("yyyyMM");
                            using (var client = new WebClient())
                            {
                                //先發出request,讓伺服器生成php頁面
                                var values = new System.Collections.Specialized.NameValueCollection();
                                values["STK_NO"] = stock_code;
                                values["mmon"]   = period.Substring(4, 2).Trim('0');
                                values["myear"]  = period.Substring(0, 4);
                                var response       = client.UploadValues(ConfigurationManager.AppSettings["TWSE_Gen"], values);
                                var responseString = System.Text.Encoding.Default.GetString(response);
                                var start          = responseString.IndexOf("(\"");
                                var end            = responseString.IndexOf("\")");
                                //再去抓生成後的php頁面
                                var crawler_url = ConfigurationManager.AppSettings["TWSE_Stock"] + responseString.Substring(start + 2, end - start - 2);

                                WebRequest myRequest = WebRequest.Create(crawler_url);
                                myRequest.Method = "GET";
                                WebResponse myResponse;

                                myResponse = myRequest.GetResponse();

                                using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                                {
                                    string result = sr.ReadToEnd();
                                    CQ     dom    = CQ.Create(result);
                                    comm.CommandText = @"
                                        INSERT INTO 
                                            stock_day(time, code, tv, tov, op, hp, lp, cp, spread, nt)    
                                        VALUES
                                            (@time, @code, @tv, @tov, @op, @hp, @lp, @cp, @spread, @nt)
                                        ON CONFLICT (time, code)
                                        DO 
                                            NOTHING                      
                                    ";
                                    for (var j = 2; j < dom[".board_trad tr"].Length; j++)
                                    {
                                        comm.Parameters.Clear();
                                        CultureInfo tc = new CultureInfo("zh-TW");
                                        tc.DateTimeFormat.Calendar = new TaiwanCalendar();

                                        comm.Parameters.AddWithValue("@time", DateTime.ParseExact(dom[".board_trad tr:eq(" + j + ") td:eq(0) div"].Html(), "yyyy/MM/dd", tc));
                                        comm.Parameters.AddWithValue("@code", stock_code);
                                        comm.Parameters.AddWithValue("@tv", Int32.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(1)"].Html().Replace(",", "")));
                                        comm.Parameters.AddWithValue("@tov", Int64.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(2)"].Html().Replace(",", "")));
                                        comm.Parameters.AddWithValue("@op", float.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(3)"].Html()));
                                        comm.Parameters.AddWithValue("@hp", float.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(4)"].Html()));
                                        comm.Parameters.AddWithValue("@lp", float.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(5)"].Html()));
                                        comm.Parameters.AddWithValue("@cp", float.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(6)"].Html()));
                                        comm.Parameters.AddWithValue("@spread", float.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(7)"].Html().Replace("X", "")));
                                        comm.Parameters.AddWithValue("@nt", Int32.Parse(dom[".board_trad tr:eq(" + j + ") td:eq(8)"].Html().Replace(",", "")));
                                        comm.ExecuteNonQuery();
                                    }
                                }
                                myResponse.Close();
                            }
                        }
                    }
                    #endregion
                }
            }
        }
Esempio n. 52
0
 public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v, string idcolumn, string idvalue)
 {
     return(BuildUpdateSql(v, idcolumn, idvalue, 0));
 }
Esempio n. 53
0
        /// <summary>
        /// 支付接口记录日志(记事本)
        /// </summary>
        /// <param name="PageName">页面名</param>
        /// <param name="logContents">日志内容</param>
        /// <param name="bRecordRequest">是否记录参数</param>
        public static void RecordLog(string PageName, string logContents, bool bRecordRequest)
        {
            lock (RootLock)
            {
                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    string      path   = AppDomain.CurrentDomain.BaseDirectory + "\\YeePayConfig.xml";
                    xmldoc.Load(path);
                    XElement xmlRoot = XElement.Parse(xmldoc.InnerXml);
                    foreach (XElement xe in xmlRoot.Elements("log"))
                    {
                        if (xe.Element("islog") != null)
                        {
                            islog = xe.Element("islog").Value;
                        }
                    }
                }
                catch (Exception)
                {
                }

                if (islog.Contains("1"))
                {
                    StreamWriter  fs = null;
                    StringBuilder sb = new StringBuilder();
                    try
                    {
                        #region 记录文本日志

                        sb.AppendFormat("记录时间:" + DateTime.Now.ToString() + "\r\n");
                        sb.AppendFormat("内    容: " + logContents + "\r\n");

                        if (HttpContext.Current != null && HttpContext.Current.Request != null)
                        {
                            sb.AppendFormat("      IP:" + System.Web.HttpContext.Current.Request.UserHostAddress + "\r\n");
                            sb.AppendFormat("  Request.HttpMethod:" + HttpContext.Current.Request.HttpMethod + "\r\n");

                            if (bRecordRequest)
                            {
                                #region 记录 Request 参数
                                try
                                {
                                    if (HttpContext.Current.Request.HttpMethod == "POST")
                                    {
                                        #region POST 提交
                                        if (HttpContext.Current.Request.Form.Count != 0)
                                        {
                                            //__VIEWSTATE
                                            //__EVENTVALIDATION
                                            System.Collections.Specialized.NameValueCollection nv = HttpContext.Current.Request.Form;
                                            if (nv != null && nv.Keys.Count > 0)
                                            {
                                                foreach (string key in nv.Keys)
                                                {
                                                    if (key == "__VIEWSTATE" || key == "__EVENTVALIDATION")
                                                    {
                                                        continue;
                                                    }
                                                    sb.AppendFormat("{0} ={1} \r\n", key, (nv[key] != null ? nv[key].ToString() : ""));
                                                }
                                            }
                                        }
                                        else
                                        {
                                            sb.AppendFormat(" HttpContext.Current.Request.Form.Count = 0 \r\n");
                                        }

                                        #endregion
                                    }
                                    else if (HttpContext.Current.Request.HttpMethod == "GET")
                                    {
                                        #region GET 提交

                                        if (HttpContext.Current.Request.QueryString.Count != 0)
                                        {
                                            System.Collections.Specialized.NameValueCollection nv = HttpContext.Current.Request.QueryString;
                                            if (nv != null && nv.Keys.Count > 0)
                                            {
                                                foreach (string key in nv.Keys)
                                                {
                                                    sb.AppendFormat("{0}={1} \r\n", key, nv[key]);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            sb.AppendFormat(" HttpContext.Current.QueryString.Form.Count = 0 \r\n");
                                        }

                                        #endregion
                                    }
                                    else
                                    {
                                    }
                                }
                                catch (Exception ex)
                                {
                                    sb.AppendFormat("  异常内容: " + ex + "\r\n");
                                    sb.AppendFormat("----------------------------------------------------------------------------------------------------\r\n\r\n");
                                    AgainWrite(sb, PageName);
                                }

                                #endregion
                            }
                        }
                        else
                        {
                            sb.AppendFormat("  HttpContext.Current.Request=null \r\n");
                        }

                        sb.AppendFormat("----------------------------------------------------------------------------------------------------\r\n\r\n");

                        string dir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Logs\\" + PageName + "\\";
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        fs = new StreamWriter(dir + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true, System.Text.Encoding.Default);
                        fs.WriteLine(sb.ToString());

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        sb.AppendFormat("catch(Exception ex): " + ex.ToString() + "\r\n");
                        AgainWrite(sb, PageName);
                    }
                    finally
                    {
                        if (fs != null)
                        {
                            fs.Close();
                            fs.Dispose();
                        }
                    }
                }
            }
        }
Esempio n. 54
0
        // Create or Update
        public override string PostAction(string parameters, System.Collections.Specialized.NameValueCollection querystring, string postdata)
        {
            string data = string.Empty;
            string bvin = FirstParameter(parameters);
            ApiResponse <ProductDTO> response = new ApiResponse <ProductDTO>();

            ProductDTO postedItem = null;

            try
            {
                postedItem = MerchantTribe.Web.Json.ObjectFromJson <ProductDTO>(postdata);
            }
            catch (Exception ex)
            {
                response.Errors.Add(new ApiError("EXCEPTION", ex.Message));
                return(MerchantTribe.Web.Json.ObjectToJson(response));
            }

            Product item = new Product();

            item.FromDto(postedItem);

            Product existing = MTApp.CatalogServices.Products.Find(item.Bvin);

            if (existing == null || existing.Bvin == string.Empty)
            {
                item.StoreId = MTApp.CurrentStore.Id;
                if (item.UrlSlug.Trim().Length < 1)
                {
                    item.UrlSlug = MerchantTribe.Web.Text.Slugify(item.ProductName, true, true);
                }

                // Try ten times to append to URL if in use
                bool rewriteUrlInUse = MerchantTribe.Commerce.Utilities.UrlRewriter.IsProductSlugInUse(item.UrlSlug, string.Empty, MTApp);
                for (int i = 0; i < 10; i++)
                {
                    if (rewriteUrlInUse)
                    {
                        item.UrlSlug    = item.UrlSlug + "-2";
                        rewriteUrlInUse = MerchantTribe.Commerce.Utilities.UrlRewriter.IsProductSlugInUse(item.UrlSlug, string.Empty, MTApp);
                        if (rewriteUrlInUse == false)
                        {
                            break;
                        }
                    }
                }

                if (MTApp.CatalogServices.ProductsCreateWithInventory(item, false))
                {
                    bvin = item.Bvin;
                }
            }
            else
            {
                MTApp.CatalogServices.ProductsUpdateWithSearchRebuild(item);
            }
            Product resultItem = MTApp.CatalogServices.Products.Find(bvin);

            if (resultItem != null)
            {
                response.Content = resultItem.ToDto();
            }



            data = MerchantTribe.Web.Json.ObjectToJson(response);
            return(data);
        }
Esempio n. 55
0
        /// <summary>
        /// 公众号转微信wap支付接口H5模式
        /// </summary>
        /// <param name="apptype">风控配置表id</param>
        /// <param name="code">订单编号</param>
        /// <param name="goodsname">商品名称</param>
        /// <param name="price">支付金额</param>
        /// <param name="orderid">订单id</param>
        /// <param name="ip">ip地址</param>
        /// <param name="appid">应用id</param>
        /// <returns></returns>
        private InnerResponse gzhwaph5(int apptype, string code, string goodsname, decimal price, int orderid, string ip, int appid, int infoTimes, int paymode)
        {
            InnerResponse   respon = new InnerResponse();
            InnerResponse   inn    = new InnerResponse();
            SelectInterface SeIn   = new SelectInterface();

            try
            {
                //查询应用是否开通微信公众号支付
                var payType = new PayWxGzh();
                var payc    = payType.LoadChannel(paymode, apptype, infoTimes, appid);
                if (string.IsNullOrEmpty(payc.PassName))
                {
                    inn = inn.ToResponse(ErrorCode.Code106);
                    return(inn);
                }
                System.Collections.Specialized.NameValueCollection Palist = new System.Collections.Specialized.NameValueCollection();

                string hckey = "wxgzhzwap" + appid;
                SeIn = SelectUserInfo(hckey, apptype, appid, infoTimes);
                JmPayParameter.JsonStr jsonStr = new JsonStr();
                PayBankModels          modes   = jsonStr.ParameterEntity(code, goodsname, price, "4", apptype, paymode);
                //h5模式
                respon = jsonStr.H5JsonStr(modes, ip);
                if (respon.ErrorCode == 100)
                {
                    Palist.Add("key", SeIn.UserKey);                                                             //key
                    Palist.Add("f", "json");                                                                     //API返回的格式支持json和js
                    Palist.Add("url", respon.ExtraData.ToString());                                              //要跳转的链接,先要经过urlencode编码
                    Palist.Add("b", "other");                                                                    //浏览器 默认other 表示其他浏览器,  baidu则表示手机百度,androd_chrome表示android chrome浏览器
                    string    urlstr                = ConfigurationManager.AppSettings["gzhzwapUrl"].ToString(); //公众号转wap请求地址
                    WebClient webClient             = new WebClient();
                    byte[]    responseData          = webClient.UploadValues(urlstr, "POST", Palist);            //得到返回字符流
                    string    srcString             = Encoding.UTF8.GetString(responseData);                     //解码
                    Dictionary <string, object> dic = new Dictionary <string, object>();
                    dic = JMP.TOOL.JsonHelper.DataRowFromJSON(srcString);
                    if (dic["status"].ToString() == "ok")
                    {
                        inn = inn.ToResponse(ErrorCode.Code100);
                        string ticket_url = dic["ticket_url"].ToString();
                        if (paymode == 3)
                        {
                            inn.ExtraData = ticket_url;
                            inn.IsJump    = true;
                        }
                        else
                        {
                            string json = "{\"data\":\"" + ticket_url + "\",\"PaymentType\":\"2\",\"SubType\":\"6\",\"IsH5\":\"1\"}";
                            inn.ExtraData = JMP.TOOL.AesHelper.AesEncrypt(json, ConfigurationManager.AppSettings["encryption"].ToString());
                        }
                    }
                    else
                    {
                        inn = inn.ToResponse(ErrorCode.Code104);
                        //转换微信链接失败
                        PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:" + srcString, summary: "公众号转wap支付接口错误信息", channelId: SeIn.PayId);
                    }
                    return(inn);
                }
                else
                {
                    return(respon);
                }
            }
            catch (Exception ex)
            {
                inn = inn.ToResponse(ErrorCode.Code104);
                //转换微信链接失败
                PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:" + ex, summary: "公众号转wap支付接口错误信息", channelId: SeIn.PayId);
                return(inn);
            }
        }
Esempio n. 56
0
 public virtual void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
 {
 }
Esempio n. 57
0
        public static string Old_HttpPost(string _url, string _conmand, string _header = "", string _cookie = null)
        {
            string _result = null;

            try
            {
                Uri            uri = new Uri(_url);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
                req.AllowAutoRedirect = true;
                req.KeepAlive         = true;
                req.Proxy             = null;
                string param = _conmand;
                byte[] bs    = Encoding.UTF8.GetBytes(param);

                req.Method = "POST";
                //req.ContentType = "application/x-www-form-urlencoded";
                req.ContentType   = "application/json;charset=UTF-8";
                req.ContentLength = bs.Length;
                if (_header != "")
                {
                    System.Collections.Specialized.NameValueCollection collection = null;
                    var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    if (property != null)
                    {
                        collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
                    }
                    if (collection != null)
                    {
                        foreach (string str in GetData(_header, "(.*?):(.*?)\n", "$1@$2|").Split('|'))
                        {
                            if (str != "")
                            {
                                string[] po = str.Split('@');
                                //设置对象的Header数据
                                if (collection != null)
                                {
                                    collection[po[0]] = po[1];
                                }
                            }
                        }
                    }
                }
                if (_cookie != null)
                {
                    CookieContainer cookie_container = new CookieContainer();
                    if (_cookie.IndexOf(";") >= 0)
                    {
                        string[] arrCookie = _cookie.Split(';');
                        //加载Cookie
                        //cookie_container.SetCookies(new Uri(url), cookie);
                        foreach (string sCookie in arrCookie)
                        {
                            if (sCookie.IndexOf("expires") > 0)
                            {
                                continue;
                            }
                            cookie_container.SetCookies(uri, sCookie);
                        }
                    }
                    else
                    {
                        cookie_container.SetCookies(uri, _cookie);
                    }
                    req.CookieContainer = cookie_container;
                }

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                    reqStream.Close();
                }

                string responseData = String.Empty;
                using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
                {
                    Stream _stream = response.GetResponseStream();
                    using (StreamReader reader = new StreamReader(_stream, Encoding.UTF8))
                    {
                        responseData = reader.ReadToEnd().ToString();
                    }
                    _result = responseData;
                }
            }
            catch (WebException err)
            {
                var rsp = err.Response as HttpWebResponse;
                if (rsp != null)
                {
                    rsp.Close(); rsp.Dispose();
                }
            }
            return(_result);
        }
Esempio n. 58
0
 public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v, string idcolumn, string idvalue, int type)
 {
     System.Collections.Specialized.NameValueCollection identity = new System.Collections.Specialized.NameValueCollection();
     identity.Add(idcolumn, idvalue);
     return(BuildUpdateSql(v, identity, type));
 }
Esempio n. 59
0
        // List or Find Single
        public override string GetAction(string parameters, System.Collections.Specialized.NameValueCollection querystring)
        {
            string data = string.Empty;

            if (string.Empty == (parameters ?? string.Empty))
            {
                // List
                string categoryBvin = querystring["bycategory"] ?? string.Empty;
                string countonly    = querystring["countonly"] ?? string.Empty;

                string page    = querystring["page"] ?? "1";
                int    pageInt = 1;
                int.TryParse(page, out pageInt);
                string pageSize    = querystring["pagesize"] ?? "9";
                int    pageSizeInt = 9;
                int.TryParse(pageSize, out pageSizeInt);
                int totalCount = 0;

                if (categoryBvin.Trim().Length > 0)
                {
                    // by category
                    ApiResponse <PageOfProducts> responsePage = new ApiResponse <PageOfProducts>();
                    responsePage.Content = new PageOfProducts();

                    List <Product> resultItems = new List <Product>();
                    resultItems = MTApp.CatalogServices.FindProductForCategoryWithSort(categoryBvin, CategorySortOrder.None, false, pageInt, pageSizeInt, ref totalCount);
                    responsePage.Content.TotalProductCount = totalCount;
                    foreach (Product p in resultItems)
                    {
                        responsePage.Content.Products.Add(p.ToDto());
                    }
                    data = MerchantTribe.Web.Json.ObjectToJson(responsePage);
                }
                else if (querystring["page"] != null)
                {
                    // all by page
                    ApiResponse <PageOfProducts> responsePage = new ApiResponse <PageOfProducts>();
                    responsePage.Content = new PageOfProducts();

                    List <Product> resultItems = new List <Product>();
                    resultItems = MTApp.CatalogServices.Products.FindAllPaged(pageInt, pageSizeInt);
                    foreach (Product p in resultItems)
                    {
                        responsePage.Content.Products.Add(p.ToDto());
                    }
                    data = MerchantTribe.Web.Json.ObjectToJson(responsePage);
                }
                else if (querystring["countonly"] != null)
                {
                    // count only
                    ApiResponse <long> responseCount = new ApiResponse <long>();
                    responseCount.Content = 0;
                    int output = MTApp.CatalogServices.Products.FindAllCount();
                    responseCount.Content = output;
                    data = MerchantTribe.Web.Json.ObjectToJson(responseCount);
                }
                else
                {
                    // single product
                    ApiResponse <List <ProductDTO> > response = new ApiResponse <List <ProductDTO> >();

                    List <Product> results = new List <Product>();
                    results = MTApp.CatalogServices.Products.FindAllPaged(1, 1000);
                    List <ProductDTO> dto = new List <ProductDTO>();
                    foreach (Product item in results)
                    {
                        dto.Add(item.ToDto());
                    }
                    response.Content = dto;
                    data             = MerchantTribe.Web.Json.ObjectToJson(response);
                }
            }
            else
            {
                string bysku  = querystring["bysku"] ?? string.Empty;
                string byslug = querystring["byslug"] ?? string.Empty;
                string bvin   = FirstParameter(parameters);

                // Find One Specific Category
                ApiResponse <ProductDTO> response = new ApiResponse <ProductDTO>();

                Product item = null;
                if (bysku.Trim().Length > 0)
                {
                    item = MTApp.CatalogServices.Products.FindBySku(bysku);
                }
                else if (byslug.Trim().Length > 0)
                {
                    item = MTApp.CatalogServices.Products.FindBySlug(byslug);
                }
                else
                {
                    item = MTApp.CatalogServices.Products.Find(bvin);
                }

                if (item == null)
                {
                    response.Errors.Add(new ApiError("NULL", "Could not locate that product. Check bvin and try again."));
                }
                else
                {
                    response.Content = item.ToDto();
                }
                data = MerchantTribe.Web.Json.ObjectToJson(response);
            }

            return(data);
        }
Esempio n. 60
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SETTINGS sets = null;

            if (IsPostBack)
            {
                // Save the current view port width (used for responsive design later)
                var vpWidth = viewPortWidth.Value;
                if (!string.IsNullOrEmpty(vpWidth))
                {
                    Session["vpWidth"] = vpWidth;
                }
                else
                {
                    Session["vpWidth"] = "1000";
                }
            }
            else
            {
                try
                {
                    if (SessionManager.SessionContext != null || SessionManager.UserContext != null)
                    {
                        SessionManager.Clear();
                        Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
                    }

                    string info = System.Configuration.ConfigurationManager.AppSettings["MainInfo"];
                    if (!string.IsNullOrEmpty(info))
                    {
                        lblMainInfo.Text    = info;
                        lblMainInfo.Visible = true;
                    }

                    System.Web.HttpBrowserCapabilities browser = Request.Browser;

                    SETTINGS setsPwdReset = SQMSettings.SelectSettingByCode(entities, "COMPANY", "TASK", "PasswordResetEnable");
                    if (setsPwdReset != null && setsPwdReset.VALUE.ToUpper() == "Y")
                    {
                        lnkForgotPassword.Visible = true;
                    }

                    SETTINGS setsLoginPosting = SQMSettings.SelectSettingByCode(entities, "COMPANY", "TASK", "LoginPostingsEnable");
                    if (setsLoginPosting == null || setsLoginPosting.VALUE.ToUpper() == "Y")
                    {
                        // url format login.aspx/?t=ltc:60&p=EHS
                        // execOverride == override query params to force ticker and image posting

                        System.Collections.Specialized.NameValueCollection qry = new System.Collections.Specialized.NameValueCollection();
                        string execOverride = System.Configuration.ConfigurationManager.AppSettings["LoginOverride"];
                        if (execOverride != null && execOverride == "QAI")
                        {
                            qry.Add("t", "ltc");
                            qry.Add("p", "EHS,QS");
                        }
                        else
                        {
                            sets = SQMSettings.GetSetting("ENV", "LOGINIMAGE");                              // force login splash page display
                            if (sets != null && sets.VALUE.ToUpper() == "Y")
                            {
                                qry.Add("p", "EHS,QS");
                            }
                            sets = SQMSettings.GetSetting("ENV", "LOGINSTAT");
                            if (sets != null && sets.VALUE.ToUpper() == "LTC")
                            {
                                qry.Add("t", "ltc");
                            }
                        }

                        sets = SQMSettings.GetSetting("ENV", "LOGINMESSAGE");
                        if (sets != null && !string.IsNullOrEmpty(sets.VALUE))
                        {
                            lblLoginMessage.Text    = sets.VALUE;
                            divLoginMessage.Visible = true;
                        }


                        if (Request.QueryString.Count > 0)
                        {
                            // AW 02/2016 - don't wipe out the current Collection, just add to it
                            //qry = Request.QueryString;
                            qry.Add(Request.QueryString);
                        }

                        if (qry.Get("t") != null)
                        {
                            string[] args = qry.Get("t").ToString().Split(':');

                            COMPANY      company  = new COMPANY();
                            decimal[]    plantIDS = SQMModelMgr.SelectPlantList(entities, 1, 0).Where(l => l.LOCATION_TYPE == "P").OrderBy(l => l.PLANT_NAME).Select(l => l.PLANT_ID).ToArray();
                            SQMMetricMgr stsmgr   = new SQMMetricMgr().CreateNew(company, "0", DateTime.Now, DateTime.Now, plantIDS);
                            stsmgr.ehsCtl = new EHSCalcsCtl().CreateNew(1, DateSpanOption.SelectRange, "E");
                            stsmgr.ehsCtl.ElapsedTimeSeries(plantIDS, new decimal[1] {
                                8
                            }, new decimal[1] {
                                63
                            }, "YES", true);

                            GaugeDefinition tikCfg = new GaugeDefinition().Initialize();
                            tikCfg.Width       = 450;                       // 0;
                            tikCfg.Unit        = args.Length > 1 ? Convert.ToInt32(args[1]) : 80;
                            tikCfg.Position    = "none";
                            tikCfg.NewRow      = false;
                            pnlPosting.Visible = true;
                            divTicker.Visible  = true;
                            uclGauge.CreateTicker(tikCfg, stsmgr.ehsCtl.Results.metricSeries, divTicker);
                        }

                        if (qry.Get("p") != null)
                        {
                            string[] args = qry.Get("p").ToString().Split(',');
                            if (args.Contains("EHS"))
                            {
                                pnlPosting.Visible = true;
                                imgPostingEHS.Style.Add("MARGIN-TOP", "8px");
                                imgPostingEHS.Src = SQM.Website.Classes.SQMDocumentMgr.GetImageSourceString(SQM.Website.Classes.SQMDocumentMgr.FindCurrentDocument("SYS", 31));
                            }
                            if (args.Contains("QS"))
                            {
                                pnlPosting.Visible = true;
                                imgPostingQS.Style.Add("MARGIN-TOP", "8px");
                                imgPostingQS.Src = SQM.Website.Classes.SQMDocumentMgr.GetImageSourceString(SQM.Website.Classes.SQMDocumentMgr.FindCurrentDocument("SYS", 32));
                            }
                        }
                    }

                    string externalLinks = System.Configuration.ConfigurationManager.AppSettings["ExternalLinks"];
                    if (!string.IsNullOrEmpty(externalLinks))
                    {
                        string[] linkArray = externalLinks.Split(',');
                        foreach (string link in linkArray)
                        {
                            divLinks.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;"));
                            HyperLink hlk = new HyperLink();
                            hlk.NavigateUrl = hlk.Text = link;
                            hlk.Target      = "_blank";
                            hlk.CssClass    = "linkUnderline";
                            divLinks.Controls.Add(hlk);
                        }
                        divLinks.Visible = true;
                    }
                }
                catch
                {
                    divAnnouncements.Visible = false;
                }

                if (Request.QueryString["rdp"] != null)
                {
                    ViewState["RedirectPath"] = Request.QueryString["rdp"];
                }
            }
        }