GetResponse() публичный Метод

public GetResponse ( ) : System.Net.WebResponse
Результат System.Net.WebResponse
        public string Create(string url)
        {
            try
            {
                // setup web request to tinyurl
                request = (HttpWebRequest)WebRequest.Create(string.Format(TINYURL_ADDRESS_TEMPLATE, url));
                request.Timeout = REQUEST_TIMEOUT;
                request.UserAgent = USER_AGENT;

                // get response
                response = (HttpWebResponse)request.GetResponse();

                // prase response stream to string
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(ENCODING_NAME));

                // convert the buffer into string and store in content
                StringBuilder sb = new StringBuilder();
                while (reader.Peek() >= 0)
                {
                    sb.Append(reader.ReadLine());
                }
                return sb.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }
Пример #2
1
        public static string GerarArquivo(string texto)
        {
            Uri url = new Uri(string.Concat(URL_TTS_GOOGLE, texto));

            _request = (HttpWebRequest)HttpWebRequest.Create(url);
            _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            _request.UseDefaultCredentials = true;
           
            if (!string.IsNullOrEmpty(ProxyPath))
            {
                _request.Proxy = WebRequest.GetSystemWebProxy();
                _request.Proxy.Credentials = new NetworkCredential(ProxyUserName, ProxyPassword, ProxyDomain);
            }

            WebResponse response = _request.GetResponse();
            Stream fileContent = response.GetResponseStream();
            caminhoTemp = Path.ChangeExtension(Path.GetTempFileName(), ".mp3");

            using (Stream file = File.OpenWrite(caminhoTemp))
            {
                CopyStream(fileContent, file);
                file.Flush();
                file.Close();
            }

            fileContent.Close();
            fileContent.Dispose();

            return caminhoTemp;
        }
        public virtual HttpWebResponse GetHttpWebResp(HttpWebRequest webReq)
        {
            var countTry = 20;
              var repeat = true;
              HttpWebResponse res = null;
              while (repeat && countTry > 0)
            try
            {
              res = (HttpWebResponse)webReq.GetResponse();
              repeat = false;
            }
            catch (WebException wex)
            {
              countTry--;
              File.AppendAllText("log.txt", wex.Message + Environment.NewLine);
              File.AppendAllText("log.txt", "++" + Environment.NewLine);
              File.AppendAllText("log.txt", wex.Status.ToString() + Environment.NewLine);
              File.AppendAllText("log.txt", "++" + Environment.NewLine);
              File.AppendAllText("log.txt", "GetHttpWebResp" + Environment.NewLine);
              File.AppendAllText("log.txt", "------" + Environment.NewLine);
              webReq = GetHttpWebReq(url);
            }

              return res;
        }
Пример #4
1
 public static void Download()
 {
     using (WebClient wcDownload = new WebClient())
     {
         try
         {
             webRequest = (HttpWebRequest)WebRequest.Create(optionDownloadURL);
             webRequest.Credentials = CredentialCache.DefaultCredentials;
             webResponse = (HttpWebResponse)webRequest.GetResponse();
             Int64 fileSize = webResponse.ContentLength;
             strResponse = wcDownload.OpenRead(optionDownloadURL);
             strLocal = new FileStream(optionDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None);
             int bytesSize = 0;
             byte[] downBuffer = new byte[2048];
             downloadForm.Refresh();
             while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
             {
                 strLocal.Write(downBuffer, 0, bytesSize);
                 PercentProgress = Convert.ToInt32((strLocal.Length * 100) / fileSize);
                 pBar.Value = PercentProgress;
                 pLabel.Text = "Downloaded " + strLocal.Length + " out of " + fileSize + " (" + PercentProgress + "%)";
                 downloadForm.Refresh();
             }
         }
         catch { }
         finally
         {
             webResponse.Close();
             strResponse.Close();
             strLocal.Close();
             extractAndCleanup();
             downloadForm.Hide();
         }
     }
 }
Пример #5
0
        public string FetchRequest(HttpWebRequest request)
        {
            try
            {



                string responseText = string.Empty;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            responseText = responseReader.ReadToEnd();
                            return responseText;
                        }
                    }
                }

                return responseText;
            }
            catch (WebException ex)
            {
                var responseStream = ex.Response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                string responseText = responseReader.ReadToEnd();
                throw new MagentoApiException(responseText, ex.Status);
            }
        }
Пример #6
0
        public HttpWebResponse ExecuteRequest(HttpWebRequest request)
        {
            try
            {
                if (this.BeforeRequest != null)
                    this.BeforeRequest(request);

                var response = (HttpWebResponse)request.GetResponse();

                if (this.AfterResponse != null)
                    this.AfterResponse(response);

                return response;
            }
            catch (WebException ex)
            {
                throw WebRequestException.CreateFromWebException(ex);
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException is WebException)
                {
                    throw WebRequestException.CreateFromWebException(ex.InnerException as WebException);
                }
                else
                {
                    throw;
                }
            }
        }
Пример #7
0
 public string Reporttoserver(string status, string testname, ref string error, string emailaddress)
 {
    vartestname = testname;
    varstatus = status;
    varerror = error;
    count += 1;
    if(status == "Complete" && emailaddress.Length > 5)
        email(emailaddress);
    string responsestring = ".";
     try
     {
         req = (HttpWebRequest)WebRequest.Create("http://nz-hwlab-ws1:80/dashboard/update/?script=" + testname + "&status=" + status); //Complete
         resp = (HttpWebResponse)req.GetResponse();
         Stream istrm = resp.GetResponseStream();
         int ch;
         for (int ij = 1; ; ij++)
         {
             ch = istrm.ReadByte();
             if (ch == -1) break;
             responsestring += ((char)ch);
         }
         resp.Close();
         //email();
         return responsestring + " : from server";
     }
     catch (System.Net.WebException e)
     {
         error = e.Message;
         System.Console.WriteLine(error);
         string c = count.ToString();
         return "ServerError " + c;
     }
 }
Пример #8
0
        protected CookieContainer GetCookie(HttpWebRequest request, CookieContainer cc, byte[] content)
        {
            if (cc != null)
            {
                request.CookieContainer = cc;
            }
            else
            {
                request.CookieContainer = new CookieContainer();
                cc = request.CookieContainer;
            }

            try
            {
                Stream stream = request.GetRequestStream();
                stream.Write(content, 0, content.Length);
                stream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                //CookieCollection cook = response.Cookies;
                string CookiesString = request.CookieContainer.GetCookieHeader(request.RequestUri);
                // TODO  save cookiesstring to xml file
            }
            catch (WebException wex)
            {
                // TODO Log
            }
            catch (Exception ex)
            {
                // TODO log
            }
            return cc;
        }
Пример #9
0
        /// <summary>
        /// Get方法获取Html
        /// </summary>
        /// <param name="request">HttpWebRequest类,包含header</param>
        /// <param name="encoding">网页的编码</param>
        /// <param name="proxy">代理</param>
        /// <param name="timeout">默认设置为2000,可随意</param>
        /// <returns></returns>
        public static string GetResponseStr(HttpWebRequest request, string encoding, WebProxy proxy,int? timeout)
        {
            string html = null;
            try
            {
                if (timeout == null || timeout < 2000)
                {
                    timeout = 2000;
                }

                request.Timeout = timeout.Value;
                request.AllowAutoRedirect = true;
                if (proxy != null)
                    request.Proxy = proxy;
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                if (response.ContentEncoding == "gzip")
                {
                    //StreamReader sr1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
                    //是否要解压缩stream?
                    html = GetResponseByZipStream(response);
                    //Console.WriteLine(res);
                }
                else
                {
                    html = sr.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                html = e.Message;
            }

            return html;
        }
Пример #10
0
		public static bool DownloadImage(Uri url, string tempPath)
		{						
			var webRequest = new HttpWebRequest(url);
			webRequest.Method = "GET";
			var wr = webRequest.GetResponse();
			using (var rs = wr.GetResponseStream())
			{
				int readTotal = 0;
				using (var fs = new FileStream(tempPath, FileMode.Create))
				{			
					byte[] bytes = new byte[1024];
					int read = 0;
					while ((read = rs.Read(bytes, 0, 1024)) > 0)
					{
						fs.Write(bytes, 0, read);
						readTotal += read;
					}
				}
				long contLeng = 0;
				object contLengStr = wr.Headers["ContentLength"];
				if (contLengStr != null && long.TryParse((string)contLengStr, out contLeng))
				{				
					return readTotal == contLeng;
				}
				return true;
			}
		}
Пример #11
0
		/// <summary>
		/// Get a string response from an HttpWebRequest.
		/// </summary>
		/// <param name="Request">A valid HttpWebRequest.</param>
		/// <returns>The string returned from the web request, or an empty string if there was an error.</returns>
		/// <remarks>The response status code needs to be 'OK' for results to be processed. Also, this is designed for simple queries, 
		/// so there is an arbitrary 1024 byte limit to the response size.</remarks>
		static public string GetWebResponse( HttpWebRequest Request )
		{
			string ResponseString = "";

			try
			{
				HttpWebResponse WebResponse = ( HttpWebResponse )Request.GetResponse();
				// Simple size check to prevent exploits
				if( WebResponse.StatusCode == HttpStatusCode.OK && WebResponse.ContentLength < 1024 )
				{
					// Process the response
					Stream ResponseStream = WebResponse.GetResponseStream();
					byte[] RawResponse = new byte[WebResponse.ContentLength];
					ResponseStream.Read( RawResponse, 0, ( int )WebResponse.ContentLength );
					ResponseStream.Close();

					ResponseString = Encoding.UTF8.GetString( RawResponse );
				}
			}
			catch( Exception Ex )
			{
				Debug.WriteLine( "Exception in GetWebResponse: " + Ex.Message );
				ResponseString = "";
			}

			return ResponseString;
		}
Пример #12
0
        public string EjecutarAccion(string url, string metodo, object modelo = null)
        {
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 10 * 1000;
            request.Method = metodo;
            request.ContentType = "application/json; charset=utf-8";

            string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(usuario + ":" + clave));
            request.Headers.Add("Authorization", "Basic " + credentials);

            if (modelo != null)
            {
                var postString = new JavaScriptSerializer().Serialize(modelo);
                byte[] data = UTF8Encoding.UTF8.GetBytes(postString);
                request.ContentLength = data.Length;
                Stream postStream = request.GetRequestStream();
                postStream.Write(data, 0, data.Length);
            }
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            if (response.StatusCode != HttpStatusCode.NoContent)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                return reader.ReadToEnd();
            }

            return "";
        }
Пример #13
0
 public static string GetResponse(HttpWebRequest req, byte[] bytes)
 {
     try
     {
         using (Stream stream = req.GetRequestStream())
         {
             stream.Write(bytes, 0, bytes.Length);
         }
         using (HttpWebResponse res = req.GetResponse() as HttpWebResponse)
         {
             if (res.StatusCode == HttpStatusCode.OK)
             {
                 using (Stream stream = res.GetResponseStream())
                 {
                     using (StreamReader reader = new StreamReader(stream))
                     {
                         return reader.ReadToEnd();
                     }
                 }
             }
             else
             {
                 string message = String.Format("POST failed. Received HTTP {0}", res.StatusCode);
                 throw new ApplicationException(message);
             }
         }
     }
     catch(WebException e)
     {
         throw new RestHostMissingException(e);
     }
 }
Пример #14
0
        private HttpWebRequest myTestPage; //(HttpWebRequest)WebRequest.Create("http://localhost:53581/ResumeService/");

        #endregion Fields

        #region Methods

        public string GetPageHeader(string pageURL)
        {
            string header;
            StringBuilder body = new StringBuilder();

            myTestPage = (HttpWebRequest)WebRequest.Create(pageURL);
            HttpWebResponse myResponsePage = (HttpWebResponse)myTestPage.GetResponse();

            Console.WriteLine("Response Header:  {0}", myResponsePage.Headers.ToString());
            header = myResponsePage.Headers.ToString();

            Stream receiver = myResponsePage.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

            StreamReader sr = new StreamReader(receiver, encode);
            char[] inputStream = new char[256];

            while (sr.Read(inputStream, 0, 256) > 0)
            {
                body.Append(new String(inputStream));
            }

            myResponsePage.Close();

            return body.ToString();
        }
Пример #15
0
 public HttpResponse(HttpWebRequest con)
 {
     this.con = con;
     this.rsp = (HttpWebResponse)con.GetResponse();
     this.stream = rsp.GetResponseStream();
     this.reader = new StreamReader(stream, Encoding.UTF8);
 }
Пример #16
0
        public static void CheckUpdate()
        {
            kIRCVersionChecker.Init();
            Updater = (HttpWebRequest)HttpWebRequest.Create(update_checkerurl);
            Updater_Response = (HttpWebResponse)Updater.GetResponse();

            if (Updater_Response.StatusCode == HttpStatusCode.OK)
            {
                Rocket.Unturned.Logging.Logger.Log("kIRC: Contacting updater...");
                Stream reads = Updater_Response.GetResponseStream();
                byte[] buff = new byte[10];
                reads.Read(buff, 0, 10);
                string ver = Encoding.UTF8.GetString(buff);
                ver = ver.ToLower().Trim(new[] { ' ', '\r', '\n', '\t' }).TrimEnd(new[] { '\0' });

                if (ver == VERSION.ToLower().Trim())
                {
                    Rocket.Unturned.Logging.Logger.Log("kIRC: This plugin is using the latest version!");
                }
                else
                {
                    Rocket.Unturned.Logging.Logger.LogWarning("kIRC Warning: Plugin version mismatch!");
                    Rocket.Unturned.Logging.Logger.LogWarning("Current version: "+VERSION+", Latest version on repository is " + ver + ".");
                }
            }
            else
            {
                Rocket.Unturned.Logging.Logger.LogError("kIRC Error: Failed to contact updater.");
            }
            Updater.Abort();
            Updater = null;
            Updater_Response = null;
            lastchecked = DateTime.Now;
        }
Пример #17
0
        public string doGet(HttpWebRequest responseDataRequest)
        {
            string result=null;
            try
            {
                var response = (HttpWebResponse)responseDataRequest.GetResponse();//You return this response.
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    return result;

                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)//You return wex.Response instead
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            return generateErrors(reader, wex);
                        }
                    }
                }
            }

            //refund deserializedProduct = JsonConvert.DeserializeObject<refund>(output);
            return null;
        }
Пример #18
0
        private Result RequestAndRespond(HttpWebRequest request, string content)
        {
            HttpStatusCode statusCode = HttpStatusCode.NotFound;

            try
            {
                var contentBytes = Encoding.UTF8.GetBytes(content);
                request.ContentLength = contentBytes.Length;
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(contentBytes, 0, contentBytes.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    statusCode = HttpClient.GetStatusCode(response);
                }
            }
            catch (WebException webException)
            {
                var response = webException.Response as HttpWebResponse;
                statusCode = HttpClient.GetStatusCode(response);
            }

            return HttpStatusCodeExtensions.ToResult(statusCode);
        }
Пример #19
0
 public static HttpWebResponse GetResponse(HttpWebRequest request)
 {
     Contract.Requires(request != null);
     Debug.WriteLine("Request: " + request.RequestUri);
     var response = request.GetResponse() as HttpWebResponse;
     return response;
 }
Пример #20
0
        public void Request(string url)
        {
            var timer = new Stopwatch();
            var respBody = new StringBuilder();

            _request = (HttpWebRequest) WebRequest.Create(url);

            try
            {
                timer.Start();
                _response = (HttpWebResponse) _request.GetResponse();
                var buf = new byte[8192];
                Stream respStream = _response.GetResponseStream();
                int count = 0;
                do
                {
                    count = respStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                        respBody.Append(Encoding.ASCII.GetString(buf, 0, count));
                } while (count > 0);
                timer.Stop();

                _responseBody = respBody.ToString();
                _statusCode = (int) _response.StatusCode;
                _responseTime = timer.ElapsedMilliseconds/1000.0;
            }
            catch (WebException ex)
            {
                _response = (HttpWebResponse) ex.Response;
                _responseBody = "No Server Response";
                _escapedBody = "No Server Response";
                _responseTime = 0.0;
            }
        }
Пример #21
0
        public string GetResponse(HttpWebRequest request)
        {
            ServicePointManager.Expect100Continue = false;

            if (request != null)
                using (var response = request.GetResponse() as HttpWebResponse)
                {

                    try
                    {
                        if (response != null && response.StatusCode != HttpStatusCode.OK)
                        {
                            throw new ApplicationException(
                                string.Format("The request did not compplete successfully and returned status code:{0}",
                                              response.StatusCode));
                        }
                        if (response != null)
                            using (var reader = new StreamReader(response.GetResponseStream()))
                            {
                                return reader.ReadToEnd();
                            }
                    }
                    catch (WebException exception)
                    {
                        return exception.Message;
                    }
                }
            return "The request is null";
        }
Пример #22
0
        public string WebResponseGet(HttpWebRequest webRequest)
        {
            StreamReader responseReader = null;
            string responseData = "";

            try
            {
                responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch(WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = response.GetResponseStream())
                    {
                        string text = new StreamReader(data).ReadToEnd();
                        Console.WriteLine(text);
                    }
                }

            }
            finally
            {
                webRequest.GetResponse().GetResponseStream().Close();
                responseReader.Close();
                responseReader = null;
            }

            return responseData;
        }
Пример #23
0
		private static void ProcessRequest(HttpWebRequest request)
		{
			try
			{
				using (WebResponse response = request.GetResponse())
				{
					using (Stream dataStream = response.GetResponseStream())
					{
						if (dataStream == null)
						{
							Assert.Fail("GetResponseStream is null");
						}

						using (var reader = new StreamReader(dataStream))
						{
							string responseFromServer = reader.ReadToEnd();

							Console.WriteLine(responseFromServer);
						}
					}
				}
			}
			catch (Exception e)
			{
				Assert.Fail(e.Message);
			}
		}
Пример #24
0
        private static string GetResponseText(HttpWebRequest request)
        {
            string responseText = "";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // PollHaveResponse(request);

                    int contentLength = (int)response.ContentLength;
                    byte[] buffer = new byte[contentLength];
                    Stream stream = response.GetResponseStream();
                    int i = 0;
                    while (i < contentLength)
                    {
                        int readCount = stream.Read(buffer, i, contentLength - i);
                        i += readCount;
                    }

                    char[] responseChars = Encoding.UTF8.GetChars(buffer);
                    responseText = new string(responseChars);
                }
            }
            catch (Exception ex)
            {
                Debug.Print("Exception in GetResponseText: " + ex.Message);
            }

            // PollHaveResponse(request);

            return responseText;
        }
Пример #25
0
        public Stream GetStreamAutoCookie(HttpWebRequest request1, ref string textRef1, ref HttpWebResponse responseRef1)
        {
            string str = "";
            HttpWebResponse response = null;
            request1.Headers.Add(HttpRequestHeader.Cookie, this._objCookieList.ToString());
            response = (HttpWebResponse) request1.GetResponse();
            Stream responseStream = response.GetResponseStream();
            switch (response.ContentEncoding.ToLower())
            {
                case "gzip":
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                    break;

                case "deflate":
                    responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                    break;
            }
            textRef1 = response.ResponseUri.ToString();
            responseRef1 = response;
            str = response.Headers["Set-Cookie"];
            if (!String.IsNullOrEmpty(str))
            {
                str = this.ProcessCookie(str);
            }
            return responseStream;
        }
Пример #26
0
		protected virtual string GetResponseText(HttpWebRequest request)
		{
			try
			{
				using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
				{
					string responseText = string.Empty;

					using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
					{
						responseText = reader.ReadToEnd();
					}

					return responseText;
				}
			}
			catch (System.Exception ex)
			{
				string message = string.Format("对地址{0}执行{1}操作错误:{2}",
					request.RequestUri.ToString(),
					request.Method, 
					ex.Message);

				throw new ApplicationException(message, ex);
			}
		}
Пример #27
0
        public string GetRequestAutoCookie(HttpWebRequest request1, ref string textRef1, ref string textRef2)
        {
            string str3 = "";
            string str2 = "";
            request1.Headers.Add(HttpRequestHeader.Cookie, this._objCookieList.ToString());
            HttpWebResponse response = (HttpWebResponse) request1.GetResponse();
            Stream responseStream = response.GetResponseStream();
            switch (response.ContentEncoding.ToLower())
            {
                case "gzip":
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                    break;

                case "deflate":
                    responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                    break;
            }
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            str3 = reader.ReadToEnd();
            reader.Close();
            textRef1 = response.ResponseUri.ToString();
            textRef2 = response.Headers.Get("Location");
            str2 = response.Headers["Set-Cookie"];
            if (str2 != null && str2 != string.Empty)
            {
                str2 = this.ProcessCookie(str2);
            }
            return str3;
        }
Пример #28
0
        private static HttpResponse remoteCall( int bufmax, ILog log, HttpWebRequest request )
        {
            HttpWebResponse response;
            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                response = e.Response as HttpWebResponse;
            }
            Stream receiveStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader readStream = new StreamReader(receiveStream, encode);
            Char[] read = new Char[bufmax];
            int count = readStream.Read(read, 0, bufmax);
            if (count == bufmax)
                throw new Exception("buf is small ");

            HttpResponse callRespon = new HttpResponse();
            callRespon.body = new String(read, 0, count);
            callRespon.status = response.StatusCode.ToString();
            log.InfoFormat("[GET] status {0} body:{1}", callRespon.status, callRespon.body);
            response.Close();
            readStream.Close();
            return callRespon;
        }
Пример #29
0
        public HttpWebResponse Login(Uri uri, byte[] loginData)
        {
            _request = RequestFactory.GetPostRequest(uri, loginData, Cookies);
            _request.CookieContainer = Cookies;

            return (HttpWebResponse)_request.GetResponse();
        }
Пример #30
0
        /// <summary> 检测WebService是否可用 </summary>
        public static bool IsWebServiceAvaiable(string url)
        {
            bool bRet = false;

            Net.HttpWebRequest myHttpWebRequest = null;
            try
            {
                System.GC.Collect();

                myHttpWebRequest           = (Net.HttpWebRequest)Net.WebRequest.Create(url);
                myHttpWebRequest.Timeout   = 60000;
                myHttpWebRequest.KeepAlive = false;
                myHttpWebRequest.ServicePoint.ConnectionLimit = 200;
                using (Net.HttpWebResponse myHttpWebResponse = (Net.HttpWebResponse)myHttpWebRequest.GetResponse())
                {
                    bRet = true;
                    if (myHttpWebResponse != null)
                    {
                        myHttpWebResponse.Close();
                    }
                }
            }
            catch (Net.WebException e)
            {
                Common.LogHelper.Instance.WriteError(String.Format("网络连接错误 : {0}", e.Message));
            }
            catch (Exception ex)
            {
                Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace);
            }
            finally
            {
                if (myHttpWebRequest != null)
                {
                    myHttpWebRequest.Abort();
                    myHttpWebRequest = null;
                }
            }

            return(bRet);
        }
Пример #31
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Session["Name"]           = txtName.Text;
        Session["Email"]          = txtEmailAddress.Text;
        Session["ContactNo"]      = txtContactNo.Text;
        Session["Paymentgateway"] = rbl_CardType.SelectedValue;
        Decimal           TotalAmount   = Convert.ToDecimal(Session["TotalAmount"].ToString());
        Decimal           PayableAmount = Convert.ToDecimal(Session["PayableAmount"].ToString());
        DateTime          DateofBooking = DateTime.Now.Date;
        string            ISDCode       = "91";
        TransactionRecord tr            = new TransactionRecord();

        tr.MMTBookingID = GTICKBOL.MMTBooking_Max();
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(tr.MMTBookingID.ToString() + "booking id");
        Session["BookingID"] = tr.MMTBookingID;
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(tr.MMTBookingID.ToString() + "booking id");
        tr.MMTPayableAmount = Convert.ToDecimal(Session["PayableAmount"].ToString());
        DateTime day = Convert.ToDateTime(Session["day"]);

        MaxBookingId();
        GTICKBOL.MMTBooking_Details(Convert.ToInt16(Session["NoofPackages"]), Session["pnr"].ToString(), Session["promocode"].ToString(), Convert.ToDecimal(Session["TotalAmount"].ToString()), Convert.ToDecimal(Session["PayableAmount"].ToString()), DateofBooking, Session["BookingID"].ToString(), day, Session["Name"].ToString(), Session["Email"].ToString(), Session["ContactNo"].ToString(), Session["Paymentgateway"].ToString(), false, "", "");
        //Parameters for AMEX.........................
        string Street  = txt_street.Text;
        string Pin     = txt_pin.Text;
        string Country = ddl_country.SelectedValue;
        string tital   = Ddl_title.SelectedValue;
        string fname   = Txtfname.Text;
        string mname   = Txtmname.Text;
        string lname   = Txtlname.Text;
        string city    = Txtcity.Text;
        string state   = Txtstate.Text;
        string country = txt_country.SelectedValue;


        string trackId, amount;

        trackId            = Session["BookingID"].ToString();
        Session["trackId"] = trackId;
        amount             = Session["PayableAmount"].ToString();
        Session["amount"]  = amount;
        // Session["PayDetailsTemp"] = tr.BookingID.ToString() + "_" + trackId + "~" + "web" + "|" + tr.MMTPayableAmount + "|" + "Jhumroo";


        if (rbl_CardType.SelectedValue == "HDFC")
        {
            string URL = "";
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(Session["BookingID"].ToString() + "Sending to HDFC Payment Gateway");
            //GTICKV.LogEntry(tr.NYBookingID.ToString(), "Sending to HDFC Payment Gateway", "8", "");


            String ErrorUrl    = KoDTicketingIPAddress + "MMT/HDFC/Error.aspx";
            String ResponseUrl = KoDTicketingIPAddress + "MMT/HDFC/ReturnReceipt.aspx";

            //string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + Server.UrlEncode(amount)
            //    + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
            //    + "&trackid=" + trackId
            //    + "&udf1=TicketBooking&udf2=" + Server.UrlEncode(txtEmailAddress.Text.Trim())
            //    + "&udf3=" + Server.UrlEncode(txtISDCode.Text + txtContactNo.Text) + "&udf4=" + Server.UrlEncode(txtAddress.Text.Trim()) + "&udf5=" + tr.BookingID;

            string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + amount
                            + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                            + "&trackid=" + trackId
                            + "&udf1=TicketBooking&udf2=" + txtEmailAddress.Text.Trim()
                            + "&udf3=" + Server.UrlEncode(ISDCode.ToString().TrimStart('+') + txtContactNo.Text) + "&udf4=" + Server.UrlEncode(txtName.Text.Trim()) + "&udf5=" + tr.MMTBookingID.ToString();

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Preparing for HDFC Payment..." + qrystr);

            //Writefile_new("\n***************Initial Request********************", Server.MapPath("~"));
            //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + qrystr, Server.MapPath("~"));

            System.IO.StreamWriter requestWriter = null;
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Redirecting for HDFC Payment..." + HDFCTransUrl);
            System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);       //create a SSL connection object server-to-server
            objRequest.Method          = "POST";
            objRequest.ContentLength   = qrystr.Length;
            objRequest.ContentType     = "application/x-www-form-urlencoded";
            objRequest.CookieContainer = new System.Net.CookieContainer();
            try
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Processing request for HDFC Payment...");
                requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());      // here the request is sent to payment gateway
                requestWriter.Write(qrystr);
            }
            catch (Exception ex)
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Excetion while processing HDFC payment: " + trackId + ex.Message);
            }

            if (requestWriter != null)
            {
                requestWriter.Close();
            }

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Review validation response from HDFC Payment Gateway...");
            System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

            //System.Net.CookieContainer responseCookiesContainer = new System.Net.CookieContainer();
            //foreach (System.Net.Cookie cook in objResponse.Cookies)
            //{
            //    responseCookiesContainer.Add(cook);
            //}

            using (System.IO.StreamReader sr =
                       new System.IO.StreamReader(objResponse.GetResponseStream()))
            {
                String NSDLval = sr.ReadToEnd();
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Response: " + NSDLval);
                if (NSDLval.Contains("Invalid User Defined Field"))
                {
                    lblMess.Text = "The information submitted contains some invalid character, please avoid using [+,-,#] etc.";
                    return;
                }

                //Writefile_new("\n***************Initial Response********************", Server.MapPath("~"));
                //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + NSDLval, Server.MapPath("~"));
                if (NSDLval.IndexOf("http") == -1)
                {
                    lblMess.Text = "Payment cannot be processed with information provided.";
                    return;
                }

                // gb.HDFCLog(transid.ToString(), "", trackId, "***Initial Response*** : " + NSDLval);
                string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));      // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
                string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
                if (strPmtId != String.Empty && strPmtUrl != String.Empty)
                {
                    URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
                }
                else
                {
                    lblMess.Text = "Invalid Response!";
                }
                sr.Close();
            }
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
            Response.Redirect(URL, false);
        }
        else if (rbl_CardType.SelectedValue == "AMEX")
        {
            string URL = "";

            GTICKV.LogEntry(tr.BookingID.ToString(), "Sending to AMEX Payment Gateway", "8", trackId.ToString());
            if (ddl_country.SelectedValue == "india")
            {
                URL = "AMEX/Default.aspx?type=amex&transid=" + trackId + "&amt=" + tr.MMTPayableAmount
                      + "&show=" + "" + "&title=" + "" + "&fname=" + "" + "&mname=" + "" + "&lname=" + "" + "&street=" + "NA" + "&city=" + "NA" + "&state=" + "NA" + "&pin=" + "NA" + "&country=" + "";
            }
            else
            {
                URL = "AMEX/Default.aspx?type=amex&transid=" + trackId + "&amt=" + tr.MMTPayableAmount
                      + "&show=" + "" + "&title=" + tital + "&fname=" + fname + "&mname=" + mname + "&lname=" + lname + "&street=" + Street + "&city=" + city + "&state=" + state + "&pin=" + Pin + "&country=" + country;
            }
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
            //Response.Redirect(URL, false);
            Response.Redirect(URL, false);
        }
    }
Пример #32
0
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                if (worker != null)
                {
                    _totalfilecount = _updateOm.UpdateFileList.Length;
                    //create temp folder for downloading update files
                    _tempFolder = Application.StartupPath + "\\temp" + System.DateTime.Now.Date.ToString("yyyyMMdd") + "-" + System.DateTime.Now.TimeOfDay.TotalMilliseconds.ToString();
                    Directory.CreateDirectory(_tempFolder);

                    for (int ix = 0; ix < _updateOm.UpdateFileList.Length; ix++)
                    {
                        try
                        {
                            _currentnum  = ix;
                            _currentFile = _updateOm.UpdateFileList[ix];
                            System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_updateOm.UrlAddress + "/" + _updateOm.UpdateFileList[ix]);
                            System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                            _totalBytes = myrp.ContentLength;
                            System.IO.Stream st = myrp.GetResponseStream();
                            System.IO.Stream so = new System.IO.FileStream(Path.Combine(_tempFolder, _updateOm.UpdateFileList[ix]), System.IO.FileMode.Create);
                            _totalDownloadedByte = 0;
                            byte[] by    = new byte[1024];
                            int    osize = st.Read(by, 0, (int)by.Length);
                            while (osize > 0)
                            {
                                //Check for cancellation
                                if (worker.CancellationPending)
                                {
                                    e.Cancel = true;
                                    break;
                                }
                                else
                                {
                                    worker.ReportProgress((int)(_totalDownloadedByte * 100 / _totalBytes + 1));
                                }
                                _totalDownloadedByte = osize + _totalDownloadedByte;
                                so.Write(by, 0, osize);
                                osize = st.Read(by, 0, (int)by.Length);
                            }
                            so.Close();
                            st.Close();
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Quit();
            }
        }
        static void Main(string[] args)
        {
            //CUCM IP address. Change it to your Cisco Call Manager IP address.

            string ipCCM = "172.168.2.11";
            //Calls a phone. For more info, read the Cisco CUCM AXL manuals.
            string soapreq;

            soapreq  = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:WebdialerSoap\">\n";
            soapreq += "<soapenv:Header/>\n";
            soapreq += "<soapenv:Body>\n";
            soapreq += "<urn:makeCallSoap soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n";
            soapreq += "<cred xsi:type=\"urn:Credential\">\n";
            soapreq += "<userID xsi:type=\"xsd:string\">a_user_id\n";
            soapreq += "<password xsi:type=\"xsd:string\">1234\n";
            soapreq += "</cred>\n";
            soapreq += "<dest xsi:type=\"xsd:string\">1108\n";
            soapreq += "<prof xsi:type=\"urn:UserProfile\">\n";
            soapreq += "<user xsi:type=\"xsd:string\">a_user_id\n";
            soapreq += "<deviceName xsi:type=\"xsd:string\">SEP002D80AADEA7\n";
            soapreq += "<lineNumber xsi:type=\"xsd:string\">2103\n";
            soapreq += "<supportEM xsi:type=\"xsd:boolean\">false\n";
            soapreq += "<locale xsi:type=\"xsd:string\">\n";
            soapreq += "</prof>\n";
            soapreq += "</urn:makeCallSoap>\n";
            soapreq += "</soapenv:Body>\n";
            soapreq += "</soapenv:Envelope>\n";


            //Set up SSL
            System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
                                                                                           System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                                                                           System.Security.Cryptography.X509Certificates.X509Chain chain,
                                                                                           System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); };

            //Issue the request over SSL
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)WebRequest.Create("https://" + ipCCM + ":8443/webdialer/services/WebdialerSoapService");
            req.ContentType = "text/xml;charset=\"utf-8\"";
            req.Accept      = "text/xml";
            req.Method      = "POST";
            req.Headers.Add("SOAPAction: http://localhost:8373/");
            req.Credentials = CredentialCache.DefaultCredentials;

            StreamWriter sw = new StreamWriter(req.GetRequestStream());

            System.Text.StringBuilder soapRequest = new System.Text.StringBuilder();
            soapRequest.Append(soapreq);
            sw.Write(soapRequest.ToString());
            sw.Close();

            try
            {
                //Get response and display
                using (System.Net.WebResponse webresp = (System.Net.WebResponse)req.GetResponse())

                {
                    // Load data into a dataset
                    DataSet dsBasicInfo = new DataSet();
                    dsBasicInfo.ReadXml(webresp.GetResponseStream());
                    if (dsBasicInfo.Tables["multiRef"] != null)
                    {
                        if (dsBasicInfo.Tables["multiRef"].Rows.Count > 0)
                        {
                            //Retrieve outcome of the soap operation.
                            DataRow itemRow = dsBasicInfo.Tables["multiRef"].Rows[0];

                            //Success
                            //User Authentication Error
                            string outcome = itemRow[1].ToString();
                            Console.WriteLine(outcome);

                            if (outcome == "Success")
                            {
                                //Means user has authenticated properly against the credentials.
                                //Get also use getUserProfile instead of makeCallSoap
                            }
                            else
                            {
                                //Something has not worked.
                            }
                        }
                        else
                        {
                            Console.WriteLine("multiref count = 0, nothing processed.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error - Table multiref does not exist!");
                    }
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }

            Console.ReadKey();
        }
Пример #34
0
    public string HelloWorld(string BookingID, string Name, string Email, string Contact_No, string Event_Name, string responceURL)
    {
        //Session["ID"] = entid.ToString();
        DataTable dt = TransactionBOL.Check_EventTransaction(BookingID);

        if (dt.Rows.Count == 0)
        {
            decimal  TotalAmount   = Convert.ToDecimal("1000");
            DateTime DateofBooking = DateTime.Now.Date;
            string   ISDCode       = "91";
            // String BookingID = EVENT00000; //for the FirstTime//
            TransactionRecord tr = new TransactionRecord();
            tr.EvtBookingID   = GTICKBOL.EventBooking_Max();
            tr.EvtTotalAmount = Convert.ToDecimal(TotalAmount);
            string evtbookingid = MaxBookingId(tr.EvtBookingID.ToString());
            tr.EvtBookingID = evtbookingid;
            int enrty = GTICKBOL.EventBooking_Details(Event_Name + BookingID, Name, Event_Name, Contact_No, Event_Name, responceURL, TotalAmount, DateofBooking, false, "", tr.EvtBookingID.ToString());
            //********Payment GateWay Flow******//
            #region Payment GateWay Flow
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(tr.EvtBookingID.ToString() + "Sending to HDFC Payment Gateway");
            string trackid, amount;
            string URL = "";
            trackid = tr.EvtBookingID.ToString();
            //Session["trackid"] = trackid;
            amount = TotalAmount.ToString();
            String ErrorUrl    = KoDTicketingIPAddress + "EventTransaction/HDFC/Error.aspx";
            String ResponseUrl = KoDTicketingIPAddress + "EventTransaction/HDFC/ReturnReceipt.aspx";

            string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + amount
                            + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                            + "&trackid=" + trackid
                            + "&udf1=TicketBooking&udf2=" + "".Trim()
                            + "&udf3=" + Server.UrlEncode(ISDCode.ToString().TrimStart('+') + "") + "&udf4=" + Server.UrlEncode("".Trim()) + "&udf5=" + tr.BookingID.ToString();

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Preparing for HDFC Payment..." + qrystr);

            System.IO.StreamWriter requestWriter = null;
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Redirecting for HDFC Payment..." + HDFCTransUrl);
            System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);       //create a SSL connection object server-to-server
            objRequest.Method          = "POST";
            objRequest.ContentLength   = qrystr.Length;
            objRequest.ContentType     = "application/x-www-form-urlencoded";
            objRequest.CookieContainer = new System.Net.CookieContainer();

            try
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Processing request for HDFC Payment...");
                requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());      // here the request is sent to payment gateway
                requestWriter.Write(qrystr);
            }
            catch (Exception ex)
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Excetion while processing HDFC payment: " + trackid + ex.Message);
            }

            if (requestWriter != null)
            {
                requestWriter.Close();
            }

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Review validation response from HDFC Payment Gateway...");
            System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

            using (System.IO.StreamReader sr =
                       new System.IO.StreamReader(objResponse.GetResponseStream()))
            {
                String NSDLval = sr.ReadToEnd();
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Response: " + NSDLval);
                if (NSDLval.Contains("Invalid User Defined Field"))
                {
                    return("The information submitted contains some invalid character, please avoid using [+,-,#] etc.");
                }

                //Writefile_new("\n***************Initial Response********************", Server.MapPath("~"));
                //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + NSDLval, Server.MapPath("~"));
                if (NSDLval.IndexOf("http") == -1)
                {
                    return("Payment cannot be processed with information provided.");
                }

                // gb.HDFCLog(transid.ToString(), "", trackId, "***Initial Response*** : " + NSDLval);
                string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));      // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
                string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
                if (strPmtId != String.Empty && strPmtUrl != String.Empty)
                {
                    URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
                }
                else
                {
                    return("Invalid Response!");
                }
                sr.Close();
            }
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
            if (enrty > 0)
            {
                return(URL);
            }
            else
            {
                return(null);
            }

            #endregion Payment GateWay Flow
            //**********************************//
        }
        else
        {
            return(null);
        }
    }
Пример #35
0
    /// <summary>
    /// submit the order
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        this.RequirePermission(Affinity.RolePermission.AffinityManager);

        if (!fuAttachment.HasFile)
        {
            pnlResults.Visible = true;
            pResults.InnerHtml = "<h3 style=\"color:red;\">No File Uploaded.  Please choose an Excel file to upload.<h3>";
        }
        else
        {
            int    accountidInt     = 0;
            string originalfilename = fuAttachment.FileName;
            string ext             = System.IO.Path.GetExtension(fuAttachment.FileName);
            string accountid       = ddNewOriginator.SelectedValue;
            string county          = txtPropertyCounty.Text;
            string transactiontype = ddTransactionType.SelectedValue;
            string tractsearch     = (TractSearch.Checked.Equals("True")? "Yes" : "No");

            int.TryParse(accountid, out accountidInt);

            // Get the next available Internal ID and then increment for each order
            int internalId = 0;

            using (MySqlDataReader reader = this.phreezer.ExecuteReader("select Max(REPLACE(REPLACE(o_internal_id, 'AFF_', ''), 'AFF', '')) as maxId from `order` where o_internal_id like 'AFF%'"))
            {
                if (reader.Read())
                {
                    string numStr = reader["maxId"].ToString();
                    int.TryParse(numStr, out internalId);
                    internalId++;
                }
            }

            string internalIdStr = internalId.ToString();
            string filename      = internalIdStr + ext;
            int    uploadidInt   = 0;

            using (MySqlDataReader reader = this.phreezer.ExecuteReader("insert into order_upload_log (oul_a_id, oul_original_filename, oul_filename, oul_starting_internal_id, oul_created, oul_modified) VALUES (" + this.GetAccount().Id.ToString() + ", '" + originalfilename + "', '" + filename + "', " + internalIdStr + ", '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'); SELECT @@IDENTITY as id;"))
            {
                if (reader.Read())
                {
                    int.TryParse(reader["id"].ToString(), out uploadidInt);
                }
            }

            SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
            string path     = Server.MapPath(".\\") + "XlsUploads\\";
            string filepath = path + filename;

            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            fuAttachment.SaveAs(filepath);

            ExcelFile xlsFile = new ExcelFile();

            if (ext.Equals(".xlsx"))
            {
                string zippath = path + internalIdStr + "\\";

                if (!Directory.Exists(zippath))
                {
                    Directory.CreateDirectory(zippath);
                }

                string zipfilepath = path + internalIdStr + ".zip";
                if (File.Exists(zipfilepath))
                {
                    File.Delete(zipfilepath);
                }
                File.Move(filepath, zipfilepath);
                Xceed.Zip.Licenser.LicenseKey = "ZIN20N4AFUNK71J44NA";
                string[] sarr = { "*" };


                Xceed.Zip.QuickZip.Unzip(zipfilepath, zippath, sarr);
                xlsFile.LoadXlsxFromDirectory(zippath, XlsxOptions.None);
            }
            else
            {
                xlsFile.LoadXls(path);
            }
            ExcelWorksheet ws = xlsFile.Worksheets[0];

            pnlResults.Visible = true;
            pnlForm.Visible    = false;
            btnSubmit.Visible  = false;
            btnCancel.Text     = "Back to Admin";
            ListDictionary duplicatePINs = new ListDictionary();


            string pin                 = " ";
            string address             = " ";
            string address1            = "";
            string address2            = "";
            string city                = "";
            string state               = "";
            string zip                 = "";
            string firmname            = "";
            string attorney            = "";
            string attorneyaddress1    = "";
            string attorneyaddress2    = "";
            string attorneycity        = "";
            string attorneystate       = "";
            string attorneyzip         = "";
            string attorneyphone       = "";
            string attorneyemail       = "";
            string attorneyattentionto = "";
            int    idx                 = 1;

            /****************************************************************************************
            *  GET ACCOUNT INFORMATION
            ****************************************************************************************/
            Affinity.Account account = new Affinity.Account(this.phreezer);

            account.Load(accountid);

            XmlDocument preferencesXML = new XmlDocument();
            preferencesXML.LoadXml(account.PreferencesXml);

            XmlNode node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantName']");
            if (node != null)
            {
                firmname = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantAttorneyName']");
            if (node != null)
            {
                attorney = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantAddress']");
            if (node != null)
            {
                attorneyaddress1 = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantAddress2']");
            if (node != null)
            {
                attorneyaddress2 = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantCity']");
            if (node != null)
            {
                attorneycity = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantState']");
            if (node != null)
            {
                attorneystate = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantZip']");
            if (node != null)
            {
                attorneyzip = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantPhone']");
            if (node != null)
            {
                attorneyphone = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantEmail']");
            if (node != null)
            {
                attorneyemail = node.InnerText;
            }

            node = preferencesXML.SelectSingleNode("//Field[@name='ApplicantAttentionTo']");
            if (node != null)
            {
                attorneyattentionto = node.InnerText;
            }

            string xml = "<response><field name=\"CommittmentDeadline\"></field><field name=\"PreviousTitleEvidence\"></field><field name=\"Prior\"></field><field name=\"TypeOfProperty\">Single Family</field><field name=\"PropertyUse\"></field><field name=\"TransactionType\">[TRANSACTIONTYPE]</field><field name=\"TractSearch\">[TRACTSEARCH]</field><field name=\"ShortSale\"></field><field name=\"Foreclosure\"></field><field name=\"CashSale\"></field><field name=\"ConstructionEscrow\"></field><field name=\"ReverseMortgage\"></field><field name=\"EndorsementEPA\"></field><field name=\"EndorsementLocation\"></field><field name=\"EndorsementCondo\"></field><field name=\"EndorsementComp\"></field><field name=\"EndorsementARM\"></field><field name=\"EndorsementPUD\"></field><field name=\"EndorsementBalloon\"></field><field name=\"EndorsementOther\"></field><field name=\"MortgageAmount\">1.00</field><field name=\"PurchasePrice\"></field><field name=\"TRID\">No</field><field name=\"LoanNumber\"></field><field name=\"SecondMortgage\">No</field><field name=\"SecondMortgageAmount\"></field><field name=\"LoanNumber2nd\"></field><field name=\"ChainOfTitle\">No</field><field name=\"Buyer\">" + (TractSearch.Checked.Equals("True")? "." : "") + "</field><field name=\"Buyer1Name2\"></field><field name=\"AddBuyer2\"></field><field name=\"Buyer2Name1\"></field><field name=\"Buyer2Name2\"></field><field name=\"AddBuyer3\"></field><field name=\"Buyer3Name1\"></field><field name=\"Buyer3Name2\"></field><field name=\"AddBuyer4\"></field><field name=\"Buyer4Name1\"></field><field name=\"Buyer4Name2\"></field><field name=\"AddBuyer5\"></field><field name=\"Buyer5Name1\"></field><field name=\"Buyer5Name2\"></field><field name=\"Seller\"></field><field name=\"Seller1Name2\"></field><field name=\"AddSeller2\"></field><field name=\"Seller2Name1\"></field><field name=\"Seller2Name2\"></field><field name=\"AddSeller3\"></field><field name=\"Seller3Name1\"></field><field name=\"Seller3Name2\"></field><field name=\"AddSeller4\"></field><field name=\"Seller4Name1\"></field><field name=\"Seller4Name2\"></field><field name=\"AddSeller5\"></field><field name=\"Seller5Name1\"></field><field name=\"Seller5Name2\"></field><field name=\"Underwriter\"></field><field name=\"ApplicantName\">[FIRMNAME]</field><field name=\"ApplicantAttorneyName\">[ATTORNEY]</field><field name=\"ApplicantAddress\">[ADDRESS1]</field><field name=\"ApplicantAddress2\">[ADDRESS1]</field><field name=\"ApplicantCity\">[CITY]</field><field name=\"ApplicantState\">[STATE]</field><field name=\"ApplicantZip\">[ZIP]</field><field name=\"ApplicantPhone\">[PHONE]</field><field name=\"ApplicantFax\"></field><field name=\"ApplicantEmail\">[EMAIL]</field><field name=\"ApplicantAttentionTo\">[ATTENTIONTO]</field><field name=\"CopyApplicationTo\"></field><field name=\"LenderName\"></field><field name=\"LenderContact\"></field><field name=\"LenderAddress\"></field><field name=\"LenderAddress2\"></field><field name=\"LenderCity\"></field><field name=\"LenderState\"></field><field name=\"LenderZip\"></field><field name=\"LenderPhone\"></field><field name=\"LenderFax\"></field><field name=\"LenderEmail\"></field><field name=\"BrokerName\"></field><field name=\"BrokerLoanOfficer\"></field><field name=\"BrokerAddress\"></field><field name=\"BrokerAddress2\"></field><field name=\"BrokerCity\"></field><field name=\"BrokerState\"></field><field name=\"BrokerZip\"></field><field name=\"BrokerPhone\"></field><field name=\"BrokerFax\"></field><field name=\"BrokerEmail\"></field><field name=\"Notes\"></field><field name=\"Source\">Web Order ID</field><field name=\"SubmittedDate\">[DATE]</field><field name=\"OrderRequestStatus\">Requested</field></response>".Replace("[TRANSACTIONTYPE]", transactiontype).Replace("[TRACTSEARCH]", tractsearch).Replace("[FIRMNAME]", firmname).Replace("[ATTORNEY]", attorney).Replace("[ADDRESS1]", attorneyaddress1).Replace("[ADDRESS2]", attorneyaddress2).Replace("[CITY]", attorneycity).Replace("[STATE]", attorneystate).Replace("[ZIP]", attorneyzip).Replace("[PHONE]", attorneyphone).Replace("[EMAIL]", attorneyemail).Replace("[ATTENTIONTO]", attorneyattentionto).Replace("[DATE]", DateTime.Now.ToString());

            /****************************************************************************************
            *  END GETTING ACCOUNT INFORMATION
            ****************************************************************************************/

            while (!pin.Equals("") && ws.Rows[idx] != null && ws.Rows[idx].Cells[1] != null && ws.Rows[idx].Cells[1].Value != null)
            {
                pin                 = ws.Rows[idx].Cells[1].Value.ToString();
                address             = ws.Rows[idx].Cells[3].Value.ToString();
                address1            = "";
                address2            = "";
                city                = "";
                state               = "";
                zip                 = "";
                firmname            = "";
                attorney            = "";
                attorneyaddress1    = "";
                attorneyaddress2    = "";
                attorneycity        = "";
                attorneystate       = "";
                attorneyzip         = "";
                attorneyphone       = "";
                attorneyemail       = "";
                attorneyattentionto = "";

                if (!address.Equals(""))
                {
                    XmlDocument doc = new XmlDocument();
                    string      url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&key=";

                    System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                    req.Method    = "GET";
                    req.Accept    = "text/xml";
                    req.KeepAlive = false;

                    System.Net.HttpWebResponse response = null;

                    using (response = (System.Net.HttpWebResponse)req.GetResponse()) //attempt to get the response.
                    {
                        using (Stream RespStrm = response.GetResponseStream())
                        {
                            doc.Load(RespStrm);
                        }
                    }

                    XmlNode streetnumbernode = doc.SelectSingleNode("/GeocodeResponse/result/address_component[type='street_number']");
                    if (streetnumbernode != null)
                    {
                        address1 += streetnumbernode.SelectSingleNode("long_name").InnerText;
                    }

                    XmlNode routenode = doc.SelectSingleNode("/GeocodeResponse/result/address_component[type='route']");
                    if (routenode != null)
                    {
                        address1 += " " + routenode.SelectSingleNode("long_name").InnerText;
                    }

                    XmlNode citynode = doc.SelectSingleNode("/GeocodeResponse/result/address_component[type='locality']");
                    if (citynode != null)
                    {
                        city = citynode.SelectSingleNode("long_name").InnerText;
                    }

                    if (county.Equals(""))
                    {
                        XmlNode countynode = doc.SelectSingleNode("/GeocodeResponse/result/address_component[type='administrative_area_level_2']");
                        if (countynode != null)
                        {
                            county = countynode.SelectSingleNode("long_name").InnerText;
                        }
                    }

                    XmlNode statenode = doc.SelectSingleNode("/GeocodeResponse/result/address_component[type='administrative_area_level_1']");
                    if (statenode != null)
                    {
                        state = statenode.SelectSingleNode("short_name").InnerText;
                    }

                    XmlNode zipnode = doc.SelectSingleNode("/GeocodeResponse/result/address_component[type='postal_code']");
                    if (zipnode != null)
                    {
                        zip = zipnode.SelectSingleNode("long_name").InnerText;
                    }

                    //Response.Write(idx.ToString() + " - " + pin + " - " + address1 + " - " + city + " - " + state + " - " + zip + " - " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "<br/>");

                    // create a new order for this request
                    Affinity.Order order = new Affinity.Order(this.phreezer);

                    order.OriginatorId       = accountidInt;
                    order.CustomerStatusCode = Affinity.OrderStatus.ReadyCode;
                    order.InternalStatusCode = Affinity.OrderStatus.ReadyCode;
                    order.InternalId         = "";

                    order.ClientName       = "";
                    order.Pin              = pin;
                    order.AdditionalPins   = "";
                    order.PropertyAddress  = address1;
                    order.PropertyAddress2 = address2;
                    order.PropertyCity     = city;
                    order.PropertyState    = state;
                    order.PropertyZip      = zip;
                    order.CustomerId       = pin;
                    order.PropertyCounty   = county;
                    order.PropertyUse      = "Residential";
                    order.OrderUploadLogId = uploadidInt;

                    try
                    {
                        Affinity.Order PreviousOrder = order.GetPrevious();
                        // verify the user has not submitted this PIN in the past
                        if (PreviousOrder == null)
                        {
                            order.Insert();
                            internalId++;

                            Affinity.Request rq = new Affinity.Request(this.phreezer);
                            rq.OrderId         = order.Id;
                            rq.OriginatorId    = accountidInt;
                            rq.RequestTypeCode = "Refinance";
                            rq.StatusCode      = Affinity.RequestStatus.DefaultCode;

                            rq.Xml = xml;

                            rq.Insert();
                        }
                        else
                        {
                            duplicatePINs.Add(pin, "");
                        }
                    }
                    catch (FormatException ex)
                    {
                        this.Master.ShowFeedback("Please check that the estimated closing date is valid and in the format 'mm/dd/yyyy'", MasterPage.FeedbackType.Error);
                    }
                }

                idx++;
            }
            pnlResults.Visible = true;
            pResults.InnerHtml = "<h1 style=\"color:black;\">" + (idx - duplicatePINs.Count).ToString() + " orders have been imported. " + duplicatePINs.Count.ToString() + " records failed.</h1>";
        }
    }
Пример #36
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtURL.Text))
            {
                txtResponse.Text = "";
                try
                {
                    System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(txtURL.Text);
                    req.Method                   = metodoRequest.Text;
                    req.PreAuthenticate          = true;
                    req.ProtocolVersion          = System.Net.HttpVersion.Version10;
                    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(txtLogin.Text + ":" + txtSenha.Text));
                    req.Credentials              = new NetworkCredential("username", "password");

                    var type          = req.GetType();
                    var currentMethod = type.GetProperty("CurrentMethod", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(req);

                    var methodType = currentMethod.GetType();
                    methodType.GetField("ContentBodyNotAllowed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(currentMethod, false);

                    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

                    if (!string.IsNullOrEmpty(txtJson.Text))
                    {
                        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(txtJson.Text);
                        req.ContentType   = "application/json; charset=utf-8";
                        req.ContentLength = byteArray.Length;
                        var dataStream = req.GetRequestStream();
                        dataStream.Write(byteArray, 0, byteArray.Length);
                        dataStream.Close();
                    }
                    else
                    {
                        //throw new Exception("Erro: JSON não informado.");
                    }

                    System.Net.HttpWebResponse resp          = req.GetResponse() as System.Net.HttpWebResponse;
                    System.IO.Stream           receiveStream = resp.GetResponseStream();
                    System.Text.Encoding       encode        = Encoding.GetEncoding("utf-8");
                    // Pipes the stream to a higher level stream reader with the required encoding format.
                    System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, encode);
                    Char[] read = new Char[256];
                    // Reads 256 characters at a time.
                    int count = readStream.Read(read, 0, 256);
                    while (count > 0)
                    {
                        // Dumps the 256 characters on a string and displays the string to the console.
                        String str = new String(read, 0, count);
                        txtResponse.Text += (str);
                        count             = readStream.Read(read, 0, 256);
                    }

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

                    xDoc.LoadXml(txtResponse.Text);

                    System.Xml.XmlReader xmlReader = new System.Xml.XmlNodeReader(xDoc);

                    DataSet dsXml = new DataSet();

                    dsXml.ReadXml(xmlReader);

                    foreach (DataTable dt in dsXml.Tables)
                    {
                        if (dt.TableName == "value")
                        {
                            gridXMLDataTable.DataSource = dt;
                        }
                    }

                    // Releases the resources of the response.
                    resp.Close();
                    // Releases the resources of the Stream.
                    readStream.Close();
                }
                catch (Exception ex)
                {
                    txtResponse.Text = "Erro ao consumir a API " + txtURL.Text + ". Exceção: " + ex.Message + ". Trace: " + ex.InnerException;
                }
            }
        }
Пример #37
0
        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //MessageBox.Show(verzijaDll.ToString() + " " + localPath);

            Process[] pArry = Process.GetProcesses();

            foreach (Process p in pArry)
            {
                string s = p.ProcessName;
                //s = s.ToLower();
                if (s.CompareTo("PC POS") == 0)
                {
                    p.Kill();
                }
            }


            //ProvjeriVerzijeDll();


            string sUrlToDnldFile;

            sUrlToDnldFile = "https://www.pc1.hr/pcpos/update/PC POS.exe";


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

                sFileSavePath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\PCMALOPRODAJA.exe";

                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;

                WebClient client = new WebClient();

                Stream strRemote = client.OpenRead(url);

                FileStream strLocal = new FileStream(sFileSavePath, FileMode.Create, FileAccess.Write, 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 = (double)(iRunningByteTotal);

                    double dTotal = (double)iSize;

                    double dProgressPercentage = (dIndex / dTotal);

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


                    // update the progress bar

                    bgWorker1.ReportProgress(iProgressPercentage);
                }

                strRemote.Close();

                status = true;
            }

            catch (Exception exM)
            {
                //Show if any error Occured

                MessageBox.Show("Error: " + exM.Message);

                status = false;
            }
        }
Пример #38
0
    public static DataTable GetCadastralInfoFromPKK_REST(string cadastral)
    {
        //System.Net.WebClient obj = new System.Net.WebClient();
        string rosreestr_id = "";
        string str_text     = "";
        //UTF8Encoding utf8 = new UTF8Encoding();
        //byte[] qqq;
        DataSet   dsCadastral;
        DataTable dtCadastral;
        DataRow   d_row;

        PKK_Property_Info pty = new PKK_Property_Info();

        Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
        settings.NullValueHandling    = Newtonsoft.Json.NullValueHandling.Ignore;
        settings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.Default;


        rosreestr_id = Transform_Cadastral(cadastral);
        Uri strUrl = new Uri(System.String.Format("http://pkk5.rosreestr.ru/api/features/1/{0}?date_format=%Y-%m-%d", rosreestr_id));

        //--------------------------------------------------------
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
        request.Method            = System.Net.WebRequestMethods.Http.Get;
        request.Accept            = "application/json";
        request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
        request.Credentials       = System.Net.CredentialCache.DefaultCredentials;
        request.ReadWriteTimeout  = 60000;
        try
        {
            System.Net.WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream()) {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                str_text = reader.ReadToEnd();
            }
        }
        catch (System.Net.WebException ex)
        {
            dsCadastral = new DataSet();
            dtCadastral = dsCadastral.Tables.Add();
            dtCadastral.Columns.Add("error", typeof(String));
            d_row          = dtCadastral.NewRow();
            d_row["error"] = ex.Message;
            dtCadastral.Rows.Add(d_row);
            return(dtCadastral);

            throw;
        }
        //--------------------------------------------------------

        //        str_text = utf8.GetString(qqq)

        pty = Newtonsoft.Json.JsonConvert.DeserializeObject <PKK_Property_Info>(str_text, settings);


        dsCadastral = new DataSet();
        string xml_file_path = AppDomain.CurrentDomain.BaseDirectory + "XML\\online_data.xsd";

        //''dsCadastral.ReadXmlSchema(xml_file_path)
        //'        dtCadastral = dsCadastral.Tables("Property")
        //''dtCadastral = dsCadastral.Tables("rosreestr_info")
        dtCadastral        = new Rosreestr_Info.XML.online_data.rosreestr_infoDataTable();
        d_row              = dtCadastral.NewRow();
        d_row["cadastral"] = cadastral;

        if (pty.feature == null)
        {
            dsCadastral = new DataSet();
            dtCadastral = dsCadastral.Tables.Add();
            dtCadastral.Columns.Add("error", typeof(String));
            d_row          = dtCadastral.NewRow();
            d_row["error"] = "Не найдено";
            dtCadastral.Rows.Add(d_row);
            return(dtCadastral);
        }

        d_row["p_cadastral"] = pty.feature.attrs.cn;

        d_row["p_stoim"]      = pty.feature.attrs.cad_cost;
        d_row["p_date_stoim"] = pty.feature.attrs.date_cost;
        d_row["p_area"]       = pty.feature.attrs.area_value;
        if (pty.feature.attrs.util_by_doc != null)
        {
            d_row["p_utilByDoc"] = pty.feature.attrs.util_by_doc.Replace("&quot;", "\"\"");
        }
        else
        {
            d_row["p_utilByDoc"] = "";
        }
        if (pty.feature.attrs.util_code != null)
        {
            d_row["p_utilCode"] = pty.feature.attrs.util_code;
        }
        else
        {
            d_row["p_utilCode"] = "";
        }

        //'If Not (pty.parcelData.utilCodedesc Is Nothing) Then
        //'    d_row("p_utilDesc") = pty.parcelData.utilCodedesc.Replace("&quot;", """")
        //'Else
        //'    d_row("p_utilDesc") = ""
        //'End If

        d_row["p_status"]     = "";
        d_row["p_status_str"] = "-";
        string status_text = "";

        if (pty.feature.attrs.statecd != null)
        {
            d_row["p_status"] = pty.feature.attrs.statecd;
            switch (pty.feature.attrs.statecd)
            {
            case "01":
                status_text = "Ранее учтенный";
                break;

            case "06":
                status_text = "Учтенный";
                break;

            case "07":
                status_text = "Снят с учета";
                break;

            default:
                break;
            }
            d_row["p_status_str"] = status_text;
        }
        dtCadastral.Rows.Add(d_row);
        return(dtCadastral);
    }
    public static UInt64 GetDownloadSize(Uri uri)
    {
        UInt64 result = 0;

        try
        {
            ManualResetEvent requestEvent = new ManualResetEvent(false);

#if UNITY_WSA && ENABLE_WINMD_SUPPORT
            HttpClient          client   = new HttpClient();
            HttpRequestMessage  msg      = new HttpRequestMessage(HttpMethod.Head, uri);
            HttpResponseMessage response = null;

            var task = client.SendRequestAsync(msg);
            task.Completed =
                (Windows.Foundation.IAsyncOperationWithProgress <Windows.Web.Http.HttpResponseMessage, Windows.Web.Http.HttpProgress> asyncInfo, Windows.Foundation.AsyncStatus asyncStatus) =>
            {
                if (asyncInfo.Status == Windows.Foundation.AsyncStatus.Completed)
                {
                    response = asyncInfo.GetResults();
                }
                if (asyncStatus != Windows.Foundation.AsyncStatus.Started)
                {
                    requestEvent.Set();
                }
            };
            requestEvent.WaitOne();
#else
            System.Net.HttpWebRequest msg = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            msg.Method = "HEAD";
            System.Net.WebResponse response = null;

            try
            {
                response = msg.GetResponse();
            }
            catch { }
#endif

            if (response != null)
            {
#if UNITY_WSA && ENABLE_WINMD_SUPPORT
                if (response.IsSuccessStatusCode && response.Content != null)
                {
                    var cl = response.Content.Headers.ContentLength;
                    if (cl.HasValue)
                    {
                        result = (UInt64)cl.Value;
                    }
                }
#else
                result = (UInt64)response.ContentLength;
#endif
            }
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogErrorFormat("Exception getting download size: {0} \n{1}", ex.Message, ex.StackTrace);
        }
        return(result);
    }
Пример #40
0
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        int               CouplePackage = Convert.ToInt16(ddl_CouplePackage.SelectedValue);
        int               SinglePackage = Convert.ToInt16(ddl_SinglePackage.SelectedValue);
        int               TeensPackage  = Convert.ToInt16(ddl_TeensPackage.SelectedValue);
        int               KidsPackage   = Convert.ToInt16(ddl_KidsPackage.SelectedValue);
        decimal           CoupleAmount  = Convert.ToDecimal(CouplePackage * Convert.ToInt32(pricecouple.Text));
        decimal           SingleAmount  = Convert.ToDecimal(SinglePackage * Convert.ToInt32(pricesingle.Text));
        decimal           TeensAmount   = Convert.ToDecimal(TeensPackage * Convert.ToInt32(priceteen.Text));
        decimal           KidsAmount    = Convert.ToDecimal(KidsPackage * Convert.ToInt32(pricekids.Text));
        decimal           TotalAmount   = CoupleAmount + SingleAmount + TeensAmount + KidsAmount;
        DateTime          DateofBooking = DateTime.Now.Date;
        string            ISDCode       = "91";
        TransactionRecord tr            = new TransactionRecord();

        tr.NYBookingID   = GTICKBOL.NewYearBooking_Max();
        tr.QntyCouple    = Convert.ToInt16(CouplePackage);
        tr.QntySingle    = Convert.ToInt16(SinglePackage);
        tr.QntyTeens     = Convert.ToInt16(TeensPackage);
        tr.QntyKids      = Convert.ToInt16(KidsPackage);
        tr.NYTotalAmount = Convert.ToDecimal(TotalAmount.ToString());
        string nybookingid = MaxBookingId(tr.NYBookingID.ToString());

        tr.NYBookingID = nybookingid;
        GTICKBOL.NewYearBooking_Details(Convert.ToInt16(CouplePackage), Convert.ToInt16(SinglePackage), Convert.ToInt16(TeensPackage), Convert.ToInt16(KidsPackage), Convert.ToDecimal(TotalAmount.ToString()), DateofBooking, tr.NYBookingID.ToString(), txtName.Text, txtEmail.Text, txtContact.Text, false, "", textroyalinfo.Text);
        //Payment Gateway Flow

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(tr.NYBookingID.ToString() + "Sending to HDFC Payment Gateway");
        string trackId, amount;
        string URL = "";

        trackId = tr.NYBookingID;
        amount  = TotalAmount.ToString();
        String ErrorUrl    = KoDTicketingIPAddress + "NewYearPackages/HDFC/Error.aspx";
        String ResponseUrl = KoDTicketingIPAddress + "NewYearPackages/HDFC/ReturnReceipt.aspx";
        string qrystr      = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + amount
                             + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                             + "&trackid=" + trackId
                             + "&udf1=TicketBooking&udf2=" + txtEmail.Text.Trim()
                             + "&udf3=" + Server.UrlEncode(ISDCode.ToString().TrimStart('+') + txtContact.Text) + "&udf4=" + Server.UrlEncode(txtName.Text.Trim()) + "&udf5=" + tr.BookingID.ToString();

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Preparing for HDFC Payment..." + qrystr);
        System.IO.StreamWriter requestWriter = null;
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Redirecting for HDFC Payment..." + HDFCTransUrl);
        System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);   //create a SSL connection object server-to-server
        objRequest.Method          = "POST";
        objRequest.ContentLength   = qrystr.Length;
        objRequest.ContentType     = "application/x-www-form-urlencoded";
        objRequest.CookieContainer = new System.Net.CookieContainer();
        try
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Processing request for HDFC Payment...");
            requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());  // here the request is sent to payment gateway
            requestWriter.Write(qrystr);
        }
        catch (Exception ex)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Excetion while processing HDFC payment: " + trackId + ex.Message);
        }

        if (requestWriter != null)
        {
            requestWriter.Close();
        }

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Review validation response from HDFC Payment Gateway...");
        System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
        using (System.IO.StreamReader sr =
                   new System.IO.StreamReader(objResponse.GetResponseStream()))
        {
            String NSDLval = sr.ReadToEnd();
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Response: " + NSDLval);
            if (NSDLval.Contains("Invalid User Defined Field"))
            {
                lblMess.Text = "The information submitted contains some invalid character, please avoid using [+,-,#] etc.";
                return;
            }

            if (NSDLval.IndexOf("http") == -1)
            {
                lblMess.Text = "Payment cannot be processed with information provided.";
                return;
            }

            string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));  // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
            string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
            if (strPmtId != String.Empty && strPmtUrl != String.Empty)
            {
                URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
            }
            else
            {
                lblMess.Text = "Invalid Response!";
            }
            sr.Close();
        }
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
        Response.Redirect(URL, false);
    }
Пример #41
0
        public override void Close()
        {
            if (GetResponseOnClose)
            {
                if (disposed)
                {
                    return;
                }
                disposed = true;
                var response = (HttpWebResponse)request.GetResponse();
                response.ReadAll();
                response.Close();
                return;
            }

            if (sendChunked)
            {
                if (disposed)
                {
                    return;
                }
                disposed = true;
                if (!pending.WaitOne(WriteTimeout))
                {
                    throw new WebException("The operation has timed out.", WebExceptionStatus.Timeout);
                }
                byte [] chunk   = Encoding.ASCII.GetBytes("0\r\n\r\n");
                string  err_msg = null;
                cnc.Write(request, chunk, 0, chunk.Length, ref err_msg);
                return;
            }

            if (isRead)
            {
                if (!nextReadCalled)
                {
                    CheckComplete();
                    // If we have not read all the contents
                    if (!nextReadCalled)
                    {
                        nextReadCalled = true;
                        cnc.Close(true);
                    }
                }
                return;
            }
            else if (!allowBuffering)
            {
                complete_request_written = true;
                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }
                return;
            }

            if (disposed || requestWritten)
            {
                return;
            }

            long length = request.ContentLength;

            if (!sendChunked && length != -1 && totalWritten != length)
            {
                IOException io = new IOException("Cannot close the stream until all bytes are written");
                nextReadCalled = true;
                cnc.Close(true);
                throw new WebException("Request was cancelled.", io, WebExceptionStatus.RequestCanceled);
            }

            // Commented out the next line to fix xamarin bug #1512
            //WriteRequest ();
            disposed = true;
        }
Пример #42
0
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        string mailer = "";

        if (Request.QueryString["source"] != null)
        {
            mailer = Request.QueryString["source"].ToString();
        }
        string Package  = ddl_Package1.SelectedItem.ToString();
        int    Quantity = Convert.ToInt16(ddl_Quantity.SelectedValue);

        string[] amt           = Package.Split('.');
        decimal  TotalAmount   = Convert.ToDecimal(amt[1]) * Quantity;
        DateTime DateofBooking = DateTime.Now.Date;
        string   ISDCode       = "91";
        // String BookingID = KODVL00000; //for the FirstTime//
        TransactionRecord tr = new TransactionRecord();

        tr.VLBookingID   = GTICKBOL.ValentineBooking_Max();
        tr.Quantity      = Convert.ToInt16(Quantity);
        tr.VLTotalAmount = Convert.ToDecimal(TotalAmount);
        string vlbookingid = MaxBookingId(tr.VLBookingID.ToString());

        tr.VLBookingID = vlbookingid;


        //GTICKBOL.ValentineBooking_Details(amt[1], Quantity, Convert.ToDecimal(TotalAmount.ToString()), DateofBooking, tr.VLBookingID.ToString(), txtName.Text.ToString(), txtEmail.Text.ToString(), txtContact.Text.ToString(), false, "");
        GTICKBOL.ValentineBooking_Details(amt[1], Quantity, Convert.ToDecimal(TotalAmount.ToString()), DateofBooking, tr.VLBookingID.ToString(), txtName.Text.ToString(), txtEmail.Text.ToString(), txtContact.Text.ToString(), false, "", GetIP(), "Valentine_2014", mailer);
        //********Payment GateWay Flow******//

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(tr.VLBookingID.ToString() + "Sending to HDFC Payment Gateway");
        string trackid, amount;
        string URL = "";

        trackid            = tr.VLBookingID.ToString();
        Session["trackid"] = trackid;
        amount             = TotalAmount.ToString();


        String ErrorUrl    = KoDTicketingIPAddress + "ValentineAffair/HDFC/Error.aspx";
        String ResponseUrl = KoDTicketingIPAddress + "ValentineAffair/HDFC/ReturnReceipt.aspx";

        string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + amount
                        + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                        + "&trackid=" + trackid
                        + "&udf1=TicketBooking&udf2=" + txtEmail.Text.Trim()
                        + "&udf3=" + Server.UrlEncode(ISDCode.ToString().TrimStart('+') + txtContact.Text) + "&udf4=" + Server.UrlEncode(txtName.Text.Trim()) + "&udf5=" + tr.BookingID.ToString();

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Preparing for HDFC Payment..." + qrystr);

        System.IO.StreamWriter requestWriter = null;
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Redirecting for HDFC Payment..." + HDFCTransUrl);
        System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);   //create a SSL connection object server-to-server
        objRequest.Method          = "POST";
        objRequest.ContentLength   = qrystr.Length;
        objRequest.ContentType     = "application/x-www-form-urlencoded";
        objRequest.CookieContainer = new System.Net.CookieContainer();

        try
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Processing request for HDFC Payment...");
            requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());  // here the request is sent to payment gateway
            requestWriter.Write(qrystr);
        }
        catch (Exception ex)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Excetion while processing HDFC payment: " + trackid + ex.Message);
        }

        if (requestWriter != null)
        {
            requestWriter.Close();
        }

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Review validation response from HDFC Payment Gateway...");
        System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

        using (System.IO.StreamReader sr =
                   new System.IO.StreamReader(objResponse.GetResponseStream()))
        {
            String NSDLval = sr.ReadToEnd();
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Response: " + NSDLval);
            if (NSDLval.Contains("Invalid User Defined Field"))
            {
                lblMess.Text = "The information submitted contains some invalid character, please avoid using [+,-,#] etc.";
                return;
            }

            //Writefile_new("\n***************Initial Response********************", Server.MapPath("~"));
            //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + NSDLval, Server.MapPath("~"));
            if (NSDLval.IndexOf("http") == -1)
            {
                lblMess.Text = "Payment cannot be processed with information provided.";
                return;
            }

            // gb.HDFCLog(transid.ToString(), "", trackId, "***Initial Response*** : " + NSDLval);
            string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));  // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
            string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
            if (strPmtId != String.Empty && strPmtUrl != String.Empty)
            {
                URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
            }
            else
            {
                lblMess.Text = "Invalid Response!";
            }
            sr.Close();
        }
        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
        Response.Redirect(URL, false);
    }
Пример #43
0
                /// <summary><para>Die überladene Funktion <see cref="Load(Info.MapServiceTileBase, bool)"/> lädt das Satellitenbild, welches durch den Parameter vom Typ
                /// <see cref="MapService.Info.MapServiceTileBase"/> festgelegt wurde von dem gewünschten MapService-Provider.
                /// Ein Beispiel ist in der Funktion <see cref="Load()"/> zu finden.</para></summary>
                ///
                /// <param name="tile">Ein Objekt vom Typ <see cref="MapService.Info.MapServiceTileBase"/>, das über die <see cref="MapService.Tile"/>-Eigenschaft des <see cref="MapService"/>-Objektes erhalten werden kann.</param>
                /// <param name="silent">Legt fest, ob im Fehlerfall eine Exception weitergegeben wird (false) oder nicht (true).</param>
                /// <returns>Ein Bild vom allgemeinen Typ <see cref="System.Drawing.Image"/>.</returns>
                public Image Load(Info.MapServiceTileBase tile, bool silent)
                {
                    Image           image    = null;
                    Stream          data     = null;
                    HttpWebResponse response = null;

                    // Erst versuchen Bild, aus dem Cach zu holen
                    if (MapService.Helper.Images.Cache.Enabled == true)
                    {
                        image = MapService.Helper.Images.Cache.GetImage(this.Parent);
                        if (image != null)
                        {
                            return(image);
                        }
                    }

                    // Bild nicht im Cache, oder Cache nicht verwendet
                    if ((tile != null) && (tile.URL != ""))
                    {
                        System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tile.URL);
                        request.UserAgent = USER_AGENT;
                        request.Timeout   = 30000;
                        try
                        {
                            response = (HttpWebResponse)request.GetResponse();
                            data     = response.GetResponseStream();
                            image    = new Bitmap(data);

                            // Fehlerbild Virtual Earth und Yahoo Maps erkennen
                            if (this.Parent.MapServer != Info.MapServer.GoogleMaps)
                            {
                                bool isValidImage = ValidImage(image);
                                ErrorProvider.ErrorMessage err = new ErrorProvider.ErrorMessage("MS_NO_IMAGE");
                                if (isValidImage == false)
                                {
                                    throw new WebException(err.Text, WebExceptionStatus.ProtocolError);
                                }
                            }

                            // Bild im Cache ablegen
                            if (MapService.Helper.Images.Cache.Enabled == true)
                            {
                                MapService m;
                                if (tile.URL == Parent.Tile.URL)
                                {
                                    m = this.Parent.MemberwiseClone();
                                }
                                else
                                {
                                    m = new MapService(tile);
                                }
                                MapService.Helper.Images.Cache.Add(new CacheItem(m, image));
                            }
                        }
                        catch (WebException ex)
                        {
                            image = null;
                            if (!silent)
                            {
                                throw new Exception(ex.Message, ex);
                            }
                        }
                        catch (Exception ex)
                        {
                            image = null;
                            if (!silent)
                            {
                                throw new Exception(ex.Message, ex);
                            }
                        }
                        finally
                        {
                            if (response != null)
                            {
                                response.Close();
                            }
                            if (data != null)
                            {
                                data.Close();
                            }
                        }
                    }
                    return(image);
                }
Пример #44
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        long transid         = 0;
        TransactionRecord tr = new TransactionRecord();

        try
        {
            #region Session based
            if (Session["seat_Val"] != null && Session["Seat_TransactionID"] != null)
            {
                try
                {
                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(string.Format("Transaction [{0}]  Seats [{1}]", Session["Seat_TransactionID"].ToString(), Session["seat_Val"].ToString()));
                    tr.BookingID = long.Parse(Session["Seat_TransactionID"].ToString());
                    string[] strarr = Session["seat_Val"].ToString().Split(',');
                    if (Session["AgentCode"] != null)
                    {
                        tr.AgentCode = Session["AgentCode"].ToString();
                        tr.Source    = "MSAGENT";
                    }
                    else
                    {
                        tr.AgentCode = "WEB";
                        tr.Source    = "WEB";
                    }
                    tr.BookingType = "INDIVIDUAL";
                    //tr.VoucherType = rblVoucher.SelectedValue;
                    //tr.VoucherNo = "";
                    //tr.VoucherBookingID = 0;
                    tr.CardType       = rbl_CardType.SelectedItem.Text;
                    tr.PaymentGateway = rbl_CardType.SelectedValue;
                    tr.CardNo         = "1111222233334444";
                    tr.MobileNo       = txtContactNo.Text;
                    tr.Name           = Session["FirstName"].ToString() + Session["LastName"].ToString();
                    tr.PaymentType    = ddlPaymentMode.SelectedItem.Text;
                    tr.DateOfBooking  = DateTime.Now.Date.ToShortDateString();

                    bool istrue = emailsnd.Checked;
                    Session["Istrue"] = istrue;
                    tr.IsChecked      = istrue;
                    tr.EmailID        = txtEmailAddress.Text;

                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IsChecked" + istrue);

                    tr.PlaceOfPick           = "";
                    tr.TimeOfPick            = "";
                    Session["Complimentary"] = "false";
                    tr.WantComplimentary     = false;

                    tr.Status        = false;
                    tr.TimeOfBooking = DateTime.Now.ToShortTimeString();

                    tr.TotalSeats = int.Parse(strarr[5].ToString());
                    tr.Category   = strarr[8];
                    tr.Location   = strarr[6];
                    tr.Play       = strarr[1];
                    //replace "-"with "/"
                    //string[] datarr = strarr[2].ToString().Split('/'); // for live server
                    string[] datarr = strarr[2].ToString().Split('-'); // for dev/local
                    //replace datarr[0] to datarr[1]
                    //tr.ShowDate = datarr[1] + "/" + datarr[0] + "/" + datarr[2]; // for live server
                    tr.ShowDate = datarr[0] + "/" + datarr[1] + "/" + datarr[2];  // for dev/local

                    tr.ShowTime = strarr[7];
                    tr.Day      = Convert.ToDateTime(tr.ShowDate).DayOfWeek.ToString();
                    // for dev/local, swap month & date above after day has been calculated above
                    //comment below two lines
                    //tr.ShowDate = tr.ShowDate.Replace(datarr[1], datarr[0]);
                    //tr.ShowDate = tr.ShowDate.Replace("30", datarr[1]);
                    tr.Remark              = "";
                    tr.TotalAmount         = GTICKBOL.Get_SeatPrice_SeatKeyNoWise(tr.BookingID);
                    Session["TotalAmount"] = tr.TotalAmount;
                    tr.SeatInfo            = Session["Seat_info"].ToString();
                    tr.Address             = Session["Address"].ToString().Trim();
                    //+ Session["Address2"].ToString()
                    tr.IP = GetIP();

                    //******Promotion code related changes START*****

                    if (Session["PromotionCode"] != null)
                    {
                        KoDTicketingLibrary.DTO.Promotion PromoSession = (KoDTicketingLibrary.DTO.Promotion)Session["PromotionCode"];
                        tr.PromotionCode      = PromoSession.PromotionCode;
                        tr.DiscountPercentage = PromoSession.DiscountPercentage;
                        tr.WebPromotionId     = PromoSession.WebPromotionId;
                        tr.DiscountedAmount   = (GTICKBOL.Get_SeatPrice_SeatKeyNoWise(tr.BookingID) - (GTICKBOL.Get_SeatPrice_SeatKeyNoWise(tr.BookingID) * PromoSession.DiscountPercentage / 100));
                    }
                    //******Promotion code related changes END*****



                    //******RoyalCard related changes START*****

                    tr.RegId         = Session["Regid"].ToString();
                    tr.AvailedAmount = Convert.ToDecimal(Session["RedeemBalance"]);
                    tr.AvailedPoints = Convert.ToDecimal(Session["RedeemPoints"]);
                    tr.TopUpAmount   = tr.TotalAmount - (Convert.ToDecimal(Session["RedeemPoints"]) + Convert.ToDecimal(Session["RedeemBalance"]));
                    if (tr.TopUpAmount != 0)
                    {
                        tr.TopUpTransactionId = TransactionBOL.Card_Transaction(tr.RegId, tr.TopUpAmount, DateTime.Now, tr.RegId, 0);
                    }
                    tr.OptionalEmail   = txtEmail.Text;
                    tr.OptionalContact = txtmobileno.Text;
                    //******RoyalCard related changes END*****



                    transid = TransactionBOL.Transaction_Temp_Insert(tr);
                }
                catch (Exception ex)
                {
                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Transaction Preparation Error: " + ex.Message);
                }
                GTICKV.LogEntry(tr.BookingID.ToString(), "Category : " + tr.Category + " ,Seat Info : " + tr.SeatInfo +
                                ", Total Amt : " + tr.TotalAmount, "6", "");

                //******Promotion code send discounted AMOUNT to payment gateway changes START*****
                if (Session["PromotionCode"] != null)
                {
                    KoDTicketingLibrary.DTO.Promotion ObjPromoSession = (KoDTicketingLibrary.DTO.Promotion)Session["PromotionCode"];
                    tr.TotalAmount = 0;
                    DataTable prices = GTICKBOL.Get_AllSeatPrice_SeatKeyNoWise(tr.BookingID);
                    if (prices != null)
                    {
                        foreach (DataRow dr in prices.Rows)
                        {
                            decimal SinglePrice     = decimal.Parse(dr[0].ToString());
                            decimal DiscountedPrice = SinglePrice - (SinglePrice * ObjPromoSession.DiscountPercentage / 100);
                            DiscountedPrice = decimal.Truncate(DiscountedPrice);
                            if (DiscountedPrice == 1274)
                            {
                                DiscountedPrice = DiscountedPrice + 1;
                            }
                            else if (DiscountedPrice == 2124)
                            {
                                DiscountedPrice = DiscountedPrice + 1;
                            }
                            else if (DiscountedPrice == 2974)
                            {
                                DiscountedPrice = DiscountedPrice + 1;
                            }
                            else if (DiscountedPrice == 4249)
                            {
                                DiscountedPrice = DiscountedPrice + 1;
                            }
                            tr.TotalAmount += DiscountedPrice;
                            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Discounted Price For a Ticket" + DiscountedPrice.ToString());
                        }
                    }
                }
                //*******Promotion code send discounted AMOUNT to payment gateway changes END here **********


                tr.TotalAmount = (tr.TotalAmount) - (tr.AvailedPoints + tr.AvailedAmount);

                if (transid > 0)
                {
                    Session["AgentCode"] = null;
                    GTICKV.LogEntry(tr.BookingID.ToString(), "Data Successfully Written to Temp Transaction Table", "7", transid.ToString());
                    if (Session["PayableAmount"].ToString() == "0")
                    {
                        Session["BookingID"] = tr.BookingID;
                        Session["ID"]        = transid.ToString();
                        Response.Redirect("Payment/Print-Receipt.aspx");
                    }
                    else
                    {
                        string URL = "";
                        //Pay Details , Sent To Loyalty Card Page --  CardType,TransID,Amt,ShowName
                        //Session["PayDetailsTemp"] = rblVoucher.SelectedValue + "|" + tr.BookingID.ToString() + "_" + transid + "~" + tr.AgentCode + "|" + tr.TotalAmount + "|" + tr.Play;
                        Session["PayDetailsTemp"] = tr.BookingID.ToString() + "_" + transid + "~" + tr.AgentCode + "|" + tr.TotalAmount + "|" + tr.Play;

                        if (ddlPaymentMode.SelectedValue == "CREDIT")
                        {
                            if (rbl_CardType.SelectedValue == "IDBI")
                            {
                                GTICKV.LogEntry(tr.BookingID.ToString(), "Sending to IDBI Payment Gateway", "8", transid.ToString());
                                URL = "../../Payment/Idbi/Default.aspx?type=idbi&transid=" + tr.BookingID.ToString() + "_" + transid + "~" + tr.AgentCode + "~royal_card_payment_idbi" + "&amt=" + tr.TotalAmount
                                      + "&show=" + tr.Play;
                            }
                            else if (rbl_CardType.SelectedValue == "AMEX")
                            {
                                GTICKV.LogEntry(tr.BookingID.ToString(), "Sending to AMEX Payment Gateway", "8", transid.ToString());
                                URL = "Payment/Web/Default.aspx?type=amex&transid=" + tr.BookingID.ToString() + "_" + transid + "~" + tr.AgentCode + "&amt=" + tr.TotalAmount
                                      + "&show=" + tr.Play;
                            }
                            else if (rbl_CardType.SelectedValue == "HDFC")
                            {
                                //string check = gb.HDFCLogCheck(transid.ToString()).Rows[0]["Amount"].ToString();
                                GTICKV.LogEntry(tr.BookingID.ToString(), "Sending to HDFC Payment Gateway", "8", transid.ToString());
                                string trackId, amount;
                                //Random Rnd = new Random();
                                //trackId = Rnd.Next().ToString();		//Merchant Track ID, this is as per merchant logic
                                trackId            = tr.BookingID.ToString() + "_" + transid + "-" + tr.AgentCode;
                                Session["trackId"] = trackId;
                                amount             = tr.TotalAmount.ToString();
                                Session["amount"]  = amount;

                                String ErrorUrl    = KoDTicketingIPAddress + "RoyalCard/Account/Payment/HDFC/Error.aspx";
                                String ResponseUrl = KoDTicketingIPAddress + "RoyalCard/Account/Payment/HDFC/ReturnReceipt.aspx";

                                //string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + Server.UrlEncode(amount)
                                //    + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                                //    + "&trackid=" + trackId
                                //    + "&udf1=TicketBooking&udf2=" + Server.UrlEncode(txtEmailAddress.Text.Trim())
                                //    + "&udf3=" + Server.UrlEncode(txtISDCode.Text + txtContactNo.Text) + "&udf4=" + Server.UrlEncode(txtAddress.Text.Trim()) + "&udf5=" + tr.BookingID;

                                string qrystr = "id=" + HDFCTransPortalID + "&password="******"&action=1&langid=USA&currencycode=356&amt=" + amount
                                                + "&responseURL=" + Server.UrlEncode(ResponseUrl) + "&errorURL=" + Server.UrlEncode(ErrorUrl)
                                                + "&trackid=" + trackId
                                                + "&udf1=TicketBooking&udf2=" + txtEmailAddress.Text.Trim()
                                                + "&udf3=" + Server.UrlEncode(txtISDCode.Text.TrimStart('+') + txtContactNo.Text) + "&udf4=" + Server.UrlEncode(tr.Address.ToString()) + "&udf5=" + tr.BookingID.ToString();

                                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Preparing for HDFC Payment..." + qrystr);

                                //Writefile_new("\n***************Initial Request********************", Server.MapPath("~"));
                                //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + qrystr, Server.MapPath("~"));

                                System.IO.StreamWriter requestWriter = null;
                                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Redirecting for HDFC Payment..." + HDFCTransUrl);
                                System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(HDFCTransUrl);   //create a SSL connection object server-to-server
                                objRequest.Method          = "POST";
                                objRequest.ContentLength   = qrystr.Length;
                                objRequest.ContentType     = "application/x-www-form-urlencoded";
                                objRequest.CookieContainer = new System.Net.CookieContainer();
                                try
                                {
                                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Processing request for HDFC Payment...");
                                    requestWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());  // here the request is sent to payment gateway
                                    requestWriter.Write(qrystr);
                                }
                                catch (Exception ex)
                                {
                                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Excetion while processing HDFC payment: " + trackId + ex.Message);
                                }

                                if (requestWriter != null)
                                {
                                    requestWriter.Close();
                                }

                                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Review validation response from HDFC Payment Gateway...");
                                System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();

                                //System.Net.CookieContainer responseCookiesContainer = new System.Net.CookieContainer();
                                //foreach (System.Net.Cookie cook in objResponse.Cookies)
                                //{
                                //    responseCookiesContainer.Add(cook);
                                //}

                                using (System.IO.StreamReader sr =
                                           new System.IO.StreamReader(objResponse.GetResponseStream()))
                                {
                                    String NSDLval = sr.ReadToEnd();
                                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Response: " + NSDLval);
                                    if (NSDLval.Contains("Invalid User Defined Field"))
                                    {
                                        lblMess.Text = "The information submitted contains some invalid character, please avoid using [+,-,#] etc.";
                                        return;
                                    }

                                    //Writefile_new("\n***************Initial Response********************", Server.MapPath("~"));
                                    //Writefile_new("\n\nDateTime:" + DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Reference No:" + trackId + "Request XML:" + NSDLval, Server.MapPath("~"));
                                    if (NSDLval.IndexOf("http") == -1)
                                    {
                                        lblMess.Text = "Payment cannot be processed with information provided.";
                                        return;
                                    }

                                    // gb.HDFCLog(transid.ToString(), "", trackId, "***Initial Response*** : " + NSDLval);
                                    string strPmtId  = NSDLval.Substring(0, NSDLval.IndexOf(":http"));  // Merchant MUST map (update) the Payment ID received with the merchant Track Id in his database at this place.
                                    string strPmtUrl = NSDLval.Substring(NSDLval.IndexOf("http"));
                                    if (strPmtId != String.Empty && strPmtUrl != String.Empty)
                                    {
                                        URL = strPmtUrl.ToString() + "?PaymentID=" + strPmtId;
                                    }
                                    else
                                    {
                                        lblMess.Text = "Invalid Response!";
                                    }
                                    sr.Close();
                                }
                            }//HDFC
                        }
                        //else if (ddlPaymentMode.SelectedValue == "VOUCHER")
                        //{
                        //    Session["PayDetailsTemp"] = rblVoucher.SelectedValue + "|" + tr.BookingID.ToString() + "_" + transid + "~" + tr.AgentCode + "|" + tr.TotalSeats;
                        //    URL = "~/Payment/Voucher/Voucher.aspx";
                        //}
                        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Payment Redirection: " + URL);
                        Response.Redirect(URL, false);
                    }
                }
                else
                {
                    lblMess.Text = "Session Timeout. Please start the transaction again by clicking \"Back\" button";
                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("Session Timeout. Need to restart transaction");
                }
            }
            else //no Session[seat_val]
            {
                ClientScript.RegisterStartupScript(GetType(), "myscript", "<script>alert('Session Timeout. Please start the transaction again');window.location.href='TicketBooking.aspx';</script>");
            }
            #endregion
        }
        catch (Exception ex)
        {
            GTICKV.LogEntry(tr.BookingID.ToString(), "Error Occurred - " + ex.Message.Replace("'", ""), "8", transid.ToString());
        }
    }
Пример #45
0
        private bool?DownloadFile(Download download)
        {
            BackgroundWorker bg            = _backgroundWorkers3[download.Id];
            string           localFilePath = Path.Combine(_downloadFolder, download.Filename);

            long Content_Length = -1;

            System.Net.HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create(download.Url);

            string localFileName = Path.GetFileName(localFilePath);

            bool result = false;

            try
            {
                req.Method    = "HEAD";
                req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
                using (System.Net.WebResponse resp = req.GetResponse())
                {
                    if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
                    {
                        Content_Length = ContentLength;
                    }
                }

                FileInfo finfo = null;

                if (File.Exists(localFilePath))
                {
                    finfo = new FileInfo(localFilePath);

                    if (Content_Length != -1 && finfo.Length == Content_Length)
                    {
                        result = true;
                        //"File with name " + localFileName + " already downloaded! Skipping...");
                    }
                    else if (bg.CancellationPending)
                    {
                        download.DownloadCanceled = true;
                        result = true;
                        //"Resuming download of file named: " + localFileName + " ...");
                    }
                }



                if (result == false)
                {
                    long resContentLength = DownloadFileWithResume(download.Url, localFilePath, download.Id, ref bg);
                    if (resContentLength == -1000)
                    {
                        //file is corrupted.
                        return(null);
                    }
                }

                finfo = finfo ?? new FileInfo(localFilePath);

                if (result == false)
                {
                    if (finfo.Length == Content_Length)
                    {
                        result = true;
                        LogMessage("File named " + localFileName + " successfully downloaded!", false);
                    }
                    else
                    {
                        result = false;
                        LogMessage("Downloading file " + localFileName + " interrupted Retrying download...", true);
                        DownloadFile(download);
                    }
                }
            }
            catch (System.Net.WebException webEx)
            {
                if (webEx.Message.ToString() == "The remote server returned an error: (416) Requested Range Not Satisfiable.")
                {
                    LogMessage(download.Url + " The remote server returned an error: (416) Requested Range Not Satisfiable.", true);
                    result = true;
                }
            }
            catch (Exception ex)
            {
                LogMessage("Error: " + ex.Message + " Retrying download file " + localFileName, true);
                DownloadFile(download);
            }

            return(result);
        }
Пример #46
0
        public static string GetWebResponse(string url, string method, string contentType, System.Collections.Specialized.NameValueCollection Headers, System.Collections.Specialized.NameValueCollection formData, System.Collections.Specialized.NameValueCollection files)
        {
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            if (Headers != null)
            {
                httpWebRequest.Headers.Add(Headers);
            }
            httpWebRequest.ContentType = contentType + "; boundary=" + boundary;//multipart/form-data
            //httpWebRequest.ContentType = contentType + "; charset=utf-8";
            httpWebRequest.Method      = method;
            httpWebRequest.KeepAlive   = true;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Stream memStream = new System.IO.MemoryStream();

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            if (formData != null)
            {
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                foreach (string key in formData.Keys)
                {
                    memStream.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem      = string.Format(formdataTemplate, key, formData[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }
            }


            if (files != null)
            {
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                foreach (string key in files.Keys)
                {
                    string paramName = key;
                    string file      = files[key];
                    string fileName  = System.IO.Path.GetFileName(file);

                    string header      = string.Format(headerTemplate, paramName, fileName);
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    memStream.Write(headerbytes, 0, headerbytes.Length);
                    FileStream fileStream = new FileStream(file, FileMode.Open,
                                                           FileAccess.Read);
                    byte[] buffer    = new byte[1024];
                    int    bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                    memStream.Write(boundarybytes, 0, boundarybytes.Length);
                    fileStream.Close();
                }
            }

            if (method == "POST")
            {
                httpWebRequest.ContentLength = memStream.Length;
                Stream requestStream = httpWebRequest.GetRequestStream();
                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
            }

            System.Net.WebResponse webResponse = null;
            try
            {
                webResponse = httpWebRequest.GetResponse();
                Stream       stream = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                return(reader.ReadToEnd());
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (System.Net.HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            throw new Exception(string.Format("{0} {1}", wex.Message, reader.ReadToEnd()));
                        }
                    }
                }
                else
                {
                    throw wex;
                }
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }

                httpWebRequest = null;
            }
            //return "";
        }
Пример #47
0
        static void Main(string[] args)
        {
            //===========================Initial========================================
            List <IPEndPoint> trackerIPs = new List <IPEndPoint>();
            IPEndPoint        endPoint   = new IPEndPoint(IPAddress.Parse("192.168.81.233"), 22122);

            trackerIPs.Add(endPoint);
            ConnectionManager.Initialize(trackerIPs);
            StorageNode node = FastDFSClient.GetStorageNode("group1");

            //===========================UploadFile=====================================
            byte[] content = null;
            if (File.Exists(@"D:\材料科学与工程基础.doc"))
            {
                FileStream streamUpload = new FileStream(@"D:\材料科学与工程基础.doc", FileMode.Open);
                using (BinaryReader reader = new BinaryReader(streamUpload))
                {
                    content = reader.ReadBytes((int)streamUpload.Length);
                }
            }
            //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
            string fileName = FastDFSClient.UploadFile(node, content, "doc");

            //===========================BatchUploadFile=====================================
            string[] _FileEntries = Directory.GetFiles(@"E:\fastimage\三维", "*.jpg");
            DateTime start        = DateTime.Now;

            foreach (string file in _FileEntries)
            {
                string name = Path.GetFileName(file);
                content = null;
                FileStream streamUpload = new FileStream(file, FileMode.Open);
                using (BinaryReader reader = new BinaryReader(streamUpload))
                {
                    content = reader.ReadBytes((int)streamUpload.Length);
                }
                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                fileName = FastDFSClient.UploadFile(node, content, "jpg");
            }
            DateTime end            = DateTime.Now;
            TimeSpan consume        = ((TimeSpan)(end - start));
            double   consumeSeconds = Math.Ceiling(consume.TotalSeconds);

            //===========================QueryFile=======================================
            fileName = "M00/00/00/wKhR6U__-BnxYu0eAxRgAJZBq9Q180.mdb";
            FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, fileName);

            Console.WriteLine(string.Format("FileName:{0}", fileName));
            Console.WriteLine(string.Format("FileSize:{0}", fileInfo.FileSize));
            Console.WriteLine(string.Format("CreateTime:{0}", fileInfo.CreateTime));
            Console.WriteLine(string.Format("Crc32:{0}", fileInfo.Crc32));
            //==========================AppendFile=======================================
            FastDFSClient.AppendFile("group1", fileName, content);
            FastDFSClient.AppendFile("group1", fileName, content);

            //===========================DownloadFile====================================
            fileName = "M00/00/00/wKhR6U__-BnxYu0eAxRgAJZBq9Q180.mdb";
            byte[] buffer = FastDFSClient.DownloadFile(node, fileName, 0L, 0L);
            if (File.Exists(@"D:\SZdownload.mdb"))
            {
                File.Delete(@"D:\SZdownload.mdb");
            }
            FileStream stream = new FileStream(@"D:\SZdownload.mdb", FileMode.CreateNew);

            using (BinaryWriter write = new BinaryWriter(stream, Encoding.BigEndianUnicode))
            {
                write.Write(buffer);
                write.Close();
            }
            stream.Close();
            //===========================RemoveFile=======================================
            FastDFSClient.RemoveFile("group1", fileName);

            //===========================Http测试,流读取=======================================
            string url = "http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.jpg";

            System.Net.HttpWebRequest  req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            Image myImage = Image.FromStream(res.GetResponseStream());

            myImage.Save("c:\\fast.jpg");//保存
            //===========================Http测试,直接下载=======================================
            WebClient web = new WebClient();

            web.DownloadFile("http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.jpg", "C:\\abc.jpg");
            web.DownloadFile("http://192.168.81.233/M00/00/00/wKhR6VADbNr5s7ODAAIOGO1_YmA574.jpg", "C:\\abc.jpg");

            Console.WriteLine("Complete");
            Console.Read();
        }
Пример #48
0
        public static string GetWebResponse(string Url, Stream stream, string ContentType, Encoding enc, int Timeout = 100000)
        {
            System.Net.HttpWebResponse rp = null;
            System.IO.StreamReader     sr = null;
            try
            {
                System.Net.HttpWebRequest rq = ((System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url));
                rq.Timeout = Timeout;
                if (stream != null)
                {
                    byte[] bytearray = null;
                    //Stream stream = PostFile.BaseStream;
                    stream.Seek(0, SeekOrigin.Begin);
                    bytearray = new byte[stream.Length];
                    int count = 0;
                    while (count < stream.Length)
                    {
                        bytearray[count++] = Convert.ToByte(stream.ReadByte());
                    }


                    rq.Method        = "POST";
                    rq.ContentType   = ContentType;
                    rq.ContentLength = bytearray.Length;
                    using (Stream requestStream = rq.GetRequestStream())
                    {
                        // Send the file as body request.
                        requestStream.Write(bytearray, 0, bytearray.Length);
                        requestStream.Close();
                    }


                    //Stream rw = rq.GetRequestStream();
                    //PostFile.CopyTo(rw);
                    //rw.Write(PostData);
                    //rw.Close();
                    //rw = null;
                }

                rp = (System.Net.HttpWebResponse)rq.GetResponse();
                sr = new System.IO.StreamReader(rp.GetResponseStream(), enc);
                return(sr.ReadToEnd());
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (System.Net.HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            throw new Exception(string.Format("{0} {1}", wex.Message, reader.ReadToEnd()));
                        }
                    }
                }
                else
                {
                    throw wex;
                }
            }
            finally
            {
                if (rp != null)
                {
                    rp.Close();
                }

                if (sr != null)
                {
                    sr.Close();
                }

                rp = null;
                sr = null;
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="downLoadUrl">文件的url路径</param>
        /// <param name="saveFullName">需要保存在本地的路径(包含文件名)</param>
        /// <returns></returns>
        public static bool DownloadFile(string downLoadUrl, string saveFullName)
        {
            bool flagDown = false;
            System.Net.HttpWebRequest httpWebRequest = null;
            try
            {
                //根据url获取远程文件流
                httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl);

                System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                System.IO.Stream sr = httpWebResponse.GetResponseStream();

                //创建本地文件写入流
                System.IO.Stream sw = new System.IO.FileStream(saveFullName, System.IO.FileMode.Create);

                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = sr.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    sw.Write(by, 0, osize);
                    osize = sr.Read(by, 0, (int)by.Length);
                }
                System.Threading.Thread.Sleep(100);
                flagDown = true;
                sw.Close();
                sr.Close();
            }
            catch (System.Exception)
            {
                if (httpWebRequest != null)
                    httpWebRequest.Abort();
            }
            return flagDown;
        }
Пример #50
0
        public async void StartDownload(DownloadInfo info)
        {
            this.downloadSize = 0;
            if (String.IsNullOrEmpty(info.DownLoadUrl))
            {
                throw new Exception("下载地址不能为空!");
            }
            if (info.DownLoadUrl.ToLower().StartsWith("http://"))
            {
                await Task.Run(() =>
                {
                    bool isError = false;
                    try
                    {
                        long totalSize          = 0;
                        long threadInitedLength = 0; //分配线程任务的下载量

                        #region 获取文件信息
                        //打开网络连接
                        System.Net.HttpWebRequest initRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(info.DownLoadUrl);
                        System.Net.WebResponse initResponse   = initRequest.GetResponse();
                        FileMessage fileMsg = GetFileMessage(initResponse);
                        totalSize           = fileMsg.Length;
                        if ((!String.IsNullOrEmpty(fileMsg.FileName)) && info.LocalSaveFolder != null)
                        {
                            info.SavePath = Path.Combine(info.LocalSaveFolder, fileMsg.FileName);
                        }
                        //ReaderWriterLock readWriteLock = new ReaderWriterLock();
                        #endregion

                        #region 读取配置文件
                        string configPath      = info.SavePath.Substring(0, info.SavePath.LastIndexOf(".")) + ".cfg";
                        List <object> initInfo = null;
                        if (File.Exists(configPath) && (info.IsNew == false))
                        {
                            initInfo     = this.ReadConfig(configPath);
                            downloadSize = (long)initInfo[0];
                            totalSize    = (long)initInfo[1];
                        }
                        #endregion

                        #region  计算速度
                        //Stopwatch MyStopWatch = new Stopwatch();
                        long lastDownloadSize    = 0;     //上次下载量
                        bool isSendCompleteEvent = false; //是否完成
                        Timer timer = new Timer(new TimerCallback((o) =>
                        {
                            if (!isSendCompleteEvent && !isError)
                            {
                                DownloadEvent e = new DownloadEvent();
                                e.DownloadSize  = downloadSize;
                                e.TotalSize     = totalSize;
                                if (totalSize > 0 && downloadSize == totalSize)
                                {
                                    e.Speed             = 0;
                                    isSendCompleteEvent = true;
                                    eventFinished.Set();
                                }
                                else
                                {
                                    e.Speed          = downloadSize - lastDownloadSize;
                                    lastDownloadSize = downloadSize; //更新上次下载量
                                }

                                DownloadEvent(e);
                            }
                        }), null, 0, 1000);
                        #endregion

                        string tempPath = info.SavePath.Substring(0, info.SavePath.LastIndexOf(".")) + ".dat";

                        #region 多线程下载
                        //分配下载队列
                        Queue <ThreadDownloadInfo> downQueue = null;
                        if (initInfo == null || info.IsNew)
                        {
                            downQueue = new Queue <ThreadDownloadInfo>(); //下载信息队列
                            while (threadInitedLength < totalSize)
                            {
                                ThreadDownloadInfo downInfo = new ThreadDownloadInfo();
                                downInfo.startLength        = threadInitedLength;
                                downInfo.length             = (int)Math.Min(Math.Min(THREAD_BUFFER_SIZE, totalSize - threadInitedLength), totalSize / info.ThreadCount); //下载量
                                downQueue.Enqueue(downInfo);
                                threadInitedLength += downInfo.length;
                            }
                        }
                        else
                        {
                            downQueue = (Queue <ThreadDownloadInfo>)initInfo[2];
                        }

                        System.IO.FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate);
                        fs.SetLength(totalSize);
                        int threads = info.ThreadCount;

                        for (int i = 0; i < info.ThreadCount; i++)
                        {
                            ThreadPool.QueueUserWorkItem((state) =>
                            {
                                ThreadWork(info.DownLoadUrl, fs, downQueue);
                                if (Interlocked.Decrement(ref threads) == 0)
                                {
                                    (state as AutoResetEvent).Set();
                                }
                            }, eventFinished);
                        }

                        //等待所有线程完成
                        eventFinished.WaitOne();
                        if (fs != null)
                        {
                            fs.Close();
                        }
                        fs = null;
                        if (File.Exists(info.SavePath))
                        {
                            File.Delete(info.SavePath);
                        }

                        if (downloadSize == totalSize)
                        {
                            File.Move(tempPath, info.SavePath);
                            File.Delete(configPath);
                        }

                        if (cancelTokenSource.IsCancellationRequested && StopEvent != null)
                        {
                            StopEvent();
                            //保存配置文件
                            SaveConfig(configPath, downloadSize, totalSize, downQueue);
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        isError = true;
                        if (ErrorMakedEvent != null)
                        {
                            ErrorMakedEvent(ex.Message);
                        }
                    }
                });
            }
        }
Пример #51
0
        static bool ZamijeniDllHelper(string dllWebFolder, string dllFileName, string localPath)
        {
            string path = localPath + "\\" + dllFileName;

            bool status = false;

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

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

                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 = (double)(iRunningByteTotal);

                    double dTotal = (double)iSize;

                    double dProgressPercentage = (dIndex / dTotal);

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

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

                //MessageBox.Show(sFileSavePath + "\n\n" + path);
                System.IO.File.Copy(sFileSavePath, path, true);

                status = true;

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

            catch (Exception exM)
            {
                //Show if any error Occured

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

            return(status);
        }
Пример #52
0
        public static string ExecuteCreateGetHttpResponseProxy(string url, int?timeout, string cookie)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();;

            List <Exception> e = new List <Exception>();
            int retry          = 3;

            for (var i = 0; i < retry; i++)
            {
                bool hasException = false;
                try
                {
                    var userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
                    //#if DEBUG

                    //                    Debug.WriteLine("start" + url);
                    //                    Console.WriteLine("start" + url);
                    //#endif
                    System.Net.HttpWebRequest request = WebRequest.Create(url) as System.Net.HttpWebRequest;
                    request.Method    = "GET";
                    request.UserAgent = DefaultUserAgent;
                    if (!string.IsNullOrEmpty(userAgent))
                    {
                        request.UserAgent = userAgent;
                    }
                    if (timeout.HasValue)
                    {
                        request.Timeout = timeout.Value;
                    }
                    //if (cookies != null)
                    //{
                    //    request.CookieContainer = new CookieContainer();
                    //    request.CookieContainer.Add(cookies);
                    //}
                    request.Headers["cookie"] = cookie;

                    fillProxyMogu(request);

                    var MyResponse = request.GetResponse() as HttpWebResponse;

                    string strReturn = string.Empty;
                    Stream stream    = MyResponse.GetResponseStream();

                    var encoding = Encoding.GetEncoding("utf-8");
                    // 如果要下载的页面经过压缩,则先解压
                    if (MyResponse.ContentEncoding.ToLower().IndexOf("gzip") >= 0)
                    {
                        stream = new GZipStream(stream, CompressionMode.Decompress);
                    }
                    if (encoding == null)
                    {
                        encoding = Encoding.Default;
                    }
                    strReturn += new StreamReader(stream, encoding).ReadToEnd();//解决乱码:utf-8 + streamreader.readtoend
#if DEBUG
                    stopWatch.Stop();
                    Debug.WriteLine($"cost {stopWatch.ElapsedMilliseconds} ms,url{url}");
                    Console.WriteLine($"cost {stopWatch.ElapsedMilliseconds} ms,url{url}");
                    Debug.WriteLine("success      " + url);
                    Console.WriteLine("success       " + url);
#endif
                    return(strReturn);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("proxy out time");
                    throw new Exception("proxy out time");
                    e.Add(ex);
                    hasException = true;
                }
                if (hasException)
                {
                    Task.Delay(1000);
                }
            }


            return(String.Empty);
        }
Пример #53
0
        /// <summary>
        /// Méthode qui effectue une transaction avec Paypal
        /// </summary>
        /// <param name="qui">Notes spéciales</param>
        /// <param name="ccNumber">Numéro de carte de crédit</param>
        /// <param name="ccType">Type de CC</param>
        /// <param name="expireDate">Date d'expiration</param>
        /// <param name="cvvNum">Numéro de sécurité</param>
        /// <param name="amount">Montant</param>
        /// <param name="firstName">Premier nom</param>
        /// <param name="lastName">Nom de famille</param>
        /// <param name="street">adresse</param>
        /// <param name="city">ville</param>
        /// <param name="state">province/état</param>
        /// <param name="zip">Code postal</param>
        /// <returns>Résultat de l'opération dans un String</returns>
        public static String doTransaction(string qui, string ccNumber, string ccType, string expireDate, string cvvNum, string amount, string firstName, string lastName, string street, string city, string state, string zip)
        {
            String retour = "";

            //API INFORMATIONS (3)
            // https://www.sandbox.paypal.com/signin/
            // REGARDER payment received
            // PARLER DE IPN

            String strUsername  = "******";                      // nom du compte marchand dans le sandbox, payment pro activé
            String strPassword  = "******";                                               // password du ccompte marchand
            String strSignature = "AC9Q08PxViawtHP02THEb8XxIkxkA4xEwrqh4Z1Or4uoBpmX9BLd7IhR"; // clé d'authentification compte marchand

            string strCredentials      = "CUSTOM=" + qui + "&USER="******"&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
            string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
            string strAPIVersion       = "2.3";


            dynamic strNVP = strCredentials + "&METHOD=DoDirectPayment" + "&CREDITCARDTYPE=" + ccType + "&ACCT=" + ccNumber + "&EXPDATE=" + expireDate + "&CVV2=" + cvvNum + "&AMT=" + amount + "&CURRENCYCODE=CAD" + "&FIRSTNAME=" + firstName + "&LASTNAME=" + lastName + "&STREET=" + street + "&CITY=" + city + "&STATE=" + state + "&ZIP=" + zip + "&COUNTRYCODE=CA" + "&PAYMENTACTION=Sale" + "&VERSION=" + strAPIVersion;

            try
            {
                //Cree la requête
                System.Net.HttpWebRequest wrWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strNVPSandboxServer);
                wrWebRequest.Method = "POST";
                System.IO.StreamWriter requestWriter = new System.IO.StreamWriter(wrWebRequest.GetRequestStream());
                requestWriter.Write(strNVP);
                requestWriter.Close();
                //Obtient la réponse
                System.Net.HttpWebResponse hwrWebResponse = (System.Net.HttpWebResponse)wrWebRequest.GetResponse();
                dynamic responseReader = new System.IO.StreamReader(wrWebRequest.GetResponse().GetResponseStream());
                // Lit la réponse
                string dataReturned = responseReader.ReadToEnd();
                responseReader.Close();
                string    result        = HttpUtility.UrlDecode(dataReturned);
                string[]  arrResult     = result.Split('&');
                Hashtable htResponse    = new Hashtable();
                string[]  arrayReturned = null;
                foreach (string item in arrResult)
                {
                    arrayReturned = item.Split('=');
                    htResponse.Add(arrayReturned[0], arrayReturned[1]);
                }

                string strAck = htResponse["ACK"].ToString();
                //AFFICHE LA RÉPONSE

                if (strAck == "Success" || strAck == "SuccessWithWarning")
                {
                    string strAmt           = htResponse["AMT"].ToString();
                    string strCcy           = htResponse["CURRENCYCODE"].ToString();
                    string strTransactionID = htResponse["TRANSACTIONID"].ToString();
                    foreach (DictionaryEntry i in htResponse)
                    {
                        retour += i.Key + ": " + i.Value + "<br />";
                    }
                    //on retourne le message de confirmation
                    retour = "true";
                    //retour = "Merci pour votre commande de : $" + strAmt + " " + strCcy + ", celle-ci a bien été traitée.";
                }
                else
                {
                    //Dim strErr As String = "Error: " & htResponse("L_LONGMESSAGE0").ToString()
                    //Dim strErrcode As String = "Error code: " & htResponse("L_ERRORCODE0").ToString()

                    //Response.Write(strErr & "&lt;br /&gt;" & strErrcode)</span>
                    foreach (DictionaryEntry i in htResponse)
                    {
                        retour += i.Key + ": " + i.Value + "<br />";
                    }

                    //retourne les éléments des erreurs importantes
                    retour = "Error: " + htResponse["L_LONGMESSAGE0"].ToString() + "<br/>" + "Error code: " + htResponse["L_ERRORCODE0"].ToString();
                }
            }
            catch (Exception ex)
            {
                retour = ex.ToString();
            }
            return(retour);
        }
Пример #54
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                String url        = Page.Request.QueryString["url"];
                String fromMemory = Page.Request.QueryString["memory"];
                if (url != null)
                {
                    try
                    {
                        lblError.Text = "";
                        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                        request.UseDefaultCredentials = true;

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

                        System.IO.Stream responseStream = response.GetResponseStream();

                        string fileName = Path.GetRandomFileName();

                        //new System.Drawing.Bitmap(responseStream).Save(@"C:\Digitas\" + fileName + ".tif", System.Drawing.Imaging.ImageFormat.Tiff);

                        //System.IO.Stream tbStream = File.OpenRead(@"C:\Digitas\" + fileName + ".tif");

                        decoder = new TiffBitmapDecoder(responseStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        int pagecount = decoder.Frames.Count;


                        //lblError.Text = pagecount.ToString();
                        TiffBitmapEncoder encoderFile = new TiffBitmapEncoder();
                        images = new List <System.Drawing.Image>();

                        for (int i = 0; i < decoder.Frames.Count; i++)
                        {
                            MemoryStream      ms      = new MemoryStream();
                            TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                            //ddlPaginas.Items.Add("Página " + (i + 1));
                            encoder.Frames.Add(decoder.Frames[i]);
                            encoder.Save(ms);
                            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                            images.Add(img);

                            MemoryStream ms3 = new MemoryStream();
                            images[i].Save(ms3, System.Drawing.Imaging.ImageFormat.Tiff);
                            System.Windows.Media.Imaging.BitmapFrame bmFrame = System.Windows.Media.Imaging.BitmapFrame.Create(ms3);
                            encoderFile.Frames.Add(bmFrame);
                        }
                        Session["images"] = images;
                        System.IO.FileStream fsTemp = new System.IO.FileStream(@"C:\Digitas\" + fileName + ".tif", FileMode.Create);
                        encoderFile.Save(fsTemp);
                        fsTemp.Close();

                        //Response.ContentType = "image/jpeg";
                        //new System.Drawing.Bitmap(responseStream).Save(@"C:\Digitas\Temp_Tiff.tif", System.Drawing.Imaging.ImageFormat.Tiff);


                        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 5, 5, 5, 5);
                        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Digitas\" + fileName + ".pdf", System.IO.FileMode.Create));

                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Digitas\" + fileName + ".tif");
                        int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                        document.Open();

                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                        for (int k = 0; k < total; ++k)
                        {
                            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                            // scale the image to fit in the page
                            img.ScaleAbsolute(600, 800);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                        document.Close();
                        Response.ContentType = "Application/pdf";
                        Response.TransmitFile(@"C:\Digitas\" + fileName + ".pdf");

                        /*
                         * System.Drawing.Image img = System.Drawing.Image.FromStream(responseStream);
                         *
                         * Tiff image = Tiff.ClientOpen("memory", "r", responseStream, new TiffStream());
                         *
                         * if (img == null)
                         * {
                         *  lblError.Text = "Null image s";
                         * }
                         * else
                         * {
                         *  img.Save(@"C:\Digitas\digit.tif");
                         * }
                         *
                         * if (image == null)
                         * {
                         *  lblError.Text = "Null image tiff";
                         * }
                         * else
                         * {
                         *  var num = image.NumberOfDirectories();
                         *  lblError.Text = num.ToString();
                         * }
                         */



                        /*
                         * MemoryStream ms2 = new MemoryStream();
                         * images[0].Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                         * //BinaryReader br = new BinaryReader(ms2);
                         * //Byte[] bytes = br.ReadBytes((Int32)ms2.Length);
                         * byte[] bytes = ms2.ToArray();
                         * //string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                         * string base64String = Convert.ToBase64String(bytes);
                         * //string base64String = Convert.ToBase64String((byte[])img);
                         * Image1.ImageUrl = "data:image/jpg;base64," + base64String;
                         */
                        /*
                         * Session["images"] = images;
                         *
                         *
                         * var document = new Document(PageSize.LETTER, 5, 5, 5, 5);
                         *
                         * // Create a new PdfWriter object, specifying the output stream
                         * var output = new MemoryStream();
                         * var writer = PdfWriter.GetInstance(document, output);
                         *
                         * document.Open();
                         *
                         * for (int i = 0; i < images.Count; i++)
                         * {
                         *  var image = iTextSharp.text.Image.GetInstance(images[i], iTextSharp.text.BaseColor.WHITE);
                         *  image.ScaleAbsolute(600, 800);
                         *  document.Add(image);
                         *  document.NewPage();
                         * }
                         *
                         * document.Close();
                         *
                         * Response.ContentType = "application/pdf";
                         * //Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Receipt-{0}.pdf", txtOrderID.Text));
                         * Response.BinaryWrite(output.ToArray());
                         *
                         *
                         * // Open the Document for writing
                         *
                         * //img.Save(@"C:\Digitas\digit2.jpg");
                         *
                         * //Response.ContentType = "image/jpeg";
                         * //new System.Drawing.Bitmap(ms).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                         *
                         * //HttpContext.Current.Response.Flush();
                         * //HttpContext.Current.Response.SuppressContent = true;
                         * //HttpContext.Current.ApplicationInstance.CompleteRequest();
                         *
                         * /*HttpContext.Current.Response.Flush();
                         * HttpContext.Current.Response.SuppressContent = true;
                         * HttpContext.Current.ApplicationInstance.CompleteRequest();
                         *
                         * /*FileWebRequest request = (FileWebRequest)WebRequest.Create(url);
                         *
                         * request.UseDefaultCredentials = true;
                         *
                         * System.Net.FileWebResponse response = (System.Net.FileWebResponse)request.GetResponse();*/

                        //System.IO.Stream responseStream = response.GetResponseStream();

                        /*System.IO.StreamReader reader = new StreamReader(responseStream);
                         *
                         * if (reader == null)
                         * {
                         *  lblError.Text = "Null";
                         * }
                         * else
                         * {
                         *  MemoryStream ms = new MemoryStream();
                         *  responseStream.CopyTo(ms);
                         *  /*responseStream.Close();
                         *  reader.Close();
                         *
                         *  Tiff image = Tiff.ClientOpen("memory", "r", ms, new TiffStream());
                         *
                         *  if (image == null)
                         *  {
                         *      lblError.Text = "Null image";
                         *  }
                         *  lblError.Text = ms.Length.ToString();
                         *  using (FileStream file = new FileStream(@"C:\Digitas\digit.tif", FileMode.Create, System.IO.FileAccess.Write))
                         *  {
                         *      byte[] bytes = new byte[ms.Length];
                         *      ms.Read(bytes, 0, (int)ms.Length);
                         *      file.Write(bytes, 0, bytes.Length);
                         *      //ms.Close();
                         *      //file.Close();
                         *  }
                         *
                         *  Tiff image = Tiff.Open(@"C:\Digitas\digit.tif", "r");
                         *  if (image == null)
                         *  {
                         *      lblError.Text = "Null image";
                         *  }
                         *  else
                         *  {
                         *      var num = image.NumberOfDirectories();
                         *      lblError.Text = num.ToString();
                         *  }
                         *
                         *
                         * }*/
                    }
                    catch (System.Exception ex)
                    {
                        lblError.Text = lblError.Text + " 0.- " + ex.Message;
                    }
                }
                else if (fromMemory == null)
                {
                    try
                    {
                        RPPMain.SharepointLibrary spLibrary = new RPPMain.SharepointLibrary("http://servidors04/sitios/digitalizacion", "Seccion Primera", "autostore", "Rpp1234");
                        //RPPMain.SharepointLibrary spLibrary = new RPPMain.SharepointLibrary("http://servidors04/sitios/digitalizacion", "Seccion Primera", "administrador", "Zmy45r1");

                        //int documentoID = int.Parse(Page.Request.QueryString["documentoID"]);

                        String reg_act_tomo     = Page.Request.QueryString["tomo"];
                        String reg_act_semestre = Page.Request.QueryString["semestre"];
                        String reg_act_año      = Page.Request.QueryString["anio"];
                        String reg_act_seccion  = Page.Request.QueryString["seccion"];
                        String reg_act_serie    = Page.Request.QueryString["serie"];
                        String reg_act_partida  = Page.Request.QueryString["partida"];
                        String reg_act_libro    = Page.Request.QueryString["libro"];

                        bool   firstParameter  = true;
                        bool   secondParameter = false;
                        bool   nextParameter   = false;
                        string query           = "";

                        if (reg_act_tomo.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_semestre.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_año.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_seccion.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_serie.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_partida.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_libro.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq></And>";
                                }
                            }
                        }

                        query = "<View><Query><Where>" + query + "</Where></Query></View>";

                        query = string.Format(@"<View>
                                                <Query>
                                                    <Where>
                                                        <And>
                                                            <And>
                                                                <And>
                                                                    <And>
                                                                        <And>
                                                                            <And>
                                                                                <Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq>
                                                                                <Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq>
                                                                            </And>
                                                                            <Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq>
                                                                        </And>
                                                                        <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq>
                                                                    </And>
                                                                    <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>
                                                                </And>
                                                                <Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq>
                                                            </And>
                                                            <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq>                                                            
                                                        </And>
                                                    </Where>
                                                </Query>
                                            </View>",
                                              reg_act_tomo,
                                              reg_act_semestre,
                                              reg_act_año,
                                              reg_act_seccion,
                                              reg_act_serie,
                                              reg_act_partida,
                                              reg_act_libro);


                        /*query = string.Format(@query,
                         *          reg_act_tomo,
                         *          reg_act_semestre,
                         *          reg_act_año,
                         *          reg_act_seccion,
                         *          reg_act_serie,
                         *          reg_act_partida,
                         *          reg_act_libro);*/

                        /*string query = string.Format(@"<View>
                         *                             <Query>
                         *                                 <Where>
                         *                                     <And>
                         *                                     <And>
                         *                                     <And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{0}</Value></Eq>
                         *                                         <Eq><FieldRef Name='Partida' /><Value Type='Text'>{1}</Value></Eq>
                         *                                     </And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{2}</Value></Eq>
                         *                                     </And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{3}</Value></Eq>
                         *                                     </And>
                         *                                 </Where>
                         *                             </Query>
                         *                         </View>",
                         *     2384,
                         *     1,
                         *     1,
                         *     "A");*/

                        System.Collections.ArrayList arlRows = spLibrary.GetLibraryItem(query);

                        if (arlRows.Count > 0)
                        {
                            lblError.Text = "";

                            Microsoft.SharePoint.Client.ListItem      itemRepositorio = (Microsoft.SharePoint.Client.ListItem)arlRows[0];
                            Dictionary <string, object>               dc   = (Dictionary <string, object>)itemRepositorio.FieldValues;
                            Microsoft.SharePoint.Client.FieldUrlValue fURl = (Microsoft.SharePoint.Client.FieldUrlValue)dc["Pagina"];

                            try
                            {
                                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(fURl.Url);
                                request.UseDefaultCredentials = true;

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

                                System.IO.Stream responseStream = response.GetResponseStream();

                                /*Response.ContentType = "image/jpeg";
                                 * new System.Drawing.Bitmap(responseStream).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                 *
                                 * HttpContext.Current.Response.Flush();
                                 * HttpContext.Current.Response.SuppressContent = true;
                                 * HttpContext.Current.ApplicationInstance.CompleteRequest();*/
                            }
                            catch (System.Exception ex)
                            {
                                lblError.Text = lblError.Text + " 1.- " + ex.Message;
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        lblError.Text = lblError.Text + " 2.- " + ex.Message;
                    }
                }
                else if (fromMemory != null)
                {
                    try
                    {
                        images = new List <System.Drawing.Image>();
                        images = (List <System.Drawing.Image>)Session["images"];

                        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                        MemoryStream      ms3     = new MemoryStream();

                        for (int i = 0; i < images.Count; i++)
                        {
                            //ddlPaginas.Items.Add("Página " + (i + 1));
                            ms3 = new MemoryStream();
                            images[i].Save(ms3, System.Drawing.Imaging.ImageFormat.Tiff);
                            System.Windows.Media.Imaging.BitmapFrame bmFrame = System.Windows.Media.Imaging.BitmapFrame.Create(ms3);
                            encoder.Frames.Add(bmFrame);
                        }

                        /*
                         * MemoryStream ms2 = new MemoryStream();
                         * images[0].Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                         * byte[] bytes = ms2.ToArray();
                         * string base64String = Convert.ToBase64String(bytes);
                         * Image1.ImageUrl = "data:image/jpg;base64," + base64String;
                         *
                         * /*string fileName = Path.GetTempFileName();
                         *
                         * lblError.Text = fileName;
                         *
                         * Session["tempFileName"] = fileName;*/

                        string fileName = Path.GetRandomFileName();

                        Session["tempFileName"] = fileName + ".tif";

                        System.IO.FileStream fsTemp = new System.IO.FileStream(@"C:\Digitas\" + fileName + ".tif", FileMode.Create);
                        encoder.Save(fsTemp);
                        fsTemp.Close();



                        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 5, 5, 5, 5);
                        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Digitas\" + fileName + ".pdf", System.IO.FileMode.Create));

                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Digitas\" + fileName + ".tif");
                        int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                        document.Open();
                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                        for (int k = 0; k < total; ++k)
                        {
                            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                            // scale the image to fit in the page
                            img.ScaleAbsolute(600, 800);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                        document.Close();

                        Response.ContentType = "Application/pdf";
                        Response.TransmitFile(@"C:\Digitas\" + fileName + ".pdf");
                    }
                    catch (Exception exc)
                    {
                        lblError.Text = exc.Message;
                    }
                }
            }
            else
            {
                //decoder = (TiffBitmapDecoder)Session["decoder"];
                images = new List <System.Drawing.Image>();
                images = (List <System.Drawing.Image>)Session["images"];
            }
        }
Пример #55
0
        //Function that is executed once button is clicked and goes through various checks and eventually adds the e-mail or domain to the blocked sites profile group in mimecast
        public void AddBlockedSite()
        {
            //Setup required variables - ENTER YOUR OWN HERE
            string baseUrl         = "https://us-api.mimecast.com";
            string uri             = "/api/directory/add-group-member";
            string accessKey       = "enter your own here";
            string secretKey       = "enter your own here";
            string appId           = "enter your own here";
            string appKey          = "enter your own here";
            string blockedsenderid = "enter your own here";

            //Code borrowed from Mimecast's API Documentation with modifications to work with this application
            //Generate request header values
            string hdrDate   = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
            System.Security.Cryptography.HMAC h = new System.Security.Cryptography.HMACSHA1(System.Convert.FromBase64String(secretKey));

            //Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
            byte[] hash = h.ComputeHash(System.Text.Encoding.Default.GetBytes(hdrDate + ":" + requestId + ":" + uri + ":" + appKey));

            //Build the signature to be included in the Authorization header in your request
            string signature = "MC " + accessKey + ":" + System.Convert.ToBase64String(hash);

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method      = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = signature;
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            // checks to see if domain or e-mail address is checked
            if (rb_domain.IsChecked == true)
            {
                status.Content = ("Domain selected.");
                if (CheckDomain(tb_entry.Text))
                {
                    status.Content = ("Domain is valid.");

                    //Add request body
                    //Create and write data to stream
                    string postData = "{\"data\": [{\"id\": \"" + blockedsenderid + "\",\"domain\": \"" + tb_entry.Text + "\"}]}";

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

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

                    //Send Request
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                    //Output response to console
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    string responseBody           = "";
                    string temp = null;
                    while ((temp = reader.ReadLine()) != null)
                    {
                        responseBody += temp;
                    }
                    ;

                    //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries from Mimecast's API
                    var jsonDoc         = JsonDocument.Parse(responseBody);
                    var root            = jsonDoc.RootElement;
                    var entrystatus     = root.GetProperty("meta");
                    var entryfailstatus = root.GetProperty("fail");

                    //error handling and updating status if status is 200 and no failures this means the site was successfully added, if not it confirms status ok but there were failures
                    if (entrystatus.ToString() == "{\"status\":200}")
                    {
                        if (entryfailstatus.ToString() == "[]")
                        {
                            status.Content = ("Domain added successfully.");
                        }
                        else
                        {
                            status.Content = ("Status OK but failures present!");
                        }
                    }
                    else
                    {
                        status.Content = ("Domain not blocked, status failed.");
                    }
                }
                else
                {
                    status.Content = ("Domain is on free-email list, please recheck!");
                }
            }
            if (rb_email.IsChecked == true)
            {
                if (ValidateEmail(tb_entry.Text))
                {
                    status.Content = ("Valid e-mail");

                    //Add request body
                    //Create and write data to stream
                    string postData = "{\"data\": [{\"id\": \"" + blockedsenderid + "\",\"emailAddress\": \"" + tb_entry.Text + "\"}]}";

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

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

                    //Send Request
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                    //Output response to console
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    string responseBody           = "";
                    string temp = null;
                    while ((temp = reader.ReadLine()) != null)
                    {
                        responseBody += temp;
                    }
                    ;

                    //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries
                    var jsonDoc         = JsonDocument.Parse(responseBody);
                    var root            = jsonDoc.RootElement;
                    var entrystatus     = root.GetProperty("meta");
                    var entryfailstatus = root.GetProperty("fail");

                    //error handling and updating status if status is 200 and no failures this means the e-mail was successfully added, if not it confirms status ok but there were failures
                    if (entrystatus.ToString() == "{\"status\":200}")
                    {
                        if (entryfailstatus.ToString() == "[]")
                        {
                            status.Content = ("E-mail address added successfully.");
                        }
                        else
                        {
                            status.Content = ("Status OK but failures present!");
                        }
                    }
                    else
                    {
                        status.Content = ("E-mail address not blocked, status failed.");
                    }
                }
                else
                {
                    status.Content = ("E-mail address entered is not valid!");
                }
            }
        }
Пример #56
0
        public static async Task Render_Quick_Scene_P2EP_PS1(SocialLinkerCommand sl_command, OfficialSetData set_data, MakerCommandData command_data)
        {
            // Create variables to store the width and height of the template.
            int template_width  = 320;
            int template_height = 240;

            // Create two variables for the command user and the command channel, derived from the message object taken in.
            SocketUser        user    = sl_command.User;
            SocketTextChannel channel = (SocketTextChannel)sl_command.Channel;

            // Send a loading message to the channel while the sprite sheet is being made.
            RestUserMessage loader = await channel.SendMessageAsync("", false, P2EP_PS1_Loading_Message().Build());

            // Get the account information of the command's user.
            var account = UserInfoClasses.GetAccount(user);

            BustupData bustup_data = BustupDataMethods.Get_Bustup_Data(account, set_data, command_data);

            // Create a starting base bitmap to render all graphics on.
            Bitmap base_template = new Bitmap(template_width, template_height);

            // Create another bitmap the same size.
            // In case the user has set a colored bitmap in their settings, we'll need to use this to render it.
            Bitmap colored_background_bitmap = new Bitmap(template_width, template_height);

            // Here, we want to grab any images attached to the message to use it as a background.
            // Create a variable for the message attachment.
            var attachments = sl_command.Attachments;

            // Create an empty string variable to hold the URL of the attachment.
            string url = "";

            // If there are no attachments on the message, set the URL string to "None".
            if (attachments == default || attachments.LongCount() == 0)
            {
                url = "None";
            }
            // Else, assign the URL of the attachment to the URL string.
            else
            {
                url = attachments.ElementAt(0).Url;
            }

            // Initialize a bitmap object for the user's background. It's small now because we'll reassign it depending on our circumstances.
            Bitmap background = new Bitmap(2, 2);

            // If a URL for a message attachment exists, download it and copy its contents to the bitmap variable we just created.
            if (url != "None")
            {
                // Here, we'll want to try and retrieve the user's input image.
                try
                {
                    // Declare variables for a web request to retrieve the image.
                    System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                    webRequest.AllowWriteStreamBuffering = true;
                    webRequest.Timeout = 30000;

                    // Create a stream and download the image to it.
                    System.Net.WebResponse webResponse = webRequest.GetResponse();
                    System.IO.Stream       stream      = webResponse.GetResponseStream();

                    // Copy the stream's contents to the background bitmap variable.
                    background = (Bitmap)System.Drawing.Image.FromStream(stream);

                    webResponse.Close();
                }
                // If an exception occurs here, the filetype is likely incompatible.
                // Send an error message, delete the loading message, and return.
                catch (System.ArgumentException e)
                {
                    Console.WriteLine(e);
                    await loader.DeleteAsync();

                    _ = ErrorHandling.Incompatible_File_Type(sl_command);
                    return;
                }
            }

            // Render the uploaded image based on the user's background settings.
            switch (account.Setting_BG_Upload)
            {
            case "Maintain Aspect Ratio":
                background = Center_Image(background);
                break;

            case "Stretch to Fit":
                background = Stretch_To_Fit(background);
                break;
            }

            // The user may have a custom mono-colored background designated in their settings. Let's handle that now.
            // Check if the user's background color setting is set to something other than "Transparent".
            // If so, we have a color to render for the background!
            if (account.Setting_BG_Color != "Transparent")
            {
                // Convert the user's HTML color setting to one we can use and assign it to a color variable.
                System.Drawing.Color user_background_color = System.Drawing.ColorTranslator.FromHtml(account.Setting_BG_Color);

                // Color the entirety of the background bitmap the user's selected color.
                using (Graphics graphics = Graphics.FromImage(colored_background_bitmap))
                {
                    graphics.Clear(user_background_color);
                }
            }

            // Next, time for the conversation portrait! Create and initialize a new bitmap variable for it.
            Bitmap bustup = new Bitmap(2, 2);

            // Check if the base sprite number is something other than zero.
            // If it is zero, we have nothing to render. Otherwise, retrieve the bustup.
            if (command_data.Base_Sprite != 0)
            {
                bustup = OfficialSetMethods.Bustup_Selection(sl_command, account, set_data, bustup_data, command_data);
            }

            // If the bustup returns as null, however, something went wrong with rendering the animation frames.
            // An error message has already been sent in the frame rendering method, so delete the loading message and return.
            if (bustup == null)
            {
                await loader.DeleteAsync();

                return;
            }

            List <string>[] dialogue_lines = Line_Parser(sl_command, command_data.Dialogue);

            // Time to put it all together!
            using (Graphics graphics = Graphics.FromImage(base_template))
            {
                // Draw the input dialogue to the template.
                graphics.DrawImage(Render_Bustup(account, bustup_data, bustup), 0, 0, template_width, template_height);
                graphics.DrawImage(Render_Message_Window(account), 0, 0, template_width, template_height);
                graphics.DrawImage(Combined_Text_Layers(bustup_data, dialogue_lines), 0, 0, template_width, template_height);
            }

            // Save the entire base template to a data stream.
            MemoryStream memoryStream = new MemoryStream();

            base_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
            memoryStream.Seek(0, SeekOrigin.Begin);

            try
            {
                // Send the image.
                await sl_command.Channel.SendFileAsync(memoryStream, $"scene_{sl_command.User.Id}_{DateTime.UtcNow}.png");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                // Send an error message to the user if the image upload fails.
                _ = ErrorHandling.Image_Upload_Failed(sl_command);

                // Clean up resources used by the stream, delete the loading message, and return.
                memoryStream.Dispose();
                await loader.DeleteAsync();

                return;
            }

            // Clean up resources used by the stream and delete the loading message.
            memoryStream.Dispose();
            await loader.DeleteAsync();

            // If the user has auto-delete for their commands set to on, delete their command as well.
            if (account.Auto_Delete_Commands == "On")
            {
                await sl_command.Message.DeleteAsync();
            }
        }
Пример #57
0
        private void DownloadFileFromWeb(string productName)
        {
            try
            {
                ProductRelease productRelease = AsposeManager.GetProductReleaseInformation(productName);
                if (productRelease == null)
                {
                    return;
                }

                string downloadURL        = productRelease.DownloadLink;
                string downloadFolderRoot = AsposeManager.GetAsposeDownloadFolder(productName);
                GlobalData.backgroundWorker.ReportProgress(1);

                if (AsposeManager.IsReleaseExists(productName, downloadFolderRoot, productRelease.VersionNumber))
                {
                    GlobalData.backgroundWorker.ReportProgress(100);
                    return;
                }

                string downloadedReleasePath = downloadFolderRoot + "\\" + productName.ToLower() + ".zip";
                GlobalData.backgroundWorker.ReportProgress(1);

                Uri    url       = new Uri(downloadURL);
                string sFileName = Path.GetFileName(url.LocalPath);

                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;
                WebClient  client            = new WebClient();
                Stream     strRemote         = client.OpenRead(url);
                FileStream strLocal          = new FileStream(downloadedReleasePath, FileMode.Create, FileAccess.Write, 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 = (double)(iRunningByteTotal);
                    double dTotal = (double)iSize;
                    double dProgressPercentage = (dIndex / dTotal);
                    int    iProgressPercentage = (int)(dProgressPercentage * 98);

                    GlobalData.backgroundWorker.ReportProgress(iProgressPercentage);
                }
                strLocal.Close();
                strRemote.Close();

                AsposeManager.ExtractZipFile(downloadedReleasePath, downloadFolderRoot);
                AsposeManager.SaveReleaseInfo(productName, downloadFolderRoot, productRelease.VersionNumber);
                GlobalData.backgroundWorker.ReportProgress(100);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occurred while downloading Aspose components. Your module will be created but may not contain all the components you have selected. Please make sure you have an active internet connection and then try creating the project again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (Form != null)
                {
                    Form.Dispose();
                }
            }

            GlobalData.backgroundWorker.ReportProgress(100);
        }
Пример #58
0
        public bool CreateThread(string title, string name, string mailAddress, string contents)
        {
            Match  m                = GetRegexMatchURL();
            string url              = null;
            string postData         = null;
            string referer          = ThreadURL;
            int    jbbsBaseIndex    = 1;
            bool   isThreadCreation = title != null;

            if (!m.Success)
            {
                if (isThreadCreation)
                {
                    m = GetRegexMatchBaseURL();

                    if (!m.Success)
                    {
                        return(false);
                    }
                    jbbsBaseIndex = 0;
                    referer       = BaseURL;
                }
                else
                {
                    return(false);
                }
            }

            CookieContainer cookieContainer = new CookieContainer();


            DateTime writeTime = DateTime.Now;
            DateTime orgTime   = DateTime.Parse("1970/1/1 00:00:00");

            int unixTime = (int)((writeTime.ToFileTimeUtc() - orgTime.ToFileTimeUtc()) / 10000000);

            for (int i = 0; i < 2; i++)
            {
                switch (Response.Style)
                {
                case Response.BBSStyle.jbbs:
                {
                    url = string.Format("{0}/bbs/write.cgi", m.Groups[1].Value);

                    string submitText      = "書き込む";
                    string additionalParam = "";

                    if (isThreadCreation)
                    {
                        submitText       = "新規スレッド作成";
                        additionalParam += "&SUBJECT=" + UrlEncode(title);
                    }
                    else
                    {
                        additionalParam += "&KEY==" + m.Groups[5].Value;
                    }

                    postData = string.Format("DIR={0}&BBS={1}&TIME={2}&NAME={3}&MAIL={4}&MESSAGE={5}&submit={6}" + additionalParam
                                             , m.Groups[2 + jbbsBaseIndex].Value
                                             , m.Groups[3 + jbbsBaseIndex].Value
                                             , unixTime
                                             , UrlEncode(name)
                                             , UrlEncode(mailAddress)
                                             , UrlEncode(contents)
                                             , UrlEncode(submitText)
                                             );

                    break;
                }

                case Response.BBSStyle.yykakiko:
                case Response.BBSStyle.nichan:
                {
                    url = string.Format("{0}/test/bbs.cgi", m.Groups[1].Value);

                    string submitText      = "書き込む";
                    string additionalParam = "";
                    string nameText        = name;
                    string subject         = "";

                    if (isThreadCreation)
                    {
                        submitText       = "新規スレッド作成";
                        subject          = title;
                        additionalParam += "&subject=" + UrlEncode(subject);
                    }
                    else
                    {
                        additionalParam += "&key=" + m.Groups[3].Value;
                    }



                    if (i == 1)
                    {
                        submitText = "上記全てを承諾して書き込む";
                    }

                    if (Response.Style == Response.BBSStyle.nichan)
                    {
                        additionalParam += "&tepo=don";
                    }
                    else
                    {
                        additionalParam += "&MIRV=kakkoii";
                    }



                    postData = string.Format("bbs={0}&time={1}&FROM={2}&mail={3}&MESSAGE={4}&submit={5}" + additionalParam
                                             , m.Groups[2].Value
                                             , unixTime
                                             , UrlEncode(nameText)
                                             , UrlEncode(mailAddress)
                                             , UrlEncode(contents)
                                             , UrlEncode(submitText)
                                             );

                    if (i == 1)
                    {
                        url += "?guid=ON";
                    }

                    if (Response.Style == Response.BBSStyle.nichan && isThreadCreation)
                    {
                        referer = url;
                    }
                    break;
                }

                case Response.BBSStyle.zerochan:
                {
                    url = string.Format("{0}/2ch/test/bbs.cgi", m.Groups[1].Value);

                    string submitText      = "書き込む";
                    string additionalParam = "";
                    string nameText        = name;
                    string subject         = "";

                    if (isThreadCreation)
                    {
                        submitText       = "新規スレッド作成";
                        subject          = title;
                        additionalParam += "&subject=" + UrlEncode(subject);
                    }
                    else
                    {
                        additionalParam += "&key=" + m.Groups[3].Value;
                    }



                    if (i == 1)
                    {
                        submitText = "上記全てを承諾して書き込む";
                    }

                    if (Response.Style == Response.BBSStyle.zerochan)
                    {
                        additionalParam += "&tepo=don";
                    }



                    postData = string.Format("bbs={0}&time={1}&FROM={2}&mail={3}&MESSAGE={4}&submit={5}" + additionalParam
                                             , m.Groups[2].Value
                                             , unixTime
                                             , UrlEncode(nameText)
                                             , UrlEncode(mailAddress)
                                             , UrlEncode(contents)
                                             , UrlEncode(submitText)
                                             );

                    if (i == 1)
                    {
                        url += "?guid=ON";
                    }

                    if (Response.Style == Response.BBSStyle.nichan && isThreadCreation)
                    {
                        referer = url;
                    }
                    break;
                }
                }

                byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);


                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls
                                                        | SecurityProtocolType.Tls11
                                                        | SecurityProtocolType.Tls12
                                                        | SecurityProtocolType.Ssl3;
                System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                FormMain.UserConfig.SetProxy(webReq);

                webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko";

                //Cookieの設定
                webReq.CookieContainer = new CookieContainer();
                webReq.CookieContainer.Add(cookieContainer.GetCookies(webReq.RequestUri));
                //webReq.UserAgent = "Monazilla / 1.00(monaweb / 1.00)";

                //メソッドにPOSTを指定
                webReq.Method = "POST";

                //ContentTypeを"application/x-www-form-urlencoded"にする
                webReq.ContentType = "application/x-www-form-urlencoded";
                //POST送信するデータの長さを指定
                webReq.ContentLength = postDataBytes.Length;
                //
                webReq.Referer = referer;


                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls
                                                        | SecurityProtocolType.Tls11
                                                        | SecurityProtocolType.Tls12
                                                        | SecurityProtocolType.Ssl3;
                System.Net.HttpWebResponse webRes = null;

                try
                {
                    //データをPOST送信するためのStreamを取得
                    using (System.IO.Stream reqStream = webReq.GetRequestStream())
                    {
                        //送信するデータを書き込む
                        reqStream.Write(postDataBytes, 0, postDataBytes.Length);
                    }

                    webRes = (System.Net.HttpWebResponse)webReq.GetResponse();

                    //受信したCookieのコレクションを取得する
                    System.Net.CookieCollection cookies =
                        webReq.CookieContainer.GetCookies(webReq.RequestUri);
                    //Cookie名と値を列挙する
                    //foreach (System.Net.Cookie cook in cookies)
                    //{
                    //    Console.WriteLine("{0}={1}", cook.Name, cook.Value);
                    //}
                    //取得したCookieを保存しておく
                    cookieContainer.Add(cookies);


                    //応答データを受信するためのStreamを取得
                    System.IO.Stream resStream = webRes.GetResponseStream();
                    //受信して表示
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(resStream, GetEncoding()))
                    {
                        ReturnText = sr.ReadToEnd();
                    }

                    if (ReturnText.IndexOf("書き込み確認") >= 0)
                    {
                        //referer = url;
                        continue;
                    }

                    string temp = ReturnText.Replace("\n", "");
                    m = htmlBodyRegex.Match(temp);

                    if (m.Success)
                    {
                        ReturnText = Response.ConvertToText(m.Groups[1].Value);
                    }



                    if (ReturnText.IndexOf("ERROR") >= 0 || ReturnText.IndexOf("ERROR") >= 0)
                    {
                        return(false);
                    }


                    return(true);
                }
                catch (Exception e)
                {
                    ReturnText = e.Message;
                    return(false);
                }
            }

            return(false);
        }
Пример #59
0
        public new string PostData(string url, string postData)
        {
            string result = string.Empty;

            try
            {
                System.Uri requestUri = new System.Uri(url);
                System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestUri);
                System.Text.Encoding      uTF            = System.Text.Encoding.UTF8;
                byte[] bytes = uTF.GetBytes(postData);
                httpWebRequest.Method        = "POST";
                httpWebRequest.ContentType   = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = (long)bytes.Length;
                using (System.IO.Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
                using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse())
                {
                    using (System.IO.Stream responseStream = httpWebResponse.GetResponseStream())
                    {
                        System.Text.Encoding uTF2   = System.Text.Encoding.UTF8;
                        System.IO.Stream     stream = responseStream;
                        if (httpWebResponse.ContentEncoding.ToLower() == "gzip")
                        {
                            stream = new GZipStream(responseStream, CompressionMode.Decompress);
                        }
                        else
                        {
                            if (httpWebResponse.ContentEncoding.ToLower() == "deflate")
                            {
                                stream = new DeflateStream(responseStream, CompressionMode.Decompress);
                            }
                        }
                        using (System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, uTF2))
                        {
                            result = streamReader.ReadToEnd();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                result = string.Format("获取信息错误:{0}", ex.Message);
            }
            return(result);
        }
Пример #60
-1
        /// <summary>
        /// Fetches the <see cref="scrape"/> after logging into the <see cref="url"/> with the specified <see cref="postdata"/>
        /// </summary>
        /// <param name="url">The URL to login at </param>
        /// <param name="postdata">The postdata to login with.</param>
        /// <param name="scrape">The page to scrape.</param>
        /// <returns>The fetched page</returns>
        private string GetPage(string url, string postdata, string scrape)
        {
            req = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookies = new CookieContainer();
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            req.CookieContainer = cookies;

            StreamWriter requestWriter = new StreamWriter(req.GetRequestStream());
            requestWriter.Write(postdata);
            requestWriter.Close();

            req.GetResponse();
            cookies = req.CookieContainer;

            req = WebRequest.Create(scrape) as HttpWebRequest;
            req.CookieContainer = cookies;

            StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());

            string response = responseReader.ReadToEnd();
            responseReader.Close();

            return response;
        }