Beispiel #1
0
        /// <summary>
        /// 下载网络文件 提供一个
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="fileName"></param>
        /// <param name="label1">LABEL控件</param>
        /// <param name="image1">图片控件 </param>
        /// <param name="image1Width">图片的宽度</param>
        /// <returns></returns>
        public static bool DownloadFile(string URL,
                                        string fileName,
                                        Label label1,
                                        PictureBox image1,
                                        double image1Width
                                        )
        {
            try
            {
                System.Net.HttpWebRequest  httpWebRequest1  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();

                long totalLength = httpWebResponse1.ContentLength;

                System.IO.Stream stream1 = httpWebResponse1.GetResponseStream();
                System.IO.Stream stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create);

                long   currentLength = 0;
                byte[] by            = new byte[1024];
                int    osize         = stream1.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    currentLength = osize + currentLength;
                    stream2.Write(by, 0, osize);

                    ImageProgressBar(currentLength, totalLength, image1Width, image1);
                    label1.Text = String.Format("{0} / {1}", BytesToString(currentLength), BytesToString(totalLength));
                    osize       = stream1.Read(by, 0, (int)by.Length);
                }

                stream2.Close();
                stream1.Close();

                return(currentLength == totalLength);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #2
0
        static public void SkidajFont()
        {
            string path = Path.GetDirectoryName(Application.ExecutablePath) + "\\slike\\msgothic.ttc";

            if (System.IO.File.Exists(path))
            {
                return;
            }

            if (!Util.CheckConnection.Check())
            {
                MessageBox.Show("Ne postoji datoteka za postavljanje fonta kod ispisa računa. Pokušaj skidanja\n" +
                                " datoteke s Interneta nije uspio jer niste spojeni na Internet. Provjerite svoju Internet konekciju, " +
                                "jer u suprotnom nećete moći ispisivati račune.", "Upozorenje!");
                return;
            }

            MessageBox.Show("Slijedi pokušaj downloadanja datoteke za ispis računa.", "");

            string sUrlToDnldFile;

            sUrlToDnldFile = "https://www.pc1.hr/pcpos/update/msgothic.zip";

            bool status = false;

            try
            {
                Uri    url           = new Uri(sUrlToDnldFile);
                string sFileSavePath = "";
                string sFileName     = System.IO.Path.GetFileName(url.LocalPath);

                sFileSavePath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\msgothic.ttc";

                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                response.Close();

                // gets the size of the file in bytes

                long iSize = response.ContentLength;

                // keeps track of the total bytes downloaded so we can update the progress bar

                long iRunningByteTotal = 0;

                System.Net.WebClient client = new System.Net.WebClient();

                System.IO.Stream strRemote = client.OpenRead(url);

                System.IO.FileStream strLocal = new System.IO.FileStream(sFileSavePath,
                                                                         System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);

                int iByteSize = 0;

                byte[] byteBuffer = new byte[1024];

                while ((iByteSize = strRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                {
                    // write the bytes to the file system at the file path specified

                    strLocal.Write(byteBuffer, 0, iByteSize);

                    iRunningByteTotal += iByteSize;

                    // calculate the progress out of a base "100"

                    double dIndex = iRunningByteTotal;

                    double dTotal = iSize;

                    double dProgressPercentage = (dIndex / dTotal);

                    int iProgressPercentage = (int)(dProgressPercentage * 100);

                    // update the progress bar

                    //bgWorker1.ReportProgress(iProgressPercentage);
                }

                strRemote.Close();
                strLocal.Flush();
                strLocal.Close();

                System.IO.File.Copy(sFileSavePath, path);

                MessageBox.Show("Datoteka uspješno skinuta!", "");

                status = true;
            }
            catch (Exception exM)
            {
                //Show if any error Occured

                MessageBox.Show("Pokušaj skidanja datoteke s Interneta nije uspio.\n\n" +
                                exM.Message, "Upozorenje!");
                status = false;
            }

            return;
        }
Beispiel #3
0
        public IEnumerable <SalonCheckoutClass> InsertNew(int EmployeeServicesId, string BookingDate, string BookingTime, string PaymentStatus, string PaymentType, int IsAcitve, string CreatedDate)
        {
            string URL = "http://www.google.com";

            System.Net.HttpWebRequest  rq2  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
            System.Net.HttpWebResponse res2 = (System.Net.HttpWebResponse)rq2.GetResponse();
            DateTime Date = DateTime.Parse(res2.Headers["Date"]);

            string Date1 = Convert.ToDateTime(Date).ToString("yyyy-MM-dd");

            try
            {
                con.Open();
                MySqlCommand    cmd3 = new MySqlCommand("select SalonCheckoutId from tblSalonCheckout order by SalonCheckoutId DESC limit 1", con);
                MySqlDataReader dr3  = cmd3.ExecuteReader();
                dr3.Read();
                int Number = Convert.ToInt32(dr3["SalonCheckoutId"]);
                dr3.Close();

                Random generator    = new Random();
                int    RandomNumber = generator.Next(100000, 1000000);
                string currentYear  = DateTime.Now.Year.ToString();
                string UniqueNumber = currentYear + "_" + "AppyPetsBookingId" + "_" + RandomNumber + "_" + Number;

                MySqlCommand cmd5 = new MySqlCommand("insert into tblPayments(UserId,PaymentType,PaymentStatus,IsActive,CreatedBy,CreatedDate) values('','" + PaymentType + "','" + PaymentStatus + "','" + IsAcitve + "','','" + DateTime.Now.AddMinutes(750).ToString("yyyy-MM-dd hh:mm:ss") + "' )", con);
                cmd5.ExecuteNonQuery();
                int paymentid = Convert.ToInt32(cmd5.LastInsertedId);



                MySqlCommand cmd = new MySqlCommand("insert into tblSalonCheckout(EmployeeServicesId,BookingDate,BookingTime,BookingsId,PaymentsId,PaymentStatus,PaymentType,IsActive,CreatedDate) values(" + EmployeeServicesId + ",('" + BookingDate + "'),'" + BookingTime + "','" + UniqueNumber + "','" + paymentid + "','" + PaymentStatus + "','" + PaymentType + "','" + IsAcitve + "','" + DateTime.Now.AddMinutes(750).ToString("yyyy-MM-dd hh:mm:ss") + "' )", con);

                cmd.ExecuteNonQuery();


                MySqlCommand cmd2 = new MySqlCommand("select SalonCheckoutId from tblSalonCheckout order by SalonCheckoutId DESC limit 1", con);

                MySqlDataReader dr = cmd2.ExecuteReader();
                dr.Read();
                int SalonCheckoutId = Convert.ToInt32(dr["SalonCheckoutId"]);
                dr.Close();

                obj.Add(new SalonCheckoutClass {
                    Message = "Success", SalonCheckoutId = SalonCheckoutId
                });
                return(obj);
            }
            catch (MySqlException ex)
            {
                if (ex.Message.Contains("UNIQUE"))
                {
                    obj.Add(new SalonCheckoutClass {
                        Message = "UniqueConstraint", ErrorMessage = ex.Message
                    });
                    return(obj);
                }
                else
                {
                    obj.Add(new SalonCheckoutClass {
                        Message = "Error", ErrorMessage = ex.Message
                    });
                    return(obj);
                }
            }
            catch (Exception ex)
            {
                obj.Add(new SalonCheckoutClass {
                    Message = "Error", ErrorMessage = ex.Message
                });
                return(obj);
            }
            finally
            {
                con.Close();
            }
        }
Beispiel #4
0
        protected void Application_End(object sender, EventArgs e)
        {
            //解决IIS应用程序池自动回收的问题
            System.Threading.Thread.Sleep(1000);
            //触发事件, 写入提示信息
            LogManager.Info("触发Application_End事件,正在重新启动网站:" + DateTime.Now);
            //设置站内任意一个页面甚至不存在的页面,目的是要激发Application_Start
            string url = Request.Url.ToString();

            System.Net.HttpWebRequest  myHttpWebRequest  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
        }
Beispiel #5
0
        public void sendMessage(String action, String message_type, String message_json)
        {
            message_json = "[" + message_json + "]";
            try
            {
                // Parse the message JSON into bytes
                byte[] message_json_bytes = System.Text.Encoding.ASCII.GetBytes(message_json);

                // Create a connection object
                System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                myRequest.Method = "POST";

                // The default is that no callback function is set and the ServerCertificateValidationCallback property is null.
                // Thus, all certificates will be accepted

                // Assemble headers that contain the producer token and message type
                // Note: in this example, the only action that is used is \"create\",
                // which will work totally fine;
                // to expand this application, you could modify it to use the \"update\"
                // action to, for example, modify existing AF element template types
                myRequest.Headers.Add("producertoken", producerToken);
                myRequest.Headers.Add("messagetype", message_type);
                myRequest.Headers.Add("action", action);
                myRequest.Headers.Add("messageformat", "JSON");
                myRequest.Headers.Add("omfversion", "1.0");

                // !!! Note: if desired, uncomment the below line to Console.WriteLine the outgoing message
                Console.WriteLine("\nOutgoing message (" + message_type + ", " + url + ")\n" + message_json);
                // Send the request, and collect the response
                System.IO.Stream requestStream = myRequest.GetRequestStream();
                requestStream.Write(message_json_bytes, 0, message_json_bytes.Length);
                requestStream.Close();

                // Show the response
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)myRequest.GetResponse();
                Console.WriteLine("Response code: " + (int)response.StatusCode);
                // For more about response codes, see
                // https://omf-docs.readthedocs.io/en/v1.0/Standard_Responses.html
            }
            catch (System.Net.WebException ex)
            {
                if (ex.Response != null)
                {
                    // Catch a web-specific error; get the response stream, and read throuh it
                    using (var responseStream = ex.Response.GetResponseStream())
                        using (var reader = new System.IO.StreamReader(responseStream))
                        {
                            // Print out the specific web error to the console
                            Console.WriteLine("!!!!! " + DateTime.Now + " Error during web request: " + reader.ReadToEnd() + " (" + ex.Message + ")");
                        }
                }
                else
                {
                    Console.WriteLine("!!!!! " + DateTime.Now + " General error during web request: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                // Log any GENERAL error, if it occurs
                Console.WriteLine("!!!!! " + DateTime.Now + " General error during web request: " + ex.Message);
            }
        }
Beispiel #6
0
        private static Series ParseCreativeNovels(string link)
        {
            // Variables to be retrieved
            string title = null;
            string cover = null;
            List <Chapter.Chapter> chapters = new List <Chapter.Chapter>();

            // Necessary variables
            HtmlWeb web = new HtmlWeb();

            web.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36";
            HtmlDocument doc = web.Load(link);

            // Get Title
            HtmlNode titleNode = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'x-text-headline')]").PreviousSibling;

            title = System.Net.WebUtility.HtmlDecode(titleNode.InnerText.Trim());
            foreach (char ch in System.IO.Path.GetInvalidFileNameChars())
            {
                title = title.Replace(ch, '_');
            }

            // Get Cover
            HtmlNode coverNode = doc.DocumentNode.SelectSingleNode("//img[@class='book_cover']");

            cover = coverNode.Attributes["src"].Value;


            // Get Chapters
            // Get Novel ID
            HtmlNode idNode  = doc.DocumentNode.SelectSingleNode("//div[@id='chapter_list_novel_page']");
            string   novelId = idNode.Attributes["class"].Value;
            // Get Security Code
            string             securityCode = "bf72be1c0d";
            HtmlNodeCollection scripts      = doc.DocumentNode.SelectNodes("//body/script");

            for (int i = scripts.Count - 1; i >= 0; i--)
            {
                if (scripts[i].InnerText.Contains("chapter_list_summon"))
                {
                    securityCode = Regex.Match(scripts[i].InnerText, "\"security\":\"([^\"]*)\"").Groups[1].Value;
                    break;
                }
            }
            // POST to https://creativenovels.com/wp-admin/admin-ajax.php to get Chapter List
            //Dictionary<string, string> postValues = new Dictionary<string, string>
            //{
            //    { "action", "crn_chapter_list"},
            //    { "view_id", novelId},
            //    { "s", securityCode},
            //};
            //FormUrlEncodedContent postContent = new FormUrlEncodedContent(postValues);
            string postValues = "action=crn_chapter_list&view_id=" + novelId + "&s=" + securityCode;

            byte[] postContent = Encoding.UTF8.GetBytes(postValues);
            System.Net.HttpWebRequest postRequest = System.Net.WebRequest.CreateHttp("https://creativenovels.com/wp-admin/admin-ajax.php");
            postRequest.Method      = "POST";
            postRequest.ContentType = "application/x-www-form-urlencoded";
            System.IO.Stream postStream = postRequest.GetRequestStream();
            postStream.Write(postContent, 0, postContent.Length);
            System.Net.WebResponse response = postRequest.GetResponse();
            System.IO.StreamReader reader   = new System.IO.StreamReader(response.GetResponseStream());
            string responseContent          = reader.ReadToEnd();

            int             chId           = 1;
            MatchCollection chapterMatches = Regex.Matches(responseContent, @"(https.*?)\.data\.(.*?)\.data\.(.*?)\.data\.available\.end_data\.");

            foreach (Match chapterMatch in chapterMatches)
            {
                string chapterTitle = System.Net.WebUtility.HtmlDecode(chapterMatch.Groups[2].Value);
                chapters.Add(new Chapter.CreativeNovels(chId++, chapterTitle, chapterMatch.Groups[1].Value));
            }

            Series series = new Series(link, title, cover, chapters, 3);

            return(series);
        }
Beispiel #7
0
        public void CreateDownloadLinkUsingKeyShouldWorkCorrectly()
        {
            var assetStorageProvider  = GetAssetStorageProvider();
            var assetStorageComponent = assetStorageProvider.GetAssetStorageComponent();

            var folderPath = $"{assetStorageProvider.GetAttributeValue( "RootFolder" )}/";
            var filename   = $"{Guid.NewGuid().ToString()}.jpg";

            using (new HttpSimulator("/", webContentFolder).SimulateRequest())
            {
                Asset expectedAsset = new Asset
                {
                    Key         = $"{folderPath}{filename}",
                    AssetStream = new MemoryStream(_testJpgFileBytes),
                    Type        = AssetType.File
                };

                bool hasUploaded = assetStorageComponent.UploadObject(assetStorageProvider, expectedAsset);
                Assert.That.IsTrue(hasUploaded);

                var actualAsset = assetStorageComponent.GetObject(assetStorageProvider, expectedAsset);
                Assert.That.IsNotNull(actualAsset);

                string url         = assetStorageComponent.CreateDownloadLink(assetStorageProvider, expectedAsset);
                bool   valid       = false;
                var    actualBytes = new byte[0];
                try
                {
                    System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
                    request.Method = "GET";
                    System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;

                    actualBytes = response.GetResponseStream().ReadBytesToEnd();

                    response.Close();

                    valid = response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
                }
                catch (System.Net.WebException e)
                {
                    using (System.Net.WebResponse response = e.Response)
                    {
                        System.Net.HttpWebResponse httpResponse = (System.Net.HttpWebResponse)response;
                        if (httpResponse.StatusCode == System.Net.HttpStatusCode.Forbidden)
                        {
                            Assert.That.Inconclusive($"File ({expectedAsset.Key}) was forbidden from viewing.");
                        }
                        if (httpResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            Assert.That.Inconclusive($"Anonymous download is not allowed for ({expectedAsset.Key}).");
                        }
                    }
                }
                finally
                {
                    assetStorageComponent.DeleteAsset(assetStorageProvider, actualAsset);
                }

                Assert.That.IsTrue(valid);
                Assert.That.AreEqual(_testJpgFileBytes.AsEnumerable(), actualBytes.AsEnumerable());
            }
        }
        public ReturnValue <USR_CustomerMaintain> QQLogin(string code)
        {
            //QQ回调
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(Container.ConfigService.GetAppSetting <string>("ThirdLoginFilePath", ""));
            XmlNode node  = xmlDoc.SelectSingleNode("//ThirdLogin//QQ//AppID");
            XmlNode node1 = xmlDoc.SelectSingleNode("//ThirdLogin//QQ//Key");

            //获取Access Token
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + node.InnerText + "&client_secret=" + node1.InnerText
                                                                                                        + "&code=" + code + "&redirect_uri=" + Container.ConfigService.GetAppSetting <string>("HomeUrl", "") + "Passport/ThirdLogin.aspx");
            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            Encoding     encoding          = Encoding.UTF8;
            StreamReader reader            = new StreamReader(res.GetResponseStream(), encoding);
            string       ret      = reader.ReadToEnd();
            string       retcode  = "";
            int          timespan = 0;

            try
            {
                retcode  = ret.Split(new char[] { '&' })[0].Split(new char[] { '=' })[1];
                timespan = int.Parse(ret.Split(new char[] { '&' })[1].Split(new char[] { '=' })[1]);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            //获取OpenID
            req    = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://graph.qq.com/oauth2.0/me?access_token=" + retcode);
            res    = (System.Net.HttpWebResponse)req.GetResponse();
            reader = new StreamReader(res.GetResponseStream(), encoding);
            ret    = reader.ReadToEnd();
            string openid = "";

            try
            {
                openid = ret.Split(new char[] { '"' })[7];
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            USR_CustomerMod m_customer = USR_CustomerBll.GetInstance().GetUserByThirdID(openid);

            if (m_customer != null && m_customer.SysNo != AppConst.IntNull)
            {
                m_customer.LastLoginTime = DateTime.Now;
                USR_CustomerBll.GetInstance().Update(m_customer);

                USR_CustomerMaintain rett = new USR_CustomerMaintain();
                m_customer.MemberwiseCopy(rett);
                return(ReturnValue <USR_CustomerMaintain> .Get200OK(rett));
            }

            m_customer = new USR_CustomerMod();

            //获取用户信息
            req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(@"https://graph.qq.com/user/get_user_info?access_token=" + retcode +

                                                                              "&oauth_consumer_key=" + node.InnerXml +

                                                                              "&openid=" + openid);
            res    = (System.Net.HttpWebResponse)req.GetResponse();
            reader = new StreamReader(res.GetResponseStream(), encoding);
            ret    = reader.ReadToEnd();

            try
            {
                m_customer.NickName = ret.Split(new char[] { ':', ',' })[7].Replace(@"""", "").DoTrim();
                m_customer.Photo    = ret.Split(new string[] { @""":", "," }, StringSplitOptions.None)[19].Replace(@"""", "").Replace(@"\", "").DoTrim();
                if (USR_CustomerBll.GetInstance().CheckNickName(m_customer.NickName).SysNo != AppConst.IntNull)
                {
                    m_customer.NickName += "-" + openid.Substring(0, 6);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            #region 保存数据
            USR_ThirdLoginMod m_third = new USR_ThirdLoginMod();
            m_third.OpenID     = openid;
            m_third.AccessKey  = retcode;
            m_third.ExpireTime = DateTime.Now.AddSeconds(timespan);
            m_third.ThirdType  = (int)AppEnum.ThirdLoginType.qq;

            USR_CustomerMod m_user = new USR_CustomerMod();
            try
            {
                m_user.Email         = "";
                m_user.FateType      = (int)AppEnum.FateType.astro;
                m_user.GradeSysNo    = AppConst.OriginalGrade;;
                m_user.Password      = "";
                m_user.RegTime       = DateTime.Now;
                m_user.Point         = AppConst.OriginalPoint;
                m_user.LastLoginTime = DateTime.Now;
                if (Container.ConfigService.GetAppSetting <string>("RegisterEmailCheck", "false").ToLower() == "true")
                {
                    m_user.Status = (int)AppEnum.State.prepare;
                }
                else
                {
                    m_user.Status = (int)AppEnum.State.normal;
                }

                m_user.Credit      = 0;
                m_user.Birth       = AppConst.DateTimeNull;
                m_user.IsShowBirth = 1;
                m_user.IsStar      = 0;
                m_user.BestAnswer  = 0;
                m_user.TotalAnswer = 0;
                m_user.TotalQuest  = 0;
                m_user.HomeTown    = AppConst.IntNull;
                m_user.Intro       = AppConst.OriginalIntro;
                m_user.Signature   = AppConst.OriginalSign;
                m_user.Exp         = 0;
                m_user.TotalReply  = 0;

                m_user.SysNo = USR_CustomerBll.GetInstance().Add(m_user);

                m_third.CustomerSysNo = m_user.SysNo;
                USR_ThirdLoginBll.GetInstance().Add(m_third);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            #endregion


            USR_CustomerMaintain rettt = new USR_CustomerMaintain();
            m_customer.MemberwiseCopy(rettt);
            return(ReturnValue <USR_CustomerMaintain> .Get200OK(rettt));
        }
Beispiel #9
0
        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static Boolean Send(TemplateMessage msg, ref String errMsg)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg), "参数是必须的!");
            }


            String objJson = "{";

            objJson += "\"touser\":\"" + msg.ToUser + "\",";
            objJson += "\"template_id\":\"" + msg.TemplateID + "\",";
            objJson += "\"url\":\"" + msg.Url + "\",";
            if (!String.IsNullOrEmpty(msg.MiniProgram) && msg.MiniProgram.Length > 1)
            {
                objJson += "\"miniprogram\":" + msg.MiniProgram + ",";
            }
            objJson += "\"data\":" + msg.Data;
            objJson += "}";

            AppDebugError.Append(new AppDebugError(nameof(TemplateMessage), nameof(Send), "发送模板消息内容:" + objJson));

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Common.BaseAPIUrl + "cgi-bin/message/template/send?access_token=" + Config.AccessToken);
            request.Method = "POST";

            Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(objJson);
            request.ContentLength = bytes.Length;

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.StreamReader     reader   = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            String responseStr = reader.ReadToEnd();

            reader.Close();
            response.Close();

            if (responseStr.Contains("errcode"))
            {
                var r = new { errcode = 0, errmsg = "", msgid = "" };
                var m = JsonConvert.DeserializeAnonymousType(responseStr, r);
                if (m.errcode == 0)
                {
                    return(true);
                }
                else
                {
                    errMsg = m.errcode + ":" + m.errmsg;
                    AppDebugError.Append(new AppDebugError(nameof(TemplateMessage), nameof(Send), "发送模板消息返回错误:" + errMsg));
                    return(false);
                }
            }
            else
            {
                errMsg = "服务器返回的字符串为:" + responseStr;
                AppDebugError.Append(new AppDebugError(nameof(TemplateMessage), nameof(Send), "发送模板消息返回:" + errMsg));
                return(false);
            }
        }
Beispiel #10
0
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public List <YeZhu> DataFormServer(string action)
        {
            List <YeZhu> result = new List <YeZhu>();
            string       url    = this.hosturl;

            if (url.Contains("?"))
            {
                url += "&" + action;
            }
            else
            {
                url += "?" + action;
            }
            url += "&key=" + rndKey;
            //请求http
            string html = "";

            //返回200正常有数据,204正常无数据,其它的都为出错
            System.Net.HttpWebRequest  request  = null;
            System.Net.HttpWebResponse response = null;

            int code = 0;

            try
            {
                request  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                response = (System.Net.HttpWebResponse)request.GetResponse();
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response != null)
                {
                    response = (System.Net.HttpWebResponse)wex.Response;
                }
                else
                {
                    throw new Exception("http请求出错:" + wex.Message);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("出错:" + ex.Message);
            }
            finally
            {
                if (response != null)
                {
                    try
                    {
                        System.IO.Stream       ms = response.GetResponseStream();
                        System.IO.StreamReader sr = new System.IO.StreamReader(ms);
                        html = sr.ReadToEnd();
                        code = (int)response.StatusCode;
                        response.Close();
                    }
                    catch (Exception ex2)
                    {
                        throw new Exception("html处理出错:" + ex2.Message);
                    }
                }
            }

            if (code == 200)
            {
                try
                {
                    using (var ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(html)))
                    {
                        DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(List <YeZhu>));
                        result = (List <YeZhu>)deseralizer.ReadObject(ms);// //反序列化ReadObject
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("解析数据失败:" + ex.Message);
                }
            }
            else if (code == 204)
            {
                return(result);
            }
            return(result);
        }
Beispiel #11
0
        private void UpdateThreads()
        {
            string subjectURL = BaseURL + "subject.txt";

            System.Console.WriteLine(subjectURL);
            System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(subjectURL);
            FormMain.UserConfig.SetProxy(webReq);

            string encodingName = null;


            switch (Response.Style)
            {
            case Response.BBSStyle.jbbs:
                encodingName = "EUC-JP";
                break;

            case Response.BBSStyle.yykakiko:
            case Response.BBSStyle.nichan:
                encodingName = "Shift_JIS";
                break;
            }
            //encodingName = "Shift_JIS";
            System.Net.HttpWebResponse webRes = null;
            bBSThreads.Clear();

            PushAndSetWaitCursor();
            try
            {
                webRes = (System.Net.HttpWebResponse)webReq.GetResponse();
                Dictionary <string, object> lines = new Dictionary <string, object>();

                using (StreamReader reader = new StreamReader(webRes.GetResponseStream(), Encoding.GetEncoding(encodingName)))
                {
                    while (true)
                    {
                        string s = reader.ReadLine();
                        if (s == null)
                        {
                            break;
                        }

                        if (lines.ContainsKey(s) == false)
                        {
                            lines.Add(s, null);
                            BBSThread thread = new BBSThread();

                            if (thread.SetRawText(s))
                            {
                                bBSThreads.Add(thread);
                            }
                        }
                    }
                }


                filteredBBSThreads = new List <BBSThread>(bBSThreads);
                UpdateListView();
            }
            catch (Exception e)
            {
                FormMain.Instance.AddLog(string.Format("エラーが発生しました:{0}", e.Message));
            }
            finally
            {
                PopCursor();
            }
        }
Beispiel #12
0
        public ActionResult Sonuc()
        {
            var e = Request.Form.GetEnumerator();

            while (e.MoveNext())
            {
                String xkey = (String)e.Current;
                String xval = Request.Form.Get(xkey);
                Response.Write("<tr><td>" + xkey + "</td><td>" + xval + "</td></tr>");
            }

            String hashparams = Request.Form.Get("HASHPARAMS");
            String hashparamsval = Request.Form.Get("HASHPARAMSVAL");
            String storekey = "XXXX";     //Sizin Storkey Adresiniz
            String paramsval = "";
            int    index1 = 0, index2 = 0;

            // hash hesaplamada kullanılacak değerler ayrıştırılıp değerleri birleştiriliyor.
            do
            {
                index2 = hashparams.IndexOf(":", index1);
                String val = Request.Form.Get(hashparams.Substring(index1, index2 - index1)) == null ? "" : Request.Form.Get(hashparams.Substring(index1, index2 - index1));
                paramsval += val;
                index1     = index2 + 1;
            }while (index1 < hashparams.Length);

            //out.println("hashparams="+hashparams+"<br/>");
            //out.println("hashparamsval="+hashparamsval+"<br/>");
            //out.println("paramsval="+paramsval+"<br/>");
            String hashval   = paramsval + storekey;           //elde edilecek hash değeri için paramsval e store key ekleniyor. (işyeri anahtarı)
            String hashparam = Request.Form.Get("HASH");

            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hashbytes  = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(hashval);
            byte[] inputbytes = sha.ComputeHash(hashbytes);

            String hash = Convert.ToBase64String(inputbytes);                //Güvenlik ve kontrol amaçlı oluşturulan hash

            if (!paramsval.Equals(hashparamsval) || !hash.Equals(hashparam)) //oluşturulan hash ile gelen hash ve hash parametreleri değerleri ile ayrıştırılıp edilen edilen aynı olmalı.
            {
                Response.Write("<h4>Güvenlik Uyarısı. Sayısal İmza Geçerli Değil</h4>");
            }
            // Ödeme için gerekli parametreler
            String nameval     = "xxxx";                                                                                                         //İşyeri kullanıcı adı
            String passwordval = "xxxx";                                                                                                         //İşyeri şifresi
            String clientidval = Request.Form.Get("clientid");                                                                                   // İşyeri numarası
            String modeval     = "P";                                                                                                            //P olursa gerçek işlem, T olursa test işlemi yapar.
            String typeval     = "Auth";                                                                                                         //Auth PreAuth PostAuth Credit Void olabilir.
            String expiresval  = Request.Form.Get("Ecom_Payment_Card_ExpDate_Month") + "/" + Request.Form.Get("Ecom_Payment_Card_ExpDate_Year"); //Kredi Kartı son kullanım tarihi mm/yy formatından olmalı
            String cv2val      = Request.Form.Get("cv2");                                                                                        //Güvenlik Kodu
            String totalval    = Request.Form.Get("amount");                                                                                     //Tutar
            String numberval   = Request.Form.Get("md");                                                                                         //Kart numarası olarak 3d sonucu dönem md parametresi kullanılır.
            String taksitval   = "";                                                                                                             //Taksit sayısı peşin satışlar da boş olarak gönderilmelidir.
            String currencyval = "949";                                                                                                          //ytl için
            String orderidval  = "";                                                                                                             //Sipariş numarası


            String mdstatus = Request.Form.Get("mdStatus");                                                   // mdStatus 3d işlemin sonucu ile ilgili bilgi verir. 1,2,3,4 başarılı, 5,6,7,8,9,0 başarısızdır.

            if (mdstatus.Equals("1") || mdstatus.Equals("2") || mdstatus.Equals("3") || mdstatus.Equals("4")) //3D Onayı alınmıştır.
            {
                Response.Write("<h5>3D İşlemi Başarılı</h5><br/>");
                String cardholderpresentcodeval   = "13";
                String payersecuritylevelval      = Request.Form.Get("eci");
                String payertxnidval              = Request.Form.Get("xid");
                String payerauthenticationcodeval = Request.Form.Get("cavv");



                String ipaddressval = "";
                String emailval     = "";
                String groupidval   = "";
                String transidval   = "";
                String useridval    = "";

                //Fatura Bilgileri
                String billnameval       = "";    //Fatur İsmi
                String billstreet1val    = "";    //Fatura adres 1
                String billstreet2val    = "";    //Fatura adres 2
                String billstreet3val    = "";    //Fatura adres 3
                String billcityval       = "";    //Fatura şehir
                String billstateprovval  = "";    //Fatura eyalet
                String billpostalcodeval = "";    //Fatura posta kodu

                //Teslimat Bilgileri
                String shipnameval       = "";    //isim
                String shipstreet1val    = "";    //adres 1
                String shipstreet2val    = "";    //adres 2
                String shipstreet3val    = "";    //adres 3
                String shipcityval       = "";    //şehir
                String shipstateprovval  = "";    //eyalet
                String shippostalcodeval = "";    //posta kodu


                String extraval = "";



                //Ödeme için gerekli xml yapısı oluşturuluyor

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                System.Xml.XmlDeclaration dec =
                    doc.CreateXmlDeclaration("1.0", "ISO-8859-9", "yes");

                doc.AppendChild(dec);


                System.Xml.XmlElement cc5Request = doc.CreateElement("CC5Request");
                doc.AppendChild(cc5Request);

                System.Xml.XmlElement name = doc.CreateElement("Name");
                name.AppendChild(doc.CreateTextNode(nameval));
                cc5Request.AppendChild(name);

                System.Xml.XmlElement password = doc.CreateElement("Password");
                password.AppendChild(doc.CreateTextNode(passwordval));
                cc5Request.AppendChild(password);

                System.Xml.XmlElement clientid = doc.CreateElement("ClientId");
                clientid.AppendChild(doc.CreateTextNode(clientidval));
                cc5Request.AppendChild(clientid);

                System.Xml.XmlElement ipaddress = doc.CreateElement("IPAddress");
                ipaddress.AppendChild(doc.CreateTextNode(ipaddressval));
                cc5Request.AppendChild(ipaddress);

                System.Xml.XmlElement email = doc.CreateElement("Email");
                email.AppendChild(doc.CreateTextNode(emailval));
                cc5Request.AppendChild(email);

                System.Xml.XmlElement mode = doc.CreateElement("Mode");
                mode.AppendChild(doc.CreateTextNode(modeval));
                cc5Request.AppendChild(mode);

                System.Xml.XmlElement orderid = doc.CreateElement("OrderId");
                orderid.AppendChild(doc.CreateTextNode(orderidval));
                cc5Request.AppendChild(orderid);

                System.Xml.XmlElement groupid = doc.CreateElement("GroupId");
                groupid.AppendChild(doc.CreateTextNode(groupidval));
                cc5Request.AppendChild(groupid);

                System.Xml.XmlElement transid = doc.CreateElement("TransId");
                transid.AppendChild(doc.CreateTextNode(transidval));
                cc5Request.AppendChild(transid);

                System.Xml.XmlElement userid = doc.CreateElement("UserId");
                userid.AppendChild(doc.CreateTextNode(useridval));
                cc5Request.AppendChild(userid);

                System.Xml.XmlElement type = doc.CreateElement("Type");
                type.AppendChild(doc.CreateTextNode(typeval));
                cc5Request.AppendChild(type);

                System.Xml.XmlElement number = doc.CreateElement("Number");
                number.AppendChild(doc.CreateTextNode(numberval));
                cc5Request.AppendChild(number);

                System.Xml.XmlElement expires = doc.CreateElement("Expires");
                expires.AppendChild(doc.CreateTextNode(expiresval));
                cc5Request.AppendChild(expires);

                System.Xml.XmlElement cvv2val = doc.CreateElement("Cvv2Val");
                cvv2val.AppendChild(doc.CreateTextNode(cv2val));
                cc5Request.AppendChild(cvv2val);

                System.Xml.XmlElement total = doc.CreateElement("Total");
                total.AppendChild(doc.CreateTextNode(totalval));
                cc5Request.AppendChild(total);

                System.Xml.XmlElement currency = doc.CreateElement("Currency");
                currency.AppendChild(doc.CreateTextNode(currencyval));
                cc5Request.AppendChild(currency);

                System.Xml.XmlElement taksit = doc.CreateElement("Taksit");
                taksit.AppendChild(doc.CreateTextNode(taksitval));
                cc5Request.AppendChild(taksit);

                System.Xml.XmlElement payertxnid = doc.CreateElement("PayerTxnId");
                payertxnid.AppendChild(doc.CreateTextNode(payertxnidval));
                cc5Request.AppendChild(payertxnid);

                System.Xml.XmlElement payersecuritylevel = doc.CreateElement("PayerSecurityLevel");
                payersecuritylevel.AppendChild(doc.CreateTextNode(payersecuritylevelval));
                cc5Request.AppendChild(payersecuritylevel);

                System.Xml.XmlElement payerauthenticationcode = doc.CreateElement("PayerAuthenticationCode");
                payerauthenticationcode.AppendChild(doc.CreateTextNode(payerauthenticationcodeval));
                cc5Request.AppendChild(payerauthenticationcode);

                System.Xml.XmlElement cardholderpresentcode = doc.CreateElement("CardholderPresentCode");
                cardholderpresentcode.AppendChild(doc.CreateTextNode(cardholderpresentcodeval));
                cc5Request.AppendChild(cardholderpresentcode);

                System.Xml.XmlElement billto = doc.CreateElement("BillTo");
                cc5Request.AppendChild(billto);

                System.Xml.XmlElement billname = doc.CreateElement("Name");
                billname.AppendChild(doc.CreateTextNode(billnameval));
                billto.AppendChild(billname);

                System.Xml.XmlElement billstreet1 = doc.CreateElement("Street1");
                billstreet1.AppendChild(doc.CreateTextNode(billstreet1val));
                billto.AppendChild(billstreet1);

                System.Xml.XmlElement billstreet2 = doc.CreateElement("Street2");
                billstreet2.AppendChild(doc.CreateTextNode(billstreet2val));
                billto.AppendChild(billstreet2);

                System.Xml.XmlElement billstreet3 = doc.CreateElement("Street3");
                billstreet3.AppendChild(doc.CreateTextNode(billstreet3val));
                billto.AppendChild(billstreet3);

                System.Xml.XmlElement billcity = doc.CreateElement("City");
                billcity.AppendChild(doc.CreateTextNode(billcityval));
                billto.AppendChild(billcity);

                System.Xml.XmlElement billstateprov = doc.CreateElement("StateProv");
                billstateprov.AppendChild(doc.CreateTextNode(billstateprovval));
                billto.AppendChild(billstateprov);

                System.Xml.XmlElement billpostalcode = doc.CreateElement("PostalCode");
                billpostalcode.AppendChild(doc.CreateTextNode(billpostalcodeval));
                billto.AppendChild(billpostalcode);



                System.Xml.XmlElement shipto = doc.CreateElement("ShipTo");
                cc5Request.AppendChild(shipto);

                System.Xml.XmlElement shipname = doc.CreateElement("Name");
                shipname.AppendChild(doc.CreateTextNode(shipnameval));
                shipto.AppendChild(shipname);

                System.Xml.XmlElement shipstreet1 = doc.CreateElement("Street1");
                shipstreet1.AppendChild(doc.CreateTextNode(shipstreet1val));
                shipto.AppendChild(shipstreet1);

                System.Xml.XmlElement shipstreet2 = doc.CreateElement("Street2");
                shipstreet2.AppendChild(doc.CreateTextNode(shipstreet2val));
                shipto.AppendChild(shipstreet2);

                System.Xml.XmlElement shipstreet3 = doc.CreateElement("Street3");
                shipstreet3.AppendChild(doc.CreateTextNode(shipstreet3val));
                shipto.AppendChild(shipstreet3);

                System.Xml.XmlElement shipcity = doc.CreateElement("City");
                shipcity.AppendChild(doc.CreateTextNode(shipcityval));
                shipto.AppendChild(shipcity);

                System.Xml.XmlElement shipstateprov = doc.CreateElement("StateProv");
                shipstateprov.AppendChild(doc.CreateTextNode(shipstateprovval));
                shipto.AppendChild(shipstateprov);

                System.Xml.XmlElement shippostalcode = doc.CreateElement("PostalCode");
                shippostalcode.AppendChild(doc.CreateTextNode(shippostalcodeval));
                shipto.AppendChild(shippostalcode);


                System.Xml.XmlElement extra = doc.CreateElement("Extra");
                extra.AppendChild(doc.CreateTextNode(extraval));
                cc5Request.AppendChild(extra);
                String xmlval = doc.OuterXml;         //Oluşturulan xml string olarak alınıyor.
                                                      // Ödeme için bağlantı kuruluyor. ve post ediliyor
                String url = "https://<DonusApiAdresi>/fim/api";
                System.Net.HttpWebResponse resp = null;
                try
                {
                    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                    string postdata      = "DATA=" + xmlval.ToString();
                    byte[] postdatabytes = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(postdata);
                    request.Method        = "POST";
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = postdatabytes.Length;
                    System.IO.Stream requeststream = request.GetRequestStream();
                    requeststream.Write(postdatabytes, 0, postdatabytes.Length);
                    requeststream.Close();

                    resp = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.StreamReader responsereader = new System.IO.StreamReader(resp.GetResponseStream(), System.Text.Encoding.GetEncoding("ISO-8859-9"));



                    String gelenXml = responsereader.ReadToEnd();     //Gelen xml string olarak alındı.


                    System.Xml.XmlDocument gelen = new System.Xml.XmlDocument();
                    gelen.LoadXml(gelenXml);        //string xml dökumanına çevrildi.

                    System.Xml.XmlNodeList list = gelen.GetElementsByTagName("Response");
                    String xmlResponse          = list[0].InnerText;
                    list = gelen.GetElementsByTagName("AuthCode");
                    String xmlAuthCode = list[0].InnerText;
                    list = gelen.GetElementsByTagName("HostRefNum");
                    String xmlHostRefNum = list[0].InnerText;
                    list = gelen.GetElementsByTagName("ProcReturnCode");
                    String xmlProcReturnCode = list[0].InnerText;
                    list = gelen.GetElementsByTagName("TransId");
                    String xmlTransId = list[0].InnerText;
                    list = gelen.GetElementsByTagName("ErrMsg");
                    String xmlErrMsg = list[0].InnerText;
                    if ("Approved".Equals(xmlResponse))
                    {
                        Response.Write("Ödeme başarıyla gerçekleştirildi");
                    }
                    else
                    {
                        Response.Write("Ödemede hata oluştu");
                    }
                    resp.Close();
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }
                finally
                {
                    if (resp != null)
                    {
                        resp.Close();
                    }
                }
            }
            else
            {
                Response.Write("3D Onayı alınamadı");
            }
            return(View());
        }
Beispiel #13
0
        /// <summary>
        /// Attempts to download the Uri and (based on it's MimeType) use the DocumentFactory
        /// to get a Document subclass object that is able to parse the downloaded data.
        /// </summary>
        /// <remarks>
        /// http://www.123aspx.com/redir.aspx?res=28320
        /// </remarks>
        protected Document Download(Uri uri)
        {
            bool success = false;

            // Open the requested URL
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri.AbsoluteUri);
            req.AllowAutoRedirect            = true;
            req.MaximumAutomaticRedirections = 3;
            req.UserAgent = Preferences.UserAgent;             //"Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Searcharoo.NET)";
            req.KeepAlive = true;
            req.Timeout   = Preferences.RequestTimeout * 1000; //prefRequestTimeout

            // SIMONJONES http://codeproject.com/aspnet/spideroo.asp?msg=1421158#xx1421158xx
            req.CookieContainer = new System.Net.CookieContainer();
            req.CookieContainer.Add(_CookieContainer.GetCookies(uri));

            // Get the stream from the returned web response
            System.Net.HttpWebResponse webresponse = null;
            try
            {
                webresponse = (System.Net.HttpWebResponse)req.GetResponse();
            }
            catch (System.Net.WebException we)
            {   //remote url not found, 404; remote url forbidden, 403
                ProgressEvent(this, new ProgressEventArgs(2, "skipped  " + uri.AbsoluteUri + " response exception:" + we.ToString() + ""));
            }

            Document htmldoc = null;

            if (webresponse != null)
            {
                /* SIMONJONES */

                /* **************** this doesn't necessarily work yet...
                 * if (webresponse.ResponseUri != htmldoc.Uri)
                 * {	// we've been redirected,
                 *  if (visited.Contains(webresponse.ResponseUri.ToString().ToLower()))
                 *  {
                 *      return true;
                 *  }
                 *  else
                 *  {
                 *      visited.Add(webresponse.ResponseUri.ToString().ToLower());
                 *  }
                 * }*/

                try
                {
                    webresponse.Cookies = req.CookieContainer.GetCookies(req.RequestUri);
                    // handle cookies (need to do this incase we have any session cookies)
                    foreach (System.Net.Cookie retCookie in webresponse.Cookies)
                    {
                        bool cookieFound = false;
                        foreach (System.Net.Cookie oldCookie in _CookieContainer.GetCookies(uri))
                        {
                            if (retCookie.Name.Equals(oldCookie.Name))
                            {
                                oldCookie.Value = retCookie.Value;
                                cookieFound     = true;
                            }
                        }
                        if (!cookieFound)
                        {
                            _CookieContainer.Add(retCookie);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ProgressEvent(this, new ProgressEventArgs(3, "Cookie processing error : " + ex.Message + ""));
                }
                /* end SIMONJONES */

                htmldoc = DocumentFactory.New(uri, webresponse);
                success = htmldoc.GetResponse(webresponse);
                webresponse.Close();
                ProgressEvent(this, new ProgressEventArgs(2, "Trying index mime type: " + htmldoc.MimeType + " for " + htmldoc.Uri + ""));
            }
            else
            {
                ProgressEvent(this, new ProgressEventArgs(2, "No WebResponse for " + uri + ""));
                success = false;
            }
            return(htmldoc);
        }
Beispiel #14
0
        private void addFeedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string newUrl = Microsoft.VisualBasic.Interaction.InputBox(_I18N.GetText("Enter URL:"), Application.ProductName);

            if (newUrl.Length == 0)
            {
                return;
            }
            this.staMain.Text = "";
            if (!newUrl.ToLowerInvariant().StartsWith("http"))
            {
                // TODO add https?
                newUrl = "http://" + newUrl;
            }
            //The MSDN documentation says it's best to create an XmlTextReader through .Create
            //rather than = new XmlTextReader. However, if you do it through new, you get an
            //XmlTextReader that doesn't choke on malformed XML, and if you do it through
            //.Create you choke on malformed XML. So clearly new is better!
            System.Xml.XmlTextReader xtr;
            try
            {
                xtr = new System.Xml.XmlTextReader(newUrl);
            }
            catch (System.UriFormatException ufe)
            {
                // Not a valid URL. Skip trying to analyse.
                MessageBox.Show(_I18N.GetText("Invalid URL:") + " " + ufe.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            catch (Exception ex)
            {
                // Unknown error - File Not Found, possibly - display and quit.
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string newFeedUrl        = "";
            string rootNodeName      = "";
            bool   finishedSearching = false;
            bool   readOK            = true;

            while (!xtr.EOF && !finishedSearching && readOK)
            {
                try
                {
                    readOK = xtr.Read();
                    if (xtr.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        string elementName = xtr.Name.ToLowerInvariant();
                        // If this is the first node then it is the root node.
                        // Remember the name so that we know what type of document
                        // the user has given us - Atom, RSS, or a web page to
                        // search.
                        System.Diagnostics.Debug.Print("Node:" + elementName);
                        if (rootNodeName.Length == 0)
                        {
                            rootNodeName = elementName;
                        }
                        if (rootNodeName == "html")
                        {
                            // This is an HTML file, scan it for RSS feeds.
                            if (elementName == "link")
                            {
                                // Got a link: is it valid?
                                if (xtr.HasAttributes)
                                {
                                    string href = xtr.GetAttribute("href");
                                    string rel  = xtr.GetAttribute("rel");
                                    if (rel.ToLowerInvariant() == "alternate" && href != "")
                                    {
                                        // Got it!
                                        newFeedUrl        = href;
                                        finishedSearching = true;
                                    }
                                }
                            }
                        }
                        else if (rootNodeName == "feed" || rootNodeName == "rss")
                        {
                            // It's an RSS/Atom feed, go ahead and add it
                            // without further checking, and stop reading
                            // this document.
                            newFeedUrl        = newUrl;
                            finishedSearching = true;
                        }
                    }
                }
                catch
                {
                    //Parsing error from the web page or XML = very common, carry on going
                    //until we find something useful.
                }
                System.Windows.Forms.Application.DoEvents();
            }
            xtr.Close();

            // OK, so we've examined the url the user gave us. Found anything?
            if (newFeedUrl == "")
            {
                // Failed to find anything!
                MessageBox.Show(_I18N.GetText("No RSS news feeds found"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                // OK, try getting it.
                System.Xml.XmlTextReader newFeed = new System.Xml.XmlTextReader(newFeedUrl);
                string newTitle             = "";
                string newWebsiteUrl        = "";
                bool   foundTitleAndUrl     = false;
                bool   nextNodeIsTitle      = false;
                bool   nextNodeIsWebsiteUrl = false;
                readOK = true;
                while (!newFeed.EOF && !foundTitleAndUrl && readOK)
                {
                    try
                    {
                        readOK = newFeed.Read();
                        if (newFeed.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            System.Diagnostics.Debug.Print("Node:" + newFeed.Name.ToLowerInvariant());
                            if (newFeed.Name.ToLowerInvariant() == "title")
                            {
                                if (newTitle == "")
                                {
                                    nextNodeIsTitle = true;
                                }
                            }
                            else if (newFeed.Name.ToLowerInvariant() == "link")
                            {
                                if (newWebsiteUrl == "")
                                {
                                    nextNodeIsWebsiteUrl = true;
                                }
                            }
                        }
                        else if (newFeed.NodeType == System.Xml.XmlNodeType.Text)
                        {
                            if (nextNodeIsTitle)
                            {
                                newTitle        = newFeed.Value;
                                nextNodeIsTitle = false;
                            }
                            if (nextNodeIsWebsiteUrl)
                            {
                                newWebsiteUrl        = newFeed.Value;
                                nextNodeIsWebsiteUrl = false;
                            }
                        }
                    }
                    catch
                    {
                        // Error in XML, very common, carry on.
                    }
                    if (newTitle.Length > 0 && newWebsiteUrl.Length > 0)
                    {
                        foundTitleAndUrl = true;
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                newFeed.Close();
                // OK, add to lists!
                if (foundTitleAndUrl)
                {
                    // Assume this is good.
                    this._Library.AddFeed(newFeedUrl, newTitle, newWebsiteUrl);
                    DisplayFeeds();
                    lblStatus.Text = _I18N.GetText("Added:") + " " + newTitle;
                    // Set focus to the new feed.
                    try
                    {
                        int i = 0;
                        foreach (System.Xml.XmlNode outline in this._Library.MyFeedsOPMLDocument.DocumentElement.SelectNodes("body/outline"))
                        {
                            string url = RSSLibraryClass.GetOutlineUrl(outline);
                            if (url == newFeedUrl)
                            {
                                lstFeeds.SelectedIndex = i;
                                break;
                            }
                            i++;
                        }
                    }
                    catch
                    {
                        // Fine, didn't set focus, carry on.
                    }

                    try
                    {
                        // Submission of RSS feed to database.
                        newTitle = System.Net.WebUtility.HtmlEncode(newTitle);
                        newUrl   = System.Net.WebUtility.HtmlEncode(newUrl);
                        System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://data.webbie.org.uk/newRSSFeed.php?title=" + newTitle + "&url=" + newFeedUrl + "&language=" + this._I18N.GetLanguage());
                        wr.KeepAlive         = false;
                        wr.Method            = System.Net.WebRequestMethods.Http.Get;
                        wr.ContentType       = "text/html";
                        wr.AllowAutoRedirect = true;
                        wr.GetResponse();
                    }
                    catch
                    {
                        // Failed to connect and write feed information: record why to error log.
                        System.Diagnostics.EventLog.WriteEntry(Application.ProductName + " " + Application.ProductVersion, "Failed to submit new feed registration to WebbIE (" + newUrl + ")");
                    }
                }
                else
                {
                    // Not found a feed.
                    staMain.Text = this._I18N.GetText("0 feeds found.");
                }
            }
        }
Beispiel #15
0
        internal static Image getQRImage(byte[] data, string server)
        {
            string qrdata  = Convert.ToBase64String(data);
            string message = server + qrdata;
            string webURL  = "http://chart.apis.google.com/chart?chs=365x365&cht=qr&chl=" + System.Web.HttpUtility.UrlEncode(message);

            try
            {
                System.Net.HttpWebRequest  httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(webURL);
                System.Net.HttpWebResponse httpWebReponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                Stream stream = httpWebReponse.GetResponseStream();
                if (stream != null)
                {
                    return(Image.FromStream(stream));
                }
            }
            catch
            {
                if (Prompt(MessageBoxButtons.YesNo,
                           "Unable to connect to the internet to receive QR code.",
                           "Copy QR URL to Clipboard?")
                    != DialogResult.Yes)
                {
                    return(null);
                }
                try { Clipboard.SetText(webURL); }
                catch { Alert("Failed to set text to Clipboard"); }
            }
            return(null);
        }
Beispiel #16
0
        public Dictionary <KeyValuePair <NeedDownloadFile, string>, Exception> Download(DownloadingEventHandler downloadingEvent)
        {
            Dictionary <KeyValuePair <NeedDownloadFile, string>, Exception> FAILURES = new Dictionary <KeyValuePair <NeedDownloadFile, string>, Exception>();
            Task distri = new Task(() =>
            {
                List <Task> threads = new List <Task>();
                Dictionary <NeedDownloadFile, string> unDownloadFiles = new Dictionary <NeedDownloadFile, string>();
                int unDownloadedFiles = 0;
                float percentall      = 0;
                int addedcount        = 0;
                foreach (var file in keyValuePairs)
                {
                    unDownloadFiles.Add(file.Key, file.Value);
                    unDownloadedFiles++;
                    PERcents.Add(file, 0f);
                }
                Dictionary <NeedDownloadFile, string> downloadedFiles = new Dictionary <NeedDownloadFile, string>();
                for (int i = 0; i < DownloadSettings.MaxThreads; i++)
                {
                    threads.Add(new Task(() =>
                    {
                        while (true)
                        {
                            bool needDownload = true;
                            KeyValuePair <NeedDownloadFile, string> file = new KeyValuePair <NeedDownloadFile, string>();
                            lock (unDownloadFiles)
                            {
                                if (unDownloadFiles.Count == 0)
                                {
                                    return;
                                }
                                file = unDownloadFiles.First();
                                if (File.Exists(file.Value))
                                {
                                    string hash = HashHelper.ComputeSHA1(file.Value);
                                    if (hash == file.Key.Hash)
                                    {
                                        needDownload = false;
                                        percentall  += 1;
                                        Logger.LogInfo("Need not Download : " + file.Key.FileName);

                                        downloadedFiles.Add(file.Key, file.Value);
                                        unDownloadFiles.Remove(unDownloadFiles.First().Key);
                                    }
                                }
                                if (needDownload)
                                {
                                    unDownloadFiles.Remove(unDownloadFiles.First().Key);
                                }
                            }

                            if (needDownload)
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(file.Value));
                                Logger.LogInfo("Download File:" + file.Key.FileName);
                                //Download Paragraph
                                {
                                    try
                                    {
                                        System.Net.HttpWebRequest Myrq  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(file.Key.FileName);
                                        System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                                        long totalBytes          = myrp.ContentLength;
                                        System.IO.Stream st      = myrp.GetResponseStream();
                                        System.IO.Stream so      = new System.IO.FileStream(file.Value, System.IO.FileMode.Create);
                                        long totalDownloadedByte = 0;
                                        byte[] by = new byte[1024];
                                        int osize = st.Read(by, 0, (int)by.Length);
                                        while (osize > 0)
                                        {
                                            totalDownloadedByte = osize + totalDownloadedByte;
                                            so.Write(by, 0, osize);
                                            osize          = st.Read(by, 0, (int)by.Length);
                                            PERcents[file] = (float)totalDownloadedByte / (float)totalBytes;
                                            addedcount++;
                                        }
                                        so.Close();
                                        st.Close();
                                    }
                                    catch (System.Exception ex)
                                    {
                                        if (file.Key.FileName2 == null)
                                        {
                                            FAILURES.Add(file, ex);
                                            Logger.LogInfo("DownloadFileFAIL:" + file.Value + ex);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                System.Net.HttpWebRequest Myrq  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(file.Key.FileName2);
                                                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                                                long totalBytes          = myrp.ContentLength;
                                                System.IO.Stream st      = myrp.GetResponseStream();
                                                System.IO.Stream so      = new System.IO.FileStream(file.Value, System.IO.FileMode.Create);
                                                long totalDownloadedByte = 0;
                                                byte[] by = new byte[1024];
                                                int osize = st.Read(by, 0, (int)by.Length);
                                                while (osize > 0)
                                                {
                                                    totalDownloadedByte = osize + totalDownloadedByte;
                                                    so.Write(by, 0, osize);
                                                    osize          = st.Read(by, 0, (int)by.Length);
                                                    PERcents[file] = (float)totalDownloadedByte / (float)totalBytes;
                                                    addedcount++;
                                                }
                                                so.Close();
                                                st.Close();
                                            }
                                            catch (System.Exception exm)
                                            {
                                                FAILURES.Add(file, exm);
                                                Logger.LogInfo("DownloadFileFAIL:" + file.Value + exm);
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        downloadedFiles.Add(file.Key, file.Value);
                                        Logger.LogInfo("DownloadedFile:" + file.Value);
                                    }
                                }
                            }
                            PERcents[file] = 1;
                            unDownloadedFiles--;
                        }
                    }));
                }
                Thread report = new Thread(() =>
                {
                    float lp = 0;
                    while (true)
                    {
                        float pa = 0;
                        try
                        {
                            foreach (var p in PERcents)
                            {
                                pa += p.Value;
                            }
                            lp = pa;
                        }
                        catch
                        {
                            pa = lp;
                        }

                        downloadingEvent(pa / PERcents.Count);
                        Thread.Sleep(600);
                    }
                });
                report.Start();

                foreach (var thread in threads)
                {
                    thread.Start();
                }
                while (downloadedFiles.Count != keyValuePairs.Count)
                {
                    Thread.Sleep(600);
                }
                report.Abort();
                report.DisableComObjectEagerCleanup();
                Logger.LogInfo("Event That");
            });

            distri.Start();
            distri.Wait();
            Thread.Sleep(100);
            return(FAILURES);
        }
Beispiel #17
0
        protected void Application_End()
        {
            #region 访问首页,重启数据池
            string hosturl = SiteStaticInfo.CurDomainUrl;
#if DEBUG
            Himall.Core.Log.Info(System.DateTime.Now.ToString() + " -  " + hosturl);
#endif
            if (!string.IsNullOrWhiteSpace(hosturl))
            {
                System.Net.HttpWebRequest  myHttpWebRequest  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(hosturl);
                System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
            }
            #endregion
        }
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                System.Console.WriteLine("nwget <output> <URI>");
                return;
            }

            try
            {
                System.Uri remote;
                if (System.Uri.TryCreate(args[1], System.UriKind.Absolute, out remote) == false)
                {
                    System.Console.Error.WriteLine("**error: URI {0} is bad format.", args[1]);
                    System.Environment.Exit(-1);
                }
                System.Net.HttpWebRequest myHttpWebRequest = null;
                try
                {
                    myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remote);
                }
                catch (System.Exception)
                {
                    System.Console.Error.WriteLine("**error: URI {0} is bad format or not supported.", args[1]);
                    System.Environment.Exit(-1);
                }
                myHttpWebRequest.MaximumAutomaticRedirections = 10;
                myHttpWebRequest.AllowAutoRedirect            = true;

                System.Console.WriteLine("recive from {0}", remote.AbsoluteUri);
                var myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
                using (var output = System.IO.File.OpenWrite(args[0]))
                    using (var input = myHttpWebResponse.GetResponseStream())
                    {
                        if (input != null)
                        {
                            var  contentLength = myHttpWebResponse.ContentLength;
                            long reciveLength  = 0;
                            var  buffer        = new byte[8192];
                            int  bytesRead;
                            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                reciveLength += bytesRead;
                                output.Write(buffer, 0, bytesRead);
                                System.Console.Write("Recive: {0}  / {1} [byte] ({2}%)\r", reciveLength, contentLength, reciveLength * 100 / contentLength);
                            }
                            System.Console.WriteLine("\nRecive completed");
                            System.Environment.Exit(0);
                        }
                        else
                        {
                            System.Console.Error.WriteLine("**error: Cannot recive data.");
                            System.Environment.Exit(-1);
                        }
                    }
            }
            catch (System.Net.WebException e)
            {
                if (e.Status == System.Net.WebExceptionStatus.ProtocolError)
                {
                    System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)e.Response;
                    System.Console.Error.WriteLine("**error: {0} - {1}", myHttpWebResponse.StatusCode,
                                                   myHttpWebResponse.StatusDescription);
                    System.Environment.Exit(-1);
                }
                else if (e.Status == System.Net.WebExceptionStatus.Timeout)
                {
                    System.Console.Error.WriteLine("**error: Download is timeout.");
                    System.Environment.Exit(-1);
                }
                else
                {
                    ExceptionHandler(e, "Recive Failed.");
                }
            }
            catch (System.Exception e)
            {
                ExceptionHandler(e, "Recive Failed.");
            }
        }
Beispiel #19
0
        private void btnBuscarCep_Click(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(txtCep.Text.Replace("-", "")) || txtCep.Text.Replace("-", "").Length < 8)
                {
                    MessageBox.Show("Informe um CEP válido!");
                    return;
                }


                System.Net.HttpWebRequest requisicao = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://viacep.com.br/ws/" + txtCep.Text.Replace("-", "") + "/json/");

                requisicao.AllowAutoRedirect = false;
                System.Net.HttpWebResponse ChecaServidor = (System.Net.HttpWebResponse)requisicao.GetResponse();

                if (ChecaServidor.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    MessageBox.Show("Servidor indisponível");
                    return;
                }


                using (Stream webStream = ChecaServidor.GetResponseStream())
                {
                    if (webStream != null)
                    {
                        using (StreamReader responseReader = new StreamReader(webStream))
                        {
                            string response = responseReader.ReadToEnd();
                            response = System.Text.RegularExpressions.Regex.Replace(response, "[{},]", string.Empty);
                            response = response.Replace("\"", "");

                            String[] substrings = response.Split('\n');

                            int cont = 0;
                            foreach (var substring in substrings)
                            {
                                if (cont == 1)
                                {
                                    string[] valor = substring.Split(":".ToCharArray());
                                    if (valor[0] == "  erro")
                                    {
                                        MessageBox.Show("CEP não encontrado");
                                        txtCep.Focus();
                                        return;
                                    }
                                }

                                //Logradouro
                                if (cont == 2)
                                {
                                    string[] valor = substring.Split(":".ToCharArray());
                                    txtLogradouro.Text = valor[1];
                                }

                                //Bairro
                                if (cont == 4)
                                {
                                    string[] valor = substring.Split(":".ToCharArray());
                                    txtBairro.Text = valor[1];
                                }

                                //Localidade (Cidade)
                                if (cont == 5)
                                {
                                    string[] valor = substring.Split(":".ToCharArray());
                                    txtCidade.Text = valor[1];
                                }

                                //Estado (UF)
                                if (cont == 6)
                                {
                                    string[] valor = substring.Split(":".ToCharArray());
                                    cbxUF.SelectedItem = valor[1].Trim();
                                }

                                cont++;
                            }
                        }
                    }
                }
            }
            catch (Exception erro)
            {
                MessageBox.Show("Algo deu errado. Detalhes: " + erro.Message);
            }
        }
Beispiel #20
0
        public void ProcessRequest(HttpContext context)
        {
            string url = HttpUtility.UrlDecode(context.Request.QueryString.ToString());

            if (url == "")
            {
                context.Response.Write("PilotGaea O'view Map Server(" + (IntPtr.Size * 8).ToString() + " bits) " + (m_Server.IsStart() ? "Start" : "Stop"));
                if (!m_Server.IsStart())
                {
                    context.Response.Write(m_Server.GetLastError());
                }
            }
            else
            {
                //轉給mapserver
                //判斷是GET還是POST
                bool   bPOST      = context.Request.InputStream.Length > 0;
                byte[] postBuffer = null;
                if (bPOST)//取得POST資料
                {
                    postBuffer = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(postBuffer, 0, postBuffer.Length);
                }
                System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
                req.Method = bPOST ? "POST" : "GET";
                if (bPOST)
                {
                    req.ContentLength = postBuffer.Length;
                    req.ContentType   = "application/json";
                }
                req.UserAgent = "PilotGaea Proxy Server";

                //複製檔頭的cookie
                System.Collections.Specialized.NameValueCollection headers = context.Request.Headers;
                for (int i = 0; i < headers.Count; i++)
                {
                    //context.Response.Write(headers.GetKey(i) + ":" + headers.Get(i) + "<BR>");
                    if (headers.GetKey(i) == "Cookie")
                    {
                        req.Headers.Set("Cookie", headers.Get(i));
                        break;
                    }
                }

                byte[] retBuffer = null;
                try
                {
                    if (bPOST)
                    {
                        //上傳
                        System.IO.Stream stream_req = req.GetRequestStream();
                        stream_req.Write(postBuffer, 0, postBuffer.Length);
                        stream_req.Flush();
                        stream_req.Close();
                    }

                    System.Net.HttpWebResponse res        = req.GetResponse() as System.Net.HttpWebResponse;
                    System.IO.Stream           stream_res = res.GetResponseStream();
                    int    len                = 1024 * 1024;
                    byte[] tmpBuffer          = new byte[len];//一次1MB
                    int    readlen            = 0;
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    do
                    {
                        readlen = stream_res.Read(tmpBuffer, 0, len);
                        ms.Write(tmpBuffer, 0, readlen);
                    }while (readlen > 0);
                    retBuffer = ms.ToArray();

                    //複製回應的檔頭
                    for (int i = 0; i < res.Headers.Count; i++)
                    {
                        string[] s = res.Headers.GetValues(i);
                        string   k = res.Headers.Keys[i];
                        string   v = "";
                        for (int j = 0; j < s.Length; j++)
                        {
                            if (j > 0)
                            {
                                v += ";";
                            }
                            v += s[j];
                        }
                        if (k == "Content-Type")
                        {
                            context.Response.ContentType = v;
                        }
                        else if (k == "Set-Cookie")
                        {
                            context.Response.SetCookie(new HttpCookie(v));
                        }
                        else if (k == "Last-Modified")
                        {
                            context.Response.Headers.Set(k, v);
                        }
                        else if (k == "Content-Encoding")
                        {
                            context.Response.Headers.Set(k, v);
                        }
                    }
                    //寫入回應的本文
                    context.Response.BinaryWrite(retBuffer);
                }
                catch (System.Net.WebException ex)
                {
                    if (ex.Response != null)
                    {
                        context.Response.StatusCode        = (int)(((System.Net.HttpWebResponse)ex.Response).StatusCode);
                        context.Response.StatusDescription = ((System.Net.HttpWebResponse)ex.Response).StatusDescription;
                    }
                    else
                    {
                        //通常是伺服器沒開
                        context.Response.StatusCode        = 500;
                        context.Response.StatusDescription = "Internal Server error:" + ex.Message;
                    }
                }
                catch (Exception ex)
                {
                    context.Response.StatusCode        = 404;
                    context.Response.StatusDescription = "File not found:" + ex.Message;
                }
            }
        }
Beispiel #21
0
        private string HeadBack(string PlayerName)
        {
            //string ValueURL = "";
            //HttpWebRequest ValueURLRequest = (HttpWebRequest)WebRequest.Create("http://skins.minecraft.net/MinecraftSkins/" + PlayerName + ".png");
            //ValueURLRequest.Method = "GET";
            //ValueURL = ValueURLRequest.GetResponse().ResponseUri.ToString();
            //http://textures.minecraft.net/texture/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

            string GetUUID = "";

            System.Net.HttpWebRequest GetUUIDRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://api.mojang.com/users/profiles/minecraft/" + PlayerName);
            GetUUIDRequest.Method = "GET";
            try
            {
                using (System.Net.WebResponse response = GetUUIDRequest.GetResponse())
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        GetUUID = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception) { }
            //{"id":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","name":"xxxxxx"}

            string[] uuidArray = GetUUID.Split('"');
            string   uuid      = "";
            string   aUUID     = "";

            if (uuidArray.Count() >= 3)
            {
                uuid  = uuidArray[3];
                aUUID = uuid.Substring(0, 8) + "-" + uuid.Substring(8, 4) + "-" + uuid.Substring(12, 4) + "-" + uuid.Substring(16, 4) + "-" + uuid.Substring(20, 12);
            }
            else
            {
                uuid  = "uuidCatchFailed";
                aUUID = "uuidCatchFailed";
            }

            string GetStr = "";

            System.Net.HttpWebRequest GetStrRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
            GetStrRequest.Method = "GET";
            try
            {
                using (System.Net.WebResponse response = GetStrRequest.GetResponse())
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        GetStr = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception) { }

            GetStr = GetStr.Replace("\"id\":", "Id:");
            GetStr = GetStr.Replace("\"name\":", "SkullOwner:");
            GetStr = GetStr.Replace("\"properties\":[{", "Properties:{textures:[{");
            GetStr = GetStr.Replace("\"name\":\"textures\",", "");
            GetStr = GetStr.Replace("\"value\":", "Value:");
            GetStr = GetStr.Replace("\"signature\":", "Signature:");
            GetStr = GetStr.Replace("}]}", "}]}}");

            GetStr = GetStr.Replace(uuid, aUUID);
            GetStr = GetStr.Replace("SkullOwner:\"" + PlayerName + "\",", "");
            GetStr = GetStr.Replace("SkullOwner:\"textures\",", "");

            string outputStr = "{display:{Name:\"" + PlayerName + "\"},SkullOwner:" + GetStr + "}";

            //string ValueStr = "{\"profileId\":\"" + uuid + "\",\"profileName\":\"" + PlayerName + "\",\"textures\":{\"SKIN\":{\"url\":\"" + ValueURL + "\"}}}";
            //string base64ed = Base64Encode(ValueStr);
            //string mainStr = "{SkullOwner:\"" + PlayerName + "\",Id:\"" + uuid + "\",Properties:{textures:[{Value:\"" + base64ed + "\"}]}}";
            string endStr = "/give @p minecraft:skull 1 3 " + outputStr;

            finalStr = endStr;
            return(finalStr);
        }
Beispiel #22
0
        public ZDSXmlDocument PerformRequest(ZDSXmlDocument requestdocument)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(soapurl);
            request.Headers.Add(@"SOAPAction", soapaction);
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Accept      = "text/xml";
            request.Method      = "POST";

            System.Diagnostics.Debug.WriteLine("--------------------------------------------------------------");
            System.Diagnostics.Debug.WriteLine(soapurl);
            System.Diagnostics.Debug.WriteLine("SOAPAction:" + soapaction);
            System.Diagnostics.Debug.WriteLine("--------------------------------------------------------------");
            System.Diagnostics.Debug.WriteLine("request xml:");
            System.Diagnostics.Debug.WriteLine(requestdocument.OuterXml);
            System.Diagnostics.Debug.WriteLine("--------------------------------------------------------------");

            using (System.IO.Stream stream = request.GetRequestStream())
            {
                try
                {
                    requestdocument.Save(stream);
                    using (System.Net.WebResponse response = request.GetResponse())
                    {
                        using (System.IO.StreamReader rd = new System.IO.StreamReader(response.GetResponseStream()))
                        {
                            var responsedocument = new ZDSXmlDocument(rd);

                            System.Diagnostics.Debug.WriteLine("--------------------------------------------------------------");
                            System.Diagnostics.Debug.WriteLine("response xml:");
                            System.Diagnostics.Debug.WriteLine(responsedocument.OuterXml);
                            System.Diagnostics.Debug.WriteLine("--------------------------------------------------------------");
                            return(responsedocument);
                        }
                    }
                }
                catch (System.Net.WebException wex)
                {
                    var       errorstream        = wex.Response.GetResponseStream();
                    var       errorreader        = new System.IO.StreamReader(errorstream, Encoding.UTF8);
                    const int MAX_MESSAGE_LENGTH = 5000;
                    String    errormessage       = errorreader.ReadToEnd();
                    if (errormessage.Length > MAX_MESSAGE_LENGTH)
                    {
                        errormessage = errormessage.Substring(0, MAX_MESSAGE_LENGTH) + "... (" + errormessage.Length + " characters)";
                    }
                    String requestxml = requestdocument.OuterXml;
                    if (requestxml.Length > MAX_MESSAGE_LENGTH)
                    {
                        requestxml = requestxml.Substring(0, MAX_MESSAGE_LENGTH) + "... (" + requestxml.Length + " characters)";
                    }

                    throw new ZDSSoapServiceException(
                              "soap url: " + soapurl + "\n" +
                              "soap action: " + soapaction + "\n" +
                              "\n-- request ---------------------------------------------------------------------\n" +
                              requestxml + "\n" +
                              "\n\n-- response " + wex.Message + "---------------------------------------------------------------------\n" +
                              errormessage,
                              wex
                              );
                    //throw wex;
                }
            }
        }
Beispiel #23
0
        public Robots(Uri startPageUri, string userAgent, bool debug = false)
        {
            _UserAgent = userAgent;
            _Server    = startPageUri.Host;

            try
            {
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://" + startPageUri.Authority + "/robots.txt");
                req.UserAgent = Browser.UserAgent;
                req.Accept    = "text/plain";
                System.Net.HttpWebResponse webresponse = (System.Net.HttpWebResponse)req.GetResponse();

                using (System.IO.StreamReader stream = new System.IO.StreamReader(webresponse.GetResponseStream(), Encoding.ASCII))
                {
                    _FileContents = stream.ReadToEnd();
                }

                string[] fileLines = _FileContents.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                if (fileLines.Length < 2)
                {
                    fileLines = _FileContents.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                }

                bool rulesApply = false;
                foreach (string line in fileLines)
                {
                    RobotInstruction ri = new RobotInstruction(line);
                    if (ri.Instruction.Length < 1)
                    {
                        continue;
                    }
                    switch (ri.Instruction.TrimStart()[0]) // trim as leading whitespace before comments is valid http://www.robotstxt.org/orig.html
                    {
                    case '#':                              //then comment - ignore
                        break;

                    case 'u':       // User-Agent
                        if ((ri.UrlOrAgent == "*") ||
                            (ri.UrlOrAgent.IndexOf(_UserAgent) >= 0))
                        {     // these rules apply
                            rulesApply = true;
                            if (debug)
                            {
                                Console.WriteLine(ri.UrlOrAgent + " " + rulesApply);
                            }
                        }
                        else
                        {
                            rulesApply = false;
                        }
                        break;

                    case 'd':       // Disallow
                        if (rulesApply)
                        {
                            _DenyUrls.Add(ri.UrlOrAgent.ToLower());
                            if (debug)
                            {
                                Console.WriteLine("D " + ri.UrlOrAgent);
                            }
                        }
                        else
                        {
                            if (debug)
                            {
                                Console.WriteLine("D " + ri.UrlOrAgent + " is for another user-agent");
                            }
                        }
                        break;

                    case 'a':       // Allow
                        if (debug)
                        {
                            Console.WriteLine("A" + ri.UrlOrAgent);
                        }
                        break;

                    case 'c':
                        if (rulesApply)
                        {
                            if (debug)
                            {
                                Console.WriteLine("C " + ri.UrlOrAgent);
                            }
                            _crawlDelay = Math.Abs(Convert.ToInt32(ri.UrlOrAgent));
                        }
                        break;

                    default:
                        // empty/unknown/error
                        Console.WriteLine("Unrecognised robots.txt entry [" + line + "]");

                        break;
                    }
                }
            }
            catch (System.Net.WebException)
            {
                _FileContents = String.Empty;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Robots exception");
                Console.WriteLine("Will continue, but will be extra cautious as it could be our fault");
                Console.WriteLine("Attempted URL was " + "http://" + startPageUri.Authority + "/robots.txt");
                Console.WriteLine(ex.Message);
                _crawlDelay   = 20;
                _FileContents = String.Empty;
            }
        }
Beispiel #24
0
        /// <summary>
        /// 获取微信JSAPI支付对象
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="totalAmount">订单金额</param>
        /// <param name="appId">微信公众号AppId</param>
        /// <param name="mchId">微信商户号</param>
        /// <param name="key">支付密钥</param>
        /// <param name="openId">用户OpenId</param>
        /// <param name="ip">用户的IP</param>
        /// <param name="notifyUrl">通知地址</param>
        /// <param name="body">订单内容</param>
        /// <param name="tradeType">交易类型</param>
        /// <returns></returns>
        public static WXPayRequest GetBrandWcPayRequest(string orderId, decimal totalAmount, string appId, string mchId, string key, string openId, string ip, string notifyUrl, out bool isSuccess, string body = "", string tradeType = "")
        {
            isSuccess = false;
            string backStr = "";

            try
            {
                string nonStr = CommonUtil.CreateNoncestr();//随机串
                #region 获取微信支付预支付ID
                //第一次签名
                SortedDictionary <string, string> dicStep1 = new SortedDictionary <string, string>();
                dicStep1.Add("appid", appId);
                dicStep1.Add("body", !string.IsNullOrEmpty(body) ? body : string.Format("订单号:{0}", orderId));
                dicStep1.Add("mch_id", mchId);
                dicStep1.Add("nonce_str", nonStr);
                dicStep1.Add("out_trade_no", orderId);
                dicStep1.Add("openid", openId);
                dicStep1.Add("spbill_create_ip", ip);
                dicStep1.Add("total_fee", (totalAmount * 100).ToString("F0"));
                dicStep1.Add("notify_url", notifyUrl);
                if (!string.IsNullOrEmpty(tradeType))
                {
                    dicStep1.Add("trade_type", tradeType);
                }
                else
                {
                    dicStep1.Add("trade_type", "JSAPI");
                }
                string strTemp1 = CommonUtil.FormatBizQueryParaMap(dicStep1, false);
                string sign     = MD5SignUtil.Sign(strTemp1, key);
                //dicStep1 = (from entry in dicStep1
                //            orderby entry.Key ascending
                //            select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
                dicStep1.Add("sign", sign);
                string postData = CommonUtil.ArrayToXml(dicStep1);
                string url      = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                byte[] requestBytes           = System.Text.Encoding.UTF8.GetBytes(postData);
                req.Method        = "POST";
                req.ContentType   = "application/x-www-form-urlencoded";
                req.ContentLength = requestBytes.Length;
                System.IO.Stream requestStream = req.GetRequestStream();
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();
                System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
                System.IO.StreamReader     sr  = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
                backStr = sr.ReadToEnd();
                sr.Close();
                res.Close();
                var result     = System.Xml.Linq.XDocument.Parse(backStr);
                var returnCode = result.Element("xml").Element("return_code").Value;
                if (returnCode.ToUpper() == "FAIL")
                {
                    return(null);
                }
                string preId      = "";
                var    rusultCode = result.Element("xml").Element("result_code").Value;

                if (returnCode.ToUpper().Equals("SUCCESS") && (rusultCode.ToUpper().Equals("SUCCESS")))
                {
                    preId = result.Element("xml").Element("prepay_id").Value;
                }
                #endregion
                #region 生成微信支付请求
                WXPayRequest wxPayReq   = new WXPayRequest();
                string       timesStamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                wxPayReq.appId     = appId;
                wxPayReq.nonceStr  = nonStr;
                wxPayReq.package   = "prepay_id=" + preId;
                wxPayReq.signType  = "MD5";
                wxPayReq.timeStamp = timesStamp;
                //第二次签名
                SortedDictionary <string, string> dicStep2 = new SortedDictionary <string, string>();
                dicStep2.Add("appId", wxPayReq.appId);
                dicStep2.Add("timeStamp", wxPayReq.timeStamp);
                dicStep2.Add("nonceStr", wxPayReq.nonceStr);
                dicStep2.Add("package", wxPayReq.package);
                dicStep2.Add("signType", "MD5");
                string strTemp2 = CommonUtil.FormatQueryParaMap(dicStep2);
                string paySign  = MD5SignUtil.Sign(strTemp2, key);
                wxPayReq.paySign = paySign;
                isSuccess        = true;
                return(wxPayReq);

                #endregion
            }
            catch (Exception ex)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"E:\WXPay\Error.txt", true, Encoding.GetEncoding("UTF-8")))
                {
                    sw.WriteLine(backStr);
                }
                //return System.Xml.Linq.XDocument.Parse(backStr).Element("xml").Element("return_msg").Value;
                return(null);
            }
        }
Beispiel #25
0
        /// <summary>
        /// 附件下载
        /// </summary>
        /// <param name="infoUrl"></param>
        private void AddBaseFile(string infoUrl, string strFileName, NotifyInfo info)
        {
            string pathName    = System.IO.Path.GetExtension(strFileName.ToLower());
            string path        = ToolDb.NewGuid + pathName;
            string strFileUrl  = ToolDb.DbServerPath + "SiteManage\\Files\\Notify_Attach\\";
            string strFile     = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "\\"; //新建文件夹地址
            long   lStartPos   = 0;                                                                   //返回上次下载字节
            long   lCurrentPos = 0;                                                                   //返回当前下载文件长度
            long   lDownLoadFile;                                                                     //返回当前下载文件长度

            System.IO.FileStream fs;
            long length = 0;

            if (System.IO.File.Exists(strFileUrl + strFile))
            {
                fs        = System.IO.File.OpenWrite(strFileUrl + strFile);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
            }
            else
            {
                Directory.CreateDirectory(strFileUrl + strFile);
                fs        = new FileStream(strFileUrl + strFile + path, System.IO.FileMode.OpenOrCreate);
                lStartPos = 0;
            }
            try
            {
                System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create(infoUrl) as System.Net.HttpWebRequest;
                length        = request.GetResponse().ContentLength;
                lDownLoadFile = length;
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos);
                }
                System.IO.Stream ns     = request.GetResponse().GetResponseStream();
                byte[]           nbytes = new byte[102];
                int nReadSize           = 0;
                nReadSize = ns.Read(nbytes, 0, 102);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize   = ns.Read(nbytes, 0, 102);
                    lCurrentPos = fs.Length;
                }
                fs.Close();
                ns.Close();
                if (length > 1024)
                {
                    BaseAttach baseInfo = ToolDb.GenBaseAttach(ToolDb.NewGuid, strFileName, info.Id, strFile + path, length.ToString(), "");
                    ToolDb.SaveEntity(baseInfo, string.Empty);
                }
                else
                {
                    File.Delete(strFileUrl + strFile + path);
                }
            }
            catch
            {
                fs.Close();
                File.Delete(strFileUrl + strFile + path);
            }
        }
Beispiel #26
0
        public static string CF10109(string phone, string content, int seqid, int priority)
        {
            string url = "http://sdk4report.eucp.b2m.cn:8080/sdkproxy/sendsms.action";

            // 创建 WebRequest 对象,WebRequest 是抽象类,定义了请求的规定,
            // 可以用于各种请求,例如:Http, Ftp 等等。
            // HttpWebRequest 是 WebRequest 的派生类,专门用于 Http
            System.Net.HttpWebRequest request
                = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;

            // 请求的方式通过 Method 属性设置 ,默认为 GET
            // 可以将 Method 属性设置为任何 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。
            request.Method = "POST";

            // 输入 POST 的数据.
            string cdkey    = "0SDK-EAA-6688-JEXMT";
            string password = "******";

            content = CF10110(content);
            string postData = string.Format("cdkey={0}&password={1}&phone={2}&message={3}&addserial=&seqid={4}&smspriority={5}", cdkey, password, phone, content, seqid.ToString(), priority);

            // 拼接成请求参数串,并进行编码,成为字节
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] byte1 = encoding.GetBytes(postData);

            // 设置请求的参数形式
            request.ContentType = "application/x-www-form-urlencoded";

            // 设置请求参数的长度.
            request.ContentLength = byte1.Length;

            // 取得发向服务器的流
            System.IO.Stream newStream = request.GetRequestStream();

            // 使用 POST 方法请求的时候,实际的参数通过请求的 Body 部分以流的形式传送
            newStream.Write(byte1, 0, byte1.Length);

            // 完成后,关闭请求流.
            newStream.Close();

            // GetResponse 方法才真的发送请求,等待服务器返回
            System.Net.HttpWebResponse response
                = (System.Net.HttpWebResponse)request.GetResponse();

            // 然后可以得到以流的形式表示的回应内容
            System.IO.Stream receiveStream
                = response.GetResponseStream();

            // 还可以将字节流包装为高级的字符流,以便于读取文本内容
            // 需要注意编码
            System.IO.StreamReader readStream
                = new System.IO.StreamReader(receiveStream, Encoding.UTF8);

            string res = CF10111(XDocument.Parse(readStream.ReadToEnd().Trim()));

            // 完成后要关闭字符流,字符流底层的字节流将会自动关闭
            response.Close();
            readStream.Close();

            return(res);
        }
Beispiel #27
0
        private void ThreadableResumeDownload(string url, Action <int, int> stepCallback, Action errorCallback,
                                              Action successCallback)
        {
            //string tmpFullPath = TmpDownloadPath; //根据实际情况设置
            System.IO.FileStream downloadFileStream;
            //打开上次下载的文件或新建文件
            long lStartPos = 0;

            if (_useContinue && System.IO.File.Exists(TmpDownloadPath))
            {
                downloadFileStream = System.IO.File.OpenWrite(TmpDownloadPath);
                lStartPos          = downloadFileStream.Length;
                downloadFileStream.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针

                Console.WriteLine("Resume.... from {0}", lStartPos);
                //CDebug.LogConsole_MultiThread("Resume.... from {0}", lStartPos);
            }
            else
            {
                downloadFileStream = new System.IO.FileStream(TmpDownloadPath, System.IO.FileMode.OpenOrCreate);
                lStartPos          = 0;
            }
            System.Net.HttpWebRequest request = null;
            //打开网络连接
            try
            {
                request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos);  //设置Range值
                }
                Console.WriteLine("Getting Response : {0}", url);
                //CDebug.LogConsole_MultiThread("Getting Response : {0}", url);

                //向服务器请求,获得服务器回应数据流
                using (var response = request.GetResponse()) // TODO: Async Timeout
                {
                    //CDebug.LogConsole_MultiThread("Getted Response : {0}", url);
                    Console.WriteLine("Getted Response : {0}", url);
                    if (IsFinished)
                    {
                        throw new Exception(string.Format("Get Response ok, but is finished , maybe timeout! : {0}", url));
                    }
                    else
                    {
                        var totalSize = (int)response.ContentLength;
                        if (totalSize <= 0)
                        {
                            totalSize = int.MaxValue;
                        }
                        using (var ns = response.GetResponseStream())
                        {
                            //CDebug.LogConsole_MultiThread("Start Stream: {0}", url);
                            Console.WriteLine("Start Stream: {0}", url);

                            int    downSize  = (int)lStartPos;
                            int    chunkSize = 10240;
                            byte[] nbytes    = new byte[chunkSize];
                            int    nReadSize = (int)lStartPos;
                            while ((nReadSize = ns.Read(nbytes, 0, chunkSize)) > 0)
                            {
                                if (IsFinished)
                                {
                                    throw new Exception("When Reading Web stream but Downloder Finished!");
                                }
                                downloadFileStream.Write(nbytes, 0, nReadSize);
                                downSize += nReadSize;
                                stepCallback(totalSize, downSize);
                            }
                            stepCallback(totalSize, totalSize);

                            request.Abort();
                            downloadFileStream.Close();
                        }
                    }
                }

                //CDebug.LogConsole_MultiThread("下载完成: {0}", url);
                Console.WriteLine("下载完成: {0}", url);

                if (File.Exists(_saveFullPath))
                {
                    File.Delete(_saveFullPath);
                }
                File.Move(TmpDownloadPath, _saveFullPath);
            }
            catch (Exception ex)
            {
                //CDebug.LogConsole_MultiThread("下载过程中出现错误:" + ex.ToString());
                Console.WriteLine("下载过程中出现错误:" + ex.ToString());

                downloadFileStream.Close();

                if (request != null)
                {
                    request.Abort();
                }

                try
                {
                    if (File.Exists(TmpDownloadPath))
                    {
                        File.Delete(TmpDownloadPath); // delete temporary file
                    }
                }
                catch (Exception e)
                {
                    //CDebug.LogConsole_MultiThread(e.Message);
                    Console.WriteLine(e.Message);
                }

                errorCallback();
            }
            successCallback();
        }
Beispiel #28
0
        private String PerformRequest(String method, String url, String data)
        {
            
            if ((method.CompareTo("GET") == 0) && (!String.IsNullOrEmpty(data)))
            {
                if (url.Contains("?"))
                {
                    url = url + "&";
                }
                else
                {
                    url = url + "?";
                }
                url = url + data;
            }

            //Create connection
            connection = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            connection.UserAgent = "Veridu-CSharp/" + sdkVersion;
            connection.Headers.Add("Veridu-Client", this.clientId);

            if (!String.IsNullOrEmpty(this.sessionToken))
            {
                connection.Headers.Add("Veridu-Session", this.sessionToken);
            }

            connection.Method = method;
            connection.Timeout = 10000;
            connection.ReadWriteTimeout = 10000;
            connection.ContentType = "application/x-www-form-urlencoded";

            //Send request
            if (!String.IsNullOrWhiteSpace(data) && !method.Contains("GET"))
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] bytes = encoding.GetBytes(data);

                connection.ContentLength = bytes.Length;

                using (System.IO.Stream dataStream = connection.GetRequestStream())
                {
                    dataStream.Write(bytes, 0, bytes.Length);
                }
            }
            else
            {
                connection.ContentLength = 0;
            }

            //Get Response
            string result = "";
            try
            {
                using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)connection.GetResponse())
                {
                    System.Net.HttpStatusCode status = response.StatusCode;
                    System.IO.Stream receiveStream = response.GetResponseStream();
                    System.IO.StreamReader sr = new System.IO.StreamReader(receiveStream);
                    result = sr.ReadToEnd().Trim();
                }
            }
            catch (Exception ex)
            {
                System.Net.WebException wex = (System.Net.WebException)ex;
                var s = wex.Response.GetResponseStream();
                result = "";
                int lastNum = 0;
                do
                {
                    lastNum = s.ReadByte();
                    result += (char)lastNum;
                } while (lastNum != -1);

                s.Close();
                s = null;
            }
            return result;
        }
Beispiel #29
0
        public IEnumerable <SalonCheckoutClass> InsertNew1(string EmployeeServicesId, string BookingDate, string BookingTime, string PaymentStatus, string PaymentType, int IsAcitve, string CreatedDate, int SalonsId, string SalonServicesId, string BookingType)
        {
            con.Open();
            MySqlTransaction tran = con.BeginTransaction();

            try
            {
                string URL = "http://www.google.com";
                System.Net.HttpWebRequest  rq2  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
                System.Net.HttpWebResponse res2 = (System.Net.HttpWebResponse)rq2.GetResponse();
                DateTime Date  = DateTime.Parse(res2.Headers["Date"]);
                string   Date1 = Convert.ToDateTime(Date).ToString("yyyy-MM-dd HH:mm:ss");

                MySqlCommand    cmd3 = new MySqlCommand("select SalonCheckoutId from tblSalonCheckout order by SalonCheckoutId DESC limit 1", con);
                MySqlDataReader dr3  = cmd3.ExecuteReader();
                dr3.Read();
                int Number = Convert.ToInt32(dr3["SalonCheckoutId"]);
                dr3.Close();

                Random       generator      = new Random();
                int          RandomNumber   = generator.Next(100000, 1000000);
                string       currentYear    = DateTime.Now.Year.ToString();
                string       UniqueNumber   = currentYear + RandomNumber + Number;
                string       EvoucherNumber = "EV" + currentYear + "A" + RandomNumber + "P" + Number;
                MySqlCommand cmd5           = new MySqlCommand("insert into tblPayments(UserId,PaymentType,PaymentStatus,IsActive,CreatedBy,CreatedDate) values('','" + PaymentType + "','" + PaymentStatus + "','" + IsAcitve + "','','" + DateTime.Now.AddMinutes(750).ToString("yyyy-MM-dd hh:mm:ss") + "' )", con, tran);
                cmd5.ExecuteNonQuery();
                int paymentid = Convert.ToInt32(cmd5.LastInsertedId);

                string[] EmployeeSerId = EmployeeServicesId.Split(',');
                string[] BookDate      = BookingDate.Split(',');
                string[] BookTime      = BookingTime.Split(',');
                string[] SalonServId   = SalonServicesId.Split(',');
                for (int p = 0; p < SalonServId.Length; p++)
                {
                    MySqlCommand cmd = new MySqlCommand("insert into tblSalonCheckout(EmployeeServicesId,BookingDate,BookingTime,BookingsId,PaymentsId,PaymentStatus,PaymentType,IsActive,CreatedDate,SalonsId,SalonServicesId,BookingType,EvoucherNumber) values('" + EmployeeSerId[p] + "','" + BookDate[p] + "','" + BookTime[p] + "','" + UniqueNumber + "','" + paymentid + "','" + PaymentStatus + "','" + PaymentType + "','" + IsAcitve + "','" + DateTime.Now.AddMinutes(750).ToString("yyyy-MM-dd") + "','" + SalonsId + "','" + SalonServId[p] + "','" + BookingType + "','" + EvoucherNumber + "')", con, tran);

                    cmd.ExecuteNonQuery();
                }

                MySqlCommand cmd2 = new MySqlCommand("select SalonCheckoutId,EvoucherNumber from tblSalonCheckout order by SalonCheckoutId DESC limit 1", con);

                MySqlDataReader dr = cmd2.ExecuteReader();
                dr.Read();
                int    SalonCheckoutId = Convert.ToInt32(dr["SalonCheckoutId"]);
                string Evoucher        = dr["EvoucherNumber"].ToString();
                dr.Close();

                obj.Add(new SalonCheckoutClass {
                    Message = "Success", Evoucher = Evoucher, BookingsId = UniqueNumber, PaymentsId = paymentid, SalonCheckoutId = SalonCheckoutId
                });
                tran.Commit();
                return(obj);
            }
            catch (MySqlException ex)
            {
                tran.Rollback();
                if (ex.Message.Contains("UNIQUE"))
                {
                    obj.Add(new SalonCheckoutClass {
                        Message = "UniqueConstraint", ErrorMessage = ex.Message
                    });
                    return(obj);
                }
                else
                {
                    obj.Add(new SalonCheckoutClass {
                        Message = "Error", ErrorMessage = ex.Message
                    });
                    return(obj);
                }
            }
            catch (Exception ex)
            {
                obj.Add(new SalonCheckoutClass {
                    Message = "Error", ErrorMessage = ex.Message
                });
                return(obj);
            }
            finally
            {
                con.Close();
            }
        }
        private static string PutFile(string remotefile, string localfile)
        {
            string sReturn = "";

            try
            {
                System.IO.FileStream InputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
                try
                {
                    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile);
                    request.Method        = "PUT";
                    request.ContentType   = "application/octet-stream";
                    request.ContentLength = InputBin.Length;
                    System.IO.Stream dataStream = request.GetRequestStream();
                    byte[]           buffer     = new byte[32768];
                    int read;
                    while ((read = InputBin.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        dataStream.Write(buffer, 0, read);
                    }
                    dataStream.Close();
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                    sReturn = response.StatusCode.ToString();
                    if (sReturn != response.StatusDescription)
                    {
                        sReturn += " " + response.StatusDescription;
                    }
                    response.Close();
                }
                catch (Exception ex1)
                {
                    sReturn = ex1.Message;
                }
                InputBin.Close();
                InputBin.Dispose();
            }
            catch (Exception ex2)
            {
                sReturn = ex2.Message;
            }
            return(sReturn);
        }
Beispiel #31
0
        private string sendRequest(string req_xml, System.ComponentModel.BackgroundWorker bw)
        {
            int counter = 0;
               string ret = "Unknown Error";
                XmlDocument soap_env = new XmlDocument();
                soap_env.LoadXml(req_xml);
                request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                request.Headers.Add("SOAPAction", soap_action);
                request.ContentType = "text/xml;charset=\"utf-8\"";
                request.Method = "POST";
                request.CookieContainer = cookie;
                request.KeepAlive = false; //true
                request.UserAgent = "Small Craft C#";

             //   Ignore SSL Error if using https
               System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(
                Object obj, X509Certificate certificate, X509Chain chain,
                System.Net.Security.SslPolicyErrors errors)
                {
                    return (true);
                };

                Stream stream = request.GetRequestStream();
                soap_env.Save(stream);

                try
                {
                    string buf = "";

                    System.Net.WebResponse response = request.GetResponse();
                    Stream s = response.GetResponseStream();
                    StreamReader sr = new StreamReader(s);

                    while (!sr.EndOfStream)
                    {
                        buf += sr.ReadLine();
                        counter++;
                        if (reportProgress) {
                            bw.ReportProgress(counter);
                        }
                    }

                    ret = buf;
                }

                catch (System.Net.WebException webExc)
                {
                    ret = webExc.ToString();
                }

            return ret;
        }
Beispiel #32
0
        // QR Utility
        internal static byte[] getQRData()
        {
            // Fetch data from QR code...
            string address;

            try { address = Clipboard.GetText(); }
            catch { Alert("No text (url) in clipboard."); return(null); }
            try { if (address.Length < 4 || address.Substring(0, 3) != "htt")
                  {
                      Alert("Clipboard text is not a valid URL:", address); return(null);
                  }
            }
            catch { Alert("Clipboard text is not a valid URL:", address); return(null); }
            string webURL = "http://api.qrserver.com/v1/read-qr-code/?fileurl=" + System.Web.HttpUtility.UrlEncode(address);

            try
            {
                System.Net.HttpWebRequest  httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(webURL);
                System.Net.HttpWebResponse httpWebReponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                var    reader = new StreamReader(httpWebReponse.GetResponseStream());
                string data   = reader.ReadToEnd();
                if (data.Contains("could not find"))
                {
                    Alert("Reader could not find QR data in the image."); return(null);
                }
                if (data.Contains("filetype not supported"))
                {
                    Alert("Input URL is not valid. Double check that it is an image (jpg/png).", address); return(null);
                }
                // Quickly convert the json response to a data string
                string pkstr = data.Substring(data.IndexOf("#", StringComparison.Ordinal) + 1);               // Trim intro
                pkstr = pkstr.Substring(0, pkstr.IndexOf("\",\"error\":null}]}]", StringComparison.Ordinal)); // Trim outro
                if (pkstr.Contains("nQR-Code:"))
                {
                    pkstr = pkstr.Substring(0, pkstr.IndexOf("nQR-Code:", StringComparison.Ordinal)); //  Remove multiple QR codes in same image
                }
                pkstr = pkstr.Replace("\\", "");                                                      // Rectify response

                try { return(Convert.FromBase64String(pkstr)); }
                catch { Alert("QR string to Data failed.", pkstr); return(null); }
            }
            catch { Alert("Unable to connect to the internet to decode QR code."); return(null); }
        }