コード例 #1
0
ファイル: nclwebproxy.cs プロジェクト: zhimaqiao51/docs
    //</snippet9>
    //<snippet10>
    public static void DisplayDefaultProxy()
    {
        WebProxy proxy = WebProxy.GetDefaultProxy();

        Console.WriteLine("Address: {0}", proxy.Address);

        Console.WriteLine("Bypass on local: {0}",
                          proxy.BypassProxyOnLocal);
        int count = proxy.BypassList.Length;

        if (count == 0)
        {
            Console.WriteLine("The bypass list is empty.");
            return;
        }
        string[] bypass = proxy.BypassList;
        Console.WriteLine("The bypass list contents:");

        for (int i = 0; i < count; i++)
        {
            Console.WriteLine(bypass[i]);
        }
    }
コード例 #2
0
        //**************************************Funciones necesarias para las demás funciones****************************************
        private static string HacerRequest(string query)
        {
            string json = "";

            try
            {
                //se crea el objeto para hacer el request
                WebRequest request = WebRequest.Create(query);
                request = WebRequest.Create(query);
                WebProxy myProxy = new WebProxy("myproxy", 80);
                myProxy.BypassProxyOnLocal = true;
                request.Proxy = WebProxy.GetDefaultProxy();

                //se obtiene la respuesta en un flujo de datos
                Stream objStream = request.GetResponse().GetResponseStream();

                //se convierte el flujo de datos en cadena
                StreamReader objReader = new StreamReader(objStream);
                json = objReader.ReadLine();
            }
            catch { }
            return(json);
        }
コード例 #3
0
 public void doDownloadFile(string url)
 {
     if (!Directory.Exists(Properties.Settings.Default.downloadsDirectory))
     {
         MessageBox.Show(frmOpenTheatre.rm.GetString("noDownloadDirectory")); return;
     }
     if (Properties.Settings.Default.connectionCustom == true)
     {
         if (Properties.Settings.Default.connectionHost != null && Properties.Settings.Default.connectionPort != null)
         {
             wc.Proxy = new WebProxy(Properties.Settings.Default.connectionHost, Convert.ToInt32(Properties.Settings.Default.connectionPort)); wc.Proxy.Credentials = new NetworkCredential(Properties.Settings.Default.connectionUsername, Properties.Settings.Default.connectionPassword); wc.UseDefaultCredentials = false;
         }
     }
     else
     {
         wc.Proxy = WebProxy.GetDefaultProxy(); wc.Proxy.Credentials = CredentialCache.DefaultCredentials; wc.UseDefaultCredentials = true;
     }
     wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(downloadCompleted);
     wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgressChanged);
     wc.DownloadFileAsync(new Uri(url), Properties.Settings.Default.downloadsDirectory + Path.GetFileNameWithoutExtension(new Uri(url).LocalPath) + @"\" + Path.GetFileName(new Uri(url).LocalPath)); sw.Start(); startTime = DateTime.Now;
     infoFileURL       = url;
     infoFileName.Text = Path.GetFileName(new Uri(url).LocalPath);
 }
コード例 #4
0
 public void doDownloadFile(string url)
 {
     if (!Directory.Exists(Properties.Settings.Default.downloadsDirectory))
     {
         MessageBox.Show("Specified download directory doesn't exist"); return;
     }
     if (Properties.Settings.Default.connectionCustom == true)
     {
         if (Properties.Settings.Default.connectionHost != null && Properties.Settings.Default.connectionPort != null)
         {
             wc.Proxy = new WebProxy(Properties.Settings.Default.connectionHost, Convert.ToInt32(Properties.Settings.Default.connectionPort)); wc.Proxy.Credentials = new NetworkCredential(Properties.Settings.Default.connectionUsername, Properties.Settings.Default.connectionPassword); wc.UseDefaultCredentials = false;
         }
     }
     else
     {
         wc.Proxy = WebProxy.GetDefaultProxy(); wc.Proxy.Credentials = CredentialCache.DefaultCredentials; wc.UseDefaultCredentials = true;
     }
     wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(downloadCompleted);
     wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgressChanged);
     wc.DownloadFileAsync(new Uri(url), Properties.Settings.Default.downloadsDirectory + Path.GetFileName(new Uri(url).LocalPath));
     lblFileName.Text = Path.GetFileName(new Uri(url).LocalPath);
     sw.Start();
 }
コード例 #5
0
        /// <summary>
        /// 测试代理配置
        /// </summary>
        /// <param name="setting">代理信息</param>
        /// <param name="te">测试信息</param>
        public static bool TestProxy(ProxySettingEntity setting, TestEntity te)
        {
            if (setting == null)
            {
                return(false);
            }
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(te.TestUrl);
            WebProxy       proxy      = WebProxy.GetDefaultProxy();

            if (setting.Ip != null && setting.Ip != "" && setting.Port != 0)
            {
                proxy.Address = new Uri("http://" + setting.Ip + ":" + setting.Port + "/");

                if (!string.IsNullOrEmpty(setting.UserName) &&
                    !string.IsNullOrEmpty(setting.Password))
                {
                    proxy.Credentials = new NetworkCredential(setting.UserName, setting.Password);
                }
            }
            webRequest.Proxy = proxy;

            webRequest.Method    = "Get";
            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
            WebResponse response = webRequest.GetResponse();
            string      html     = GetHtmlString(response, Encoding.GetEncoding(te.TestWebEncoding));

            response.Close();

            if (html.Contains(te.TestWebTitle))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #6
0
        public string GetTemMethodtemp(string city)
        {
            string sURL, sURL1, sURL2;

            sURL1 = "https://weather.cit.api.here.com/weather/1.0/report.json?product=observation&name=";
            sURL2 = "&app_id=DemoAppId01082013GAL&app_code=AJKnXv84fjrb0KIHawS0Tg";
            sURL  = sURL1 + city + sURL2;

            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 80);

            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int    start = 0;
            int    end   = 0;

            //int i = 0;
            sLine = objReader.ReadToEnd();
            start = sLine.LastIndexOf(",\"temperature\":\"");   //   ,"temperature":"  ,\"temperature\":\"
            sLine = sLine.Substring(start + 16);
            end   = sLine.LastIndexOf("\",\"tem");
            sLine = sLine.Substring(0, end);        //   \",\"tem

            return(sLine);
        }
コード例 #7
0
    void doGet()
    {
        string sURL;

        sURL = "https://api.openweathermap.org/data/2.5/weather?q=Madrid&lang=es&units=metric&appid=" + meAPI;

        WebRequest wrGETURL;

        wrGETURL = WebRequest.Create(sURL);

        WebProxy myProxy = new WebProxy("myproxy", 80);

        myProxy.BypassProxyOnLocal = true;

        wrGETURL.Proxy = WebProxy.GetDefaultProxy();

        Stream objStream;

        objStream = wrGETURL.GetResponse().GetResponseStream();

        StreamReader objReader = new StreamReader(objStream);

        StartCoroutine(LogConsole(objReader));
    }
コード例 #8
0
        public static WebProxy GetWebServiceProxy()
        {
            string address = Configuration.GetWebServiceProxy();

            if (WebServiceAddressChanged(address))
            {
                if (StringHelper.IsEmpty(address))
                {
                    WebProxy defaultProxy = WebProxy.GetDefaultProxy();
                    if (defaultProxy != null)
                    {
                        defaultProxy.Credentials = CredentialCache.DefaultCredentials;
                    }

                    _webServiceProxy        = defaultProxy;
                    _webServiceProxyAddress = null;
                }
                else
                {
                    _webServiceProxy = new WebProxy(address, true);
                    if (Configuration.GetWebServiceProxyCredential() == null)
                    {
                        _webServiceProxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        _webServiceProxy.UseDefaultCredentials = false;
                        _webServiceProxy.Credentials           = Configuration.GetWebServiceProxyCredential();
                    }

                    _webServiceProxyAddress = address;
                }
            }

            return(_webServiceProxy);
        }
コード例 #9
0
    public static Socket createSocket(String targetHost, String targetPort)
    {
        WebProxy myProxy  = (WebProxy)WebProxy.GetDefaultProxy();
        Uri      proxyUri = myProxy.GetProxy(new Uri("https://en.wikipedia.org/wiki/Main_Page"));

        Console.WriteLine("connecting by default proxy {0}", proxyUri);
        myProxy.Credentials = CredentialCache.DefaultCredentials;

        var request = WebRequest.Create("http://" + targetHost + ":" + targetPort);

        request.Proxy  = myProxy;
        request.Method = "CONNECT";

        var response = request.GetResponse();

        var responseStream = response.GetResponseStream();

        Debug.Assert(responseStream != null);

        const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;

        var rsType             = responseStream.GetType();
        var connectionProperty = rsType.GetProperty("Connection", Flags);

        var connection            = connectionProperty.GetValue(responseStream, null);
        var connectionType        = connection.GetType();
        var networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags);

        var    networkStream  = networkStreamProperty.GetValue(connection, null);
        var    nsType         = networkStream.GetType();
        var    socketProperty = nsType.GetProperty("Socket", Flags);
        Socket socket         = (Socket)socketProperty.GetValue(networkStream, null);

        Console.WriteLine("proxy tunnel established");
        return(socket);
    }
コード例 #10
0
ファイル: frmRegister.cs プロジェクト: danygolden/gianfratti
        private void btnSave_Click(object sender, EventArgs e)
        {
            string errorMessage = "";

            if (txtName.Text.Trim() == "")
            {
                errorMessage += "Name can not be left blank.\r\n";
            }
            if (txtSurname.Text.Trim() == "")
            {
                errorMessage += "Surname can not be left blank.\r\n";
            }
            if (txtEmail.Text.Trim() == "")
            {
                errorMessage += "Email can not be left blank.\r\n";
            }
            if (errorMessage != "")
            {
                MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            reg.Register r = new Palantir.reg.Register();
            r.Proxy             = WebProxy.GetDefaultProxy();
            r.Proxy.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                r.RegisterUser(txtName.Text, txtSurname.Text, txtEmail.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An Error Occured. Please Try Again Later.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("Registration Successful");
            this.Close();
        }
コード例 #11
0
        public user getBestEmployee()
        {
            string sURL;

            sURL = "http://localhost:18080/HRSmart-web/rest/userbuisnesses/1/bestEmployee";
            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 80);

            myProxy.BypassProxyOnLocal = false;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();


            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);
            string       sLine     = "";
            int          i         = 0;
            string       final     = "";

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    final = final + sLine;
                }
            }
            return(JsonConvert.DeserializeObject <user>(final));
        }
コード例 #12
0
        public static BEWSConsultarCIPResponseMod1 ConsultarCIP(BEWSConsultarCIPRequestMod1 request)
        {
            request.CodServ = ConfigurationManager.AppSettings["PE_MERCHAND_ID"];
            BEWSConsultarCIPResponseMod1 response = new BEWSConsultarCIPResponseMod1();

            try
            {
                using (var proxy = new WSCrypto())
                {
                    proxy.Credentials       = System.Net.CredentialCache.DefaultNetworkCredentials;
                    proxy.Proxy             = WebProxy.GetDefaultProxy();
                    proxy.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                    request.CIPS            = request.CIPS.Trim();
                    request.Firma           = proxy.Signer(request.CIPS, ByteUtil.FileToByteArray(PrivateKey));
                    request.CIPS            = proxy.EncryptText(request.CIPS, ByteUtil.FileToByteArray(PublicKey));
                    using (var proxyCIP = new Service())
                    {
                        response = proxyCIP.ConsultarCIPMod1(request);
                        if (response != null)
                        {
                            if (!String.IsNullOrEmpty(response.XML))
                            {
                                response.XML = proxy.DecryptText(response.XML, ByteUtil.FileToByteArray(PrivateKey));
                            }
                        }
                    }
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Mensaje = ex.Message;
                response.Estado  = "-1";
                return(response);
            }
        }
コード例 #13
0
        public void Main()
        {
            string sURL;

            sURL = "http://www.microsoft.com";

            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 22);

            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int    i     = 0;

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    Console.WriteLine("{0}:{1}", i, sLine);
                }
            }
            Console.ReadLine();
        }
コード例 #14
0
        static void Main12(string[] args)
        {
            string sURL;

            sURL = "http://127.0.0.1:3000/getPosts";

            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 80);

            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int    i     = 0;

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    Console.WriteLine("{0}:{1}", i, sLine);
                }
            }
            Console.ReadLine();
        }
コード例 #15
0
        static void Main(string[] args)
        {
            string sURL;

            sURL = "http://localhost:8000/impressions?dc=EU";

            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 80);

            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            String jsonNA = "";

            //int i = 0;
            jsonNA = objReader.ReadLine();

            Ad absoluteaids = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <Ad>(jsonNA);

            //testing
            Console.WriteLine("{0}", absoluteaids.data[7].timestamp);
            Console.ReadLine();

            //Console.WriteLine(json);
            //Console.ReadLine();
        }
コード例 #16
0
        public static void WebProxy_GetDefaultProxy_NotSupported()
        {
#pragma warning disable 0618 // obsolete method
            Assert.Throws <PlatformNotSupportedException>(() => WebProxy.GetDefaultProxy());
#pragma warning restore 0618
        }
コード例 #17
0
    /// <summary>
    /// Return an HttpWebResponse object for a request. You can use the Response to
    /// read the result as needed. This is a low level method. Most of the other 'Get'
    /// methods call this method and process the results further.
    /// </summary>
    /// <remarks>Important: The Response object's Close() method must be called when you are done with the object.</remarks>
    /// <param name="Url">Url to retrieve.</param>
    /// <returns>An HttpWebResponse Object</returns>
    public HttpWebResponse GetUrlResponse(string Url)
    {
        this.Cancelled = false;

        try
        {
            this.bError        = false;
            this.cErrorMessage = "";
            this.bCancelled    = false;

            if (this.WebRequest == null)
            {
                this.WebRequest = (HttpWebRequest)System.Net.WebRequest.Create(Url);
                this.WebRequest.Headers.Add("Cache", "no-cache");
            }


            this.WebRequest.UserAgent = this.cUserAgent;
            this.WebRequest.Timeout   = this.nConnectTimeout * 1000;

            // *** Handle Security for the request
            if (this.cUsername.Length > 0)
            {
                if (this.cUsername == "AUTOLOGIN")
                {
                    this.WebRequest.Credentials = CredentialCache.DefaultCredentials;
                }
                else
                {
                    this.WebRequest.Credentials = new NetworkCredential(this.cUsername, this.cPassword);
                }
            }

            // *** Handle Proxy Server configuration
            if (this.cProxyAddress.Length > 0)
            {
                if (this.cProxyAddress == "DEFAULTPROXY")
                {
                    this.WebRequest.Proxy = new WebProxy();
                    this.WebRequest.Proxy = WebProxy.GetDefaultProxy();
                }
                else
                {
                    WebProxy loProxy = new WebProxy(this.cProxyAddress, true);
                    if (this.cProxyBypass.Length > 0)
                    {
                        loProxy.BypassList = this.cProxyBypass.Split(';');
                    }

                    if (this.cProxyUsername.Length > 0)
                    {
                        loProxy.Credentials = new NetworkCredential(this.cProxyUsername, this.cProxyPassword);
                    }

                    this.WebRequest.Proxy = loProxy;
                }
            }

            // *** Handle cookies - automatically re-assign
            if (this.bHandleCookies || (this.oCookies != null && this.oCookies.Count > 0))
            {
                this.WebRequest.CookieContainer = new CookieContainer();
                if (this.oCookies != null && this.oCookies.Count > 0)
                {
                    this.WebRequest.CookieContainer.Add(this.oCookies);
                }
            }

            // *** Deal with the POST buffer if any
            if (this.oPostData != null)
            {
                this.WebRequest.Method = "POST";
                switch (this.nPostMode)
                {
                case HttpPostMode.UrlEncoded:
                    this.WebRequest.ContentType = "application/x-www-form-urlencoded";
                    // strip off any trailing & which can cause problems with some
                    // http servers
                    //							if (this.cPostBuffer.EndsWith("&"))
                    //								this.cPostBuffer = this.cPostBuffer.Substring(0,this.cPostBuffer.Length-1);
                    break;

                case HttpPostMode.MultiPart:
                    this.WebRequest.ContentType = "multipart/form-data; boundary=" + this.cMultiPartBoundary;
                    this.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + this.cMultiPartBoundary + "\r\n"));
                    break;

                case HttpPostMode.Xml:
                    this.WebRequest.ContentType = "text/xml";
                    break;

                case HttpPostMode.Raw:
                    this.WebRequest.ContentType = "application/octet-stream";
                    break;

                default:
                    goto case HttpPostMode.UrlEncoded;
                }


                Stream loPostData = this.WebRequest.GetRequestStream();

                if (this.SendData == null)
                {
                    this.oPostStream.WriteTo(loPostData);                              // Simplest version - no events
                }
                else
                {
                    this.StreamPostBuffer(loPostData);                                 // Send in chunks and fire events
                }
                //*** Close the memory stream
                this.oPostStream.Close();
                this.oPostStream = null;

                //*** Close the Binary Writer
                this.oPostData.Close();
                this.oPostData = null;

                //*** Close Request Stream
                loPostData.Close();

                // *** If user cancelled the 'upload' exit
                if (this.Cancelled)
                {
                    this.ErrorMessage = "HTTP Request was cancelled.";
                    this.Error        = true;
                    return(null);
                }
            }

            // *** Retrieve the response headers
            HttpWebResponse Response = (HttpWebResponse)this.WebRequest.GetResponse();

            this.oWebResponse = Response;


            // *** Close out the request - it cannot be reused
            this.WebRequest = null;

            // ** Save cookies the server sends
            if (this.bHandleCookies)
            {
                if (Response.Cookies.Count > 0)
                {
                    if (this.oCookies == null)
                    {
                        this.oCookies = Response.Cookies;
                    }
                    else
                    {
                        // ** If we already have cookies update the list
                        foreach (Cookie oRespCookie in Response.Cookies)
                        {
                            bool bMatch = false;
                            foreach (Cookie oReqCookie in this.oCookies)
                            {
                                if (oReqCookie.Name == oRespCookie.Name)
                                {
                                    oReqCookie.Value = oRespCookie.Value;
                                    bMatch           = true;
                                    break;                        //
                                }
                            }                                     // for each ReqCookies
                            if (!bMatch)
                            {
                                this.oCookies.Add(oRespCookie);
                            }
                        }          // for each Response.Cookies
                    }              // this.Cookies == null
                }                  // if Response.Cookie.Count > 0
            }                      // if this.bHandleCookies = 0


            return(Response);
        }
        catch (Exception e)
        {
            if (this.bThrowExceptions)
            {
                throw e;
            }

            this.cErrorMessage = e.Message;
            this.bError        = true;
            return(null);
        }
    }
コード例 #18
0
        static WebRequestHelper()
        {
            m_proxy = WebProxy.GetDefaultProxy();

            //m_proxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ProxyUserName"],ConfigurationManager.AppSettings["ProxyPassword"],ConfigurationManager.AppSettings["ProxyDomain"]);
        }
        internal async Task <string> GetSpecification()
        {
            if (string.IsNullOrEmpty(this.UserSettings.Endpoint))
            {
                throw new ArgumentNullException("OpenAPI (Swagger) Specification Endpoint", "Please input the OpenAPI (Swagger) specification endpoint.");
            }

            //if (!this.UserSettings.Endpoint.EndsWith(".json", StringComparison.Ordinal))
            //    throw new ArgumentException("Please input the OpenAPI (Swagger) specification endpoint ends with \".json\".", "OpenAPI (Swagger) Specification Endpoint");

            var workFile = Path.GetTempFileName();

            try
            {
                // from url
                if (this.UserSettings.Endpoint.StartsWith("http://", StringComparison.Ordinal) || this.UserSettings.Endpoint.StartsWith("https://", StringComparison.Ordinal))
                {
                    var proxy = this.UseWebProxy ? new WebProxy(this.WebProxyUri, true) : WebProxy.GetDefaultProxy();
                    proxy.Credentials = this.UseWebProxy && this.UseWebProxyCredentials
                        ? new NetworkCredential(this.WebProxyNetworkCredentialsUserName,
                                                this.WebProxyNetworkCredentialsPassword, this.WebProxyNetworkCredentialsDomain)
                        : CredentialCache.DefaultCredentials;
                    var httpHandler = new HttpClientHandler();

                    if (this.UseWebProxy)
                    {
                        httpHandler.UseProxy        = this.UseWebProxy;
                        httpHandler.Proxy           = proxy;
                        httpHandler.PreAuthenticate = this.UseWebProxy;
                    }

                    if (this.UseNetworkCredentials)
                    {
                        httpHandler.UseDefaultCredentials = this.UseNetworkCredentials;
                        httpHandler.Credentials           = new NetworkCredential(this.NetworkCredentialsUserName,
                                                                                  this.NetworkCredentialsPassword, this.NetworkCredentialsDomain);
                    }

                    using (var httpClient = new HttpClient(httpHandler))
                    {
                        var specificationEndpoint = await httpClient.GetStringAsync(this.UserSettings.Endpoint);

                        if (string.IsNullOrWhiteSpace(specificationEndpoint))
                        {
                            throw new InvalidOperationException("The specification endpoint is an empty.");
                        }

                        if (this.UserSettings.Endpoint.EndsWith(".json") && !ProjectHelper.IsJson(specificationEndpoint))
                        {
                            throw new InvalidOperationException("Service endpoint ends with \".json\" is not an json.");
                        }

                        File.WriteAllText(workFile, specificationEndpoint);
                    }
                }
                else // from local path
                {
                    if (!File.Exists(this.UserSettings.Endpoint))
                    {
                        throw new ArgumentException("Please input the service endpoint with exists file path.", "OpenAPI Service Endpoint");
                    }

                    var specificationEndpoint = File.ReadAllText(this.UserSettings.Endpoint);
                    if (string.IsNullOrWhiteSpace(specificationEndpoint))
                    {
                        throw new InvalidOperationException("The specification endpoint is an empty file.");
                    }

                    if (this.UserSettings.Endpoint.EndsWith(".json") && !ProjectHelper.IsJson(specificationEndpoint))
                    {
                        throw new InvalidOperationException("Service endpoint ends with \".json\" is not an json-file.");
                    }

                    File.WriteAllText(workFile, specificationEndpoint);
                }

                return(workFile);
            }
            catch (WebException e)
            {
                throw new InvalidOperationException($"Cannot access \"{this.UserSettings.Endpoint}\". {e.Message}", e);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"Cannot access \"{this.UserSettings.Endpoint}\". {e.Message}", e);
            }
        }
コード例 #20
0
        public static string GetHtmlString(Proxy proxy, RefreshThread refresher)
        {
            string result = "";

            if (proxy == null)
            {
                return(result);
            }
            Stopwatch sw = new Stopwatch();

            sw.Start();


            Random r   = new Random();
            string url = refresher.url;
            //if (url.Contains("?"))
            //{
            //    url = url + "&p=" + r.Next(99999);
            //}
            //else
            //{
            //    url = url + "?p=" + r.Next(99999);
            //}

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url).ToString());

            try
            {
                WebProxy proxyServer = WebProxy.GetDefaultProxy();
                if (!string.IsNullOrEmpty(proxy.IP) && proxy.Port != 0)
                {
                    proxyServer.Address = new Uri("http://" + proxy.IpAndPort + "/");
                }
                webRequest.Proxy      = proxyServer;
                refresher.Description = proxy.IpAndPort + "设置完成,开始访问网页...";

                webRequest.Method    = "Get";
                webRequest.Accept    = "*/*";
                webRequest.UserAgent = "Mozilla/4.0 (MSIE 6.0; Windows NT " + r.Next(99999) + ")";
                webRequest.Headers["Accept-Language"] = "zh-cn";
                webRequest.ContentType                  = "application/x-www-form-urlencoded";
                webRequest.Referer                      = "http://www.loamen.com/404.htm?name=refresher&url=" + url;
                webRequest.Timeout                      = refresher.timeOut * 1000;
                webRequest.ReadWriteTimeout             = refresher.timeOut * 1000;
                webRequest.ServicePoint.ConnectionLimit = 100;

                WebResponse response = webRequest.GetResponse();
                result = GetHtmlString(response, Encoding.GetEncoding("GB2312"));
                response.Close();
                sw.Stop();
                refresher.Description = proxy.IpAndPort + "刷新完毕,耗时:" + sw.ElapsedMilliseconds;
                refresher.SuccessCount++;
                return(result);
            }
            catch (Exception ex)
            {
                sw.Stop();
                refresher.FailedCount++;
                refresher.Description = proxy.IpAndPort + "出错啦:" + ex.Message + sw.ElapsedMilliseconds;
                return(result);
            }
            finally
            {
                webRequest.Abort();
            }
        }
コード例 #21
0
        private static APIClient _initAPIClient()
        {
            var clientId     = CloudConfigurationManager.GetSetting("JciClientId");
            var clientSecret = CloudConfigurationManager.GetSetting("JciClientSecret");

            if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentException("JciClientId and/or JciClientSecret is not valid");
            }

            var tokenEndpoint = CloudConfigurationManager.GetSetting("JciTokenEndpoint");
            var baseAPIRoot   = CloudConfigurationManager.GetSetting("JciBuildingApiEndpoint");

            if (string.IsNullOrEmpty(tokenEndpoint) || string.IsNullOrEmpty(baseAPIRoot))
            {
                throw new ArgumentException("API base Urls are not valid");
            }

            var tokenProvider = new TokenClient(clientId, clientSecret, tokenEndpoint, WebProxy.GetDefaultProxy());

            return(new APIClient(tokenProvider, baseAPIRoot));
        }
コード例 #22
0
        private static RssFeed read(string url, HttpWebRequest request, RssFeed oldFeed)
        {
            // ***** Marked for substantial improvement
            RssFeed    feed    = new RssFeed();
            RssElement element = null;
            Stream     stream  = null;
            Uri        uri     = new Uri(url);

            feed.url = url;

            switch (uri.Scheme)
            {
            case "file":
                feed.lastModified = File.GetLastWriteTime(url);
                if ((oldFeed != null) && (feed.LastModified == oldFeed.LastModified))
                {
                    oldFeed.cached = true;
                    return(oldFeed);
                }
                stream = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                break;

            case "https":
            case "http":
                if (request == null)
                {
                    request                   = (HttpWebRequest)WebRequest.Create(uri);
                    request.Proxy             = WebProxy.GetDefaultProxy();
                    request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                }

                if (oldFeed != null)
                {
                    request.IfModifiedSince = oldFeed.LastModified;
                    request.Headers.Add("If-None-Match", oldFeed.ETag);
                }

                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    feed.lastModified = response.LastModified;
                    feed.etag         = response.Headers["ETag"];
                    try
                    {
                        if (response.ContentEncoding != String.Empty)
                        {
                            feed.encoding = Encoding.GetEncoding(response.ContentEncoding);
                        }
                    }
                    catch {}

                    stream = response.GetResponseStream();
                }
                catch (WebException)
                {
                    if (oldFeed != null)
                    {
                        oldFeed.cached = true;
                        return(oldFeed);
                    }

                    throw;
                }
                break;
            }

            if (stream != null)
            {
                RssReader reader = null;
                try
                {
                    reader = new RssReader(stream);
                    do
                    {
                        element = reader.Read();
                        if (element is RssChannel)
                        {
                            feed.Channels.Add((RssChannel)element);
                        }
                    }while (element != null);
                    feed.rssVersion = reader.Version;
                }
                finally
                {
                    feed.exceptions = reader.Exceptions;
                    reader.Close();
                }
            }
            else
            {
                throw new ApplicationException("Not a valid Url");
            }

            return(feed);
        }
コード例 #23
0
        /// <summary>
        /// Return a the result from an HTTP Url into a StreamReader.
        /// Client code should call Close() on the returned object when done reading.
        /// </summary>
        /// <param name="Url">Url to retrieve.</param>
        /// <param name="WebRequest">An HttpWebRequest object that can be passed in with properties preset.</param>
        /// <returns></returns>
        protected StreamReader GetUrlStream(string Url, HttpWebRequest Request)
        {
            try
            {
                this.bError    = false;
                this.cErrorMsg = "";


                if (Request == null)
                {
                    Request = (HttpWebRequest)System.Net.WebRequest.Create(Url);
                }

                Request.AutomaticDecompression = DecompressionMethods.Deflate;
                Request.UserAgent = this.cUserAgent;
                Request.Timeout   = this.nConnectTimeout * 1000;

                // *** Save for external access
                this.oWebRequest = Request;

                // *** Handle Security for the request
                if (this.cUsername.Length > 0)
                {
                    if (this.cUsername == "AUTOLOGIN")
                    {
                        Request.Credentials = CredentialCache.DefaultCredentials;
                    }
                    else
                    {
                        Request.Credentials = new NetworkCredential(this.cUsername, this.cPassword);
                    }
                }

                // *** Handle Proxy Server configuration
                if (this.cProxyAddress.Length > 0)
                {
                    if (this.cProxyAddress == "DEFAULTPROXY")
                    {
                        Request.Proxy = new WebProxy();
                        Request.Proxy = WebProxy.GetDefaultProxy();
                    }
                    else
                    {
                        WebProxy loProxy = new WebProxy(this.cProxyAddress, true);
                        if (this.cProxyBypass.Length > 0)
                        {
                            loProxy.BypassList = this.cProxyBypass.Split(';');
                        }

                        if (this.cProxyUsername.Length > 0)
                        {
                            loProxy.Credentials = new NetworkCredential(this.cProxyUsername, this.cProxyPassword);
                        }

                        Request.Proxy = loProxy;
                    }
                }

                // *** Handle cookies - automatically re-assign
                if (this.bHandleCookies)
                {
                    Request.CookieContainer = new CookieContainer();
                    if (this.oCookies != null && this.oCookies.Count > 0)
                    {
                        Request.CookieContainer.Add(this.oCookies[0]);
                    }
                }

                // *** Deal with the POST buffer if any
                if (this.oPostData != null)
                {
                    Request.Method = "POST";
                    switch (this.nPostMode)
                    {
                    case 1:
                        Request.ContentType = "application/x-www-form-urlencoded";
                        // strip off any trailing & which can cause problems with some
                        // http servers
                        //							if (this.cPostBuffer.EndsWith("&"))
                        //								this.cPostBuffer = this.cPostBuffer.Substring(0,this.cPostBuffer.Length-1);
                        break;

                    case 2:
                        Request.ContentType = "multipart/form-data; boundary=" + this.cMultiPartBoundary;
                        this.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + this.cMultiPartBoundary + "\r\n"));
                        break;

                    case 4:
                        Request.ContentType = "text/xml";
                        break;

                    default:
                        goto case 1;
                    }


                    Stream loPostData = Request.GetRequestStream();
                    //loPostData.Write(lcPostData,0,lcPostData.Length);
                    this.oPostStream.WriteTo(loPostData);

                    //*** Close the memory stream
                    this.oPostStream.Close();
                    this.oPostStream = null;

                    //*** Close the Binary Writer
                    this.oPostData.Close();
                    this.oPostData = null;

                    //*** Close Request Stream
                    loPostData.Close();

                    // *** clear the POST buffer
                    //this.cPostBuffer = "";
                }

                // *** Handle headers - automatically re-assign
                if (this.bHandleHeaders)
                {
                    if (this.oHeaders != null && this.oHeaders.Count > 0)
                    {
                        Request.Headers.Add(this.Headers);
                    }
                }

                // *** Retrieve the response headers
                HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

                // ** Save cookies the server sends
                if (this.bHandleCookies)
                {
                    if (Response.Cookies.Count > 0)
                    {
                        if (this.oCookies == null)
                        {
                            this.oCookies = Response.Cookies;
                        }
                        else
                        {
                            // ** If we already have cookies update the list
                            foreach (Cookie oRespCookie in Response.Cookies)
                            {
                                bool bMatch = false;
                                foreach (Cookie oReqCookie in this.oCookies)
                                {
                                    if (oReqCookie.Name == oRespCookie.Name)
                                    {
                                        oReqCookie.Value = oRespCookie.Name;
                                        bMatch           = true;
                                        break; //
                                    }
                                } // for each ReqCookies
                                if (!bMatch)
                                {
                                    this.oCookies.Add(oRespCookie);
                                }
                            } // for each Response.Cookies
                        }     // this.Cookies == null
                    }         // if Response.Cookie.Count > 0
                }             // if this.bHandleCookies = 0


                // *** Save the response object for external access
                this.oWebResponse = Response;

                Encoding enc;
                try
                {
                    if (Response.ContentEncoding.Length > 0)
                    {
                        enc = Encoding.GetEncoding(Response.ContentEncoding);
                    }
                    else
                    {
                        enc = Encoding.GetEncoding(1252);
                    }
                }
                catch
                {
                    // *** Invalid encoding passed
                    enc = Encoding.GetEncoding(1252);
                }

                // *** drag to a stream
                StreamReader strResponse =
                    new StreamReader(Response.GetResponseStream(), enc);
                return(strResponse);
            }
            catch (Exception e)
            {
                if (this.bThrowExceptions)
                {
                    throw;
                }

                this.cErrorMsg = e.Message;
                this.bError    = true;
                return(null);
            }
        }
コード例 #24
0
ファイル: ical2rdf.cs プロジェクト: qwdf1615/sncore
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Usage();
            }
            else
            {
                ArrayList icalFiles        = new ArrayList();
                bool      startedFilesPart = false;
                bool      supressErrors    = false;
                bool      outputSameName   = false;
                string    rdfFilename      = null;
                int       urlcounter       = 0;

                // first process the flags and arguments
                for (int i = 0; i < args.Length; i++)
                {
                    string arg = args[i];

                    if (arg.StartsWith("-") && !startedFilesPart)
                    {
                        if (arg.Length == 2)
                        {
                            switch (arg[1])
                            {
                            case 'c':
                                Copyright();
                                return;

                            case 'h':
                                Usage();
                                return;

                            case 'p':
                                supressErrors = true;
                                break;

                            case 'x':
                                outputSameName = true;
                                break;

                            case 'f':
                                if (i + 1 >= args.Length)
                                {
                                    Usage();
                                    return;
                                }
                                rdfFilename = args[++i];
                                break;
                            }
                        }
                        else
                        {
                            Usage();
                            return;
                        }
                    }
                    else
                    {
                        startedFilesPart = true;  // ignore any options in the
                        icalFiles.Add(arg);
                    }
                }

                // deactivate the -f flag if there are more than one icsfiles - assume they want
                // file output, which will mean the -x flag...
                if (rdfFilename != null && icalFiles.Count > 1)
                {
                    rdfFilename    = null;
                    outputSameName = true;
                }

                // now loop through the ics files and translate them to RDF
                foreach (string file in icalFiles)
                {
                    TextReader reader;
                    bool       isURL = false;

                    try
                    {
                        if (file.StartsWith("http:"))
                        {
                            isURL = true;
                            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(file);
                            req.Proxy = WebProxy.GetDefaultProxy();
                            WebResponse resp = req.GetResponse();

                            // TODO: Found a 'bug' or 'feature' (depending on perspective), of the StreamReader.Peek()
                            // method.  It does not work on streams that are socket (network) based.  It will
                            // report EOF at the end of packet, instead of end of file.  So - let's read in the
                            // entire stream into memory, and rework the Scanner class so that it doesn't use
                            // Peek().
                            StreamReader tempReader = new StreamReader(resp.GetResponseStream( ));
                            reader = new StringReader(tempReader.ReadToEnd( ));
                        }
                        else
                        {
                            reader = new StreamReader(file);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("Error encountered processing file: " + file + "\n   message: " + e.Message);
                        Usage();
                        return;
                    }

                    RDFEmitter emitter = new RDFEmitter( );
                    Parser     parser  = new Parser(reader, emitter);
                    parser.Parse( );

                    // check for errors
                    if (!supressErrors && parser.HasErrors)
                    {
                        foreach (ParserError error in parser.Errors)
                        {
                            Console.Error.WriteLine("Error on line: " + error.Linenumber + ".  " + error.Message);
                        }
                    }
                    else
                    {
                        // output it!
                        TextWriter writer;

                        if (rdfFilename != null)
                        {
                            writer = new StreamWriter(rdfFilename);
                        }
                        else if (outputSameName)
                        {
                            string outfile, infile;
                            if (isURL)
                            {
                                outfile = "calendar" + urlcounter + ".rdf";
                                urlcounter++;
                            }
                            else
                            {
                                int fslashindex = file.LastIndexOf('/');
                                int bslashindex = file.LastIndexOf('\\');
                                int slashindex  = Math.Max(fslashindex, bslashindex);

                                if (slashindex >= 0)
                                {
                                    infile = file.Substring(slashindex + 1);
                                }
                                else
                                {
                                    infile = file;
                                }

                                int dotindex = infile.LastIndexOf('.');
                                if (dotindex == -1)
                                {
                                    outfile = infile + ".rdf";
                                }
                                else
                                {
                                    outfile = infile.Substring(0, dotindex) + ".rdf";
                                }
                            }
                            writer = new StreamWriter(outfile);
                        }
                        else
                        {
                            writer = Console.Out;
                        }

                        writer.Write(emitter.Rdf);
                    }
                }
            }
        }
コード例 #25
0
 private ConnectionSingleton()
 {
     Browsers    = new BrowserAccessor();
     SystemProxy = WebProxy.GetDefaultProxy();
 }
コード例 #26
0
        private void _btnSubmit_Click(object sender, System.EventArgs e)
        {
            string userName = Core.SettingStore.ReadString("ErrorReport", "UserName");
            string password = Core.SettingStore.ReadString("ErrorReport", "Password");

            if (userName.Length == 0 || password.Length == 0)
            {
                userName = "******";
                password = "******";
            }

            SubmissionResult result = null;

            IExceptionSubmitter submitter = new RPCExceptionSubmitter();

            submitter.SubmitProgress += new SubmitProgressEventHandler(OnSubmitProgress);
            foreach (ListViewItem lvItem in _lvExceptions.SelectedItems)
            {
                Exception ex = (Exception)lvItem.Tag;
                try
                {
                    result = submitter.SubmitException(ex, _excDescription, userName, password,
                                                       Assembly.GetExecutingAssembly().GetName().Version.Build, WebProxy.GetDefaultProxy());
                }
                catch (Exception ex1)
                {
                    MessageBox.Show(this, "Failed to submit exception: " + ex1.Message, Core.ProductFullName);
                    continue;
                }
                _backgroundExceptions.Remove(ex);
            }
            for (int i = _lvExceptions.SelectedItems.Count - 1; i >= 0; i--)
            {
                _lvExceptions.Items.Remove(_lvExceptions.SelectedItems [i]);
            }

            if (result != null)
            {
                ExceptionReportForm.ShowSubmissionResult(this, result, "OM");
            }
            if (_backgroundExceptions.Count == 0)
            {
                DialogResult = DialogResult.OK;
            }
        }
コード例 #27
0
        private void ProcDownload(object o)
        {
            string tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, Constant.Tempfoldername);

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

            _evtPerDonwload = new ManualResetEvent(false);

            foreach (DownloadFileInfo file in _downloadFileList)
            {
                _total += file.Size;
            }

            CommonUnitity.OnLog(this, new EventArgs <string>("tempFolderPath=" + tempFolderPath));
            try
            {
                while (!_evtDownload.WaitOne(0, false))
                {
                    if (_downloadFileList.Count == 0)
                    {
                        break;
                    }

                    DownloadFileInfo file = _downloadFileList[0];

                    CommonUnitity.OnLog(this, new EventArgs <string>(String.Format("Start Download: url={0}, fullname={1}", file.DownloadUrl, file.FileFullName)));

                    ShowCurrentDownloadFileName(file.FileName);

                    //Download
                    _clientDownload = new WebClient();

                    //Added the function to support proxy
                    _clientDownload.Proxy             = WebProxy.GetDefaultProxy();
                    _clientDownload.Proxy.Credentials = CredentialCache.DefaultCredentials;
                    _clientDownload.Credentials       = CredentialCache.DefaultCredentials;
                    //End added

                    _clientDownload.DownloadProgressChanged += (sender, e) =>
                    {
                        try
                        {
                            SetProcessBar(e.ProgressPercentage, (int)((_nDownloadedTotal + e.BytesReceived) * 100 / _total));
                        }
                        catch
                        {
                            CommonUnitity.OnLog(this, new EventArgs <string>("progress changed failed." + e.ProgressPercentage + "/" + e.TotalBytesToReceive));
                            //log the error message,you can use the application's log code
                        }
                    };

                    _clientDownload.DownloadFileCompleted += (sender, e) =>
                    {
                        try
                        {
                            DealWithDownloadErrors();
                            DownloadFileInfo dfile = e.UserState as DownloadFileInfo;
                            _nDownloadedTotal += dfile.Size;
                            SetProcessBar(0, (int)(_nDownloadedTotal * 100 / _total));
                            _evtPerDonwload.Set();

                            CommonUnitity.OnLog(this, new EventArgs <string>("downloadFinished:" + dfile.FileFullName));
                        }
                        catch (Exception ex)
                        {
                            CommonUnitity.OnLog(this, new EventArgs <string>(ex.ToString()));
                            //log the error message,you can use the application's log code
                        }
                    };

                    _evtPerDonwload.Reset();

                    //Download the folder file
                    string tempFolderPath1 = DownloadFileInfo.GetFolderUrl(file);
                    if (!string.IsNullOrEmpty(tempFolderPath1))
                    {
                        tempFolderPath  = Path.Combine(CommonUnitity.SystemBinUrl, Constant.Tempfoldername);
                        tempFolderPath += tempFolderPath1;
                    }
                    else
                    {
                        tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, Constant.Tempfoldername);
                    }

                    _clientDownload.DownloadFileAsync(new Uri(file.DownloadUrl),
                                                      Path.Combine(tempFolderPath, file.FileName), file);

                    //Wait for the download complete
                    _evtPerDonwload.WaitOne();

                    _clientDownload.Dispose();
                    _clientDownload = null;

                    //Remove the downloaded files
                    _downloadFileList.Remove(file);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine(ex.Source);
                CommonUnitity.OnLog(this, new EventArgs <string>(ex.StackTrace));
                ShowErrorAndExitApp();
                //throw;
            }

            //When the files have not downloaded,return.
            if (_downloadFileList.Count > 0)
            {
                return;
            }

            //Test network and deal with errors if there have
            DealWithDownloadErrors();

            //Debug.WriteLine("All Downloaded");
            foreach (DownloadFileInfo file in _allFileList)
            {
                string tempUrlPath = DownloadFileInfo.GetFolderUrl(file);
                string oldPath     = string.Empty;
                string newPath     = string.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(tempUrlPath))
                    {
                        oldPath = Path.Combine(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1), file.FileName);
                        newPath = Path.Combine(CommonUnitity.SystemBinUrl + Constant.Tempfoldername + tempUrlPath, file.FileName);
                    }
                    else
                    {
                        oldPath = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName);
                        newPath = Path.Combine(CommonUnitity.SystemBinUrl + Constant.Tempfoldername, file.FileName);
                    }

//                    //just deal with the problem which the files EndsWith xml can not download
//                    FileInfo f = new FileInfo(newPath);
//                    if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.EndsWith(".xml"))
//                    {
//                        Console.WriteLine("download failed: {0}", f.FullName);
//                        ShowErrorAndExitApp();
//                    }

                    //Added for dealing with the config file download errors
                    string newfilepath = string.Empty;
                    if (newPath.Substring(newPath.LastIndexOf(".") + 1).Equals(Constant.Configfilekey))
                    {
                        if (File.Exists(newPath))
                        {
                            if (newPath.EndsWith("_"))
                            {
                                newfilepath = newPath;
                                newPath     = newPath.Substring(0, newPath.Length - 1);
                                oldPath     = oldPath.Substring(0, oldPath.Length - 1);
                            }
                            File.Move(newfilepath, newPath);
                        }
                    }
                    //End added

                    if (File.Exists(oldPath))
                    {
                        MoveFolderToOld(oldPath, newPath);
                    }
                    else
                    {
                        //Edit for config_ file
                        if (!string.IsNullOrEmpty(tempUrlPath))
                        {
                            if (!Directory.Exists(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1)))
                            {
                                Directory.CreateDirectory(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1));

                                MoveFolderToOld(oldPath, newPath);
                            }
                            else
                            {
                                MoveFolderToOld(oldPath, newPath);
                            }
                        }
                        else
                        {
                            MoveFolderToOld(oldPath, newPath);
                        }
                    }
                }
                catch (Exception exp)
                {
                    CommonUnitity.OnLog(this, new EventArgs <string>(exp.ToString()));
                    //log the error message,you can use the application's log code
                }
            }

            //After dealed with all files, clear the data
            _allFileList.Clear();

            if (_downloadFileList.Count == 0)
            {
                Exit(true);
            }
            else
            {
                Exit(false);
            }

            _evtDownload.Set();
        }
コード例 #28
0
ファイル: ELV.cs プロジェクト: prakash3129/CM
        public ELV(DataTable dtEmailStatus)
        {
            try
            {
                //BackgroundWorker bELV = new BackgroundWorker();
                DateTime dProcess_StartTime = default(DateTime);
                using (SqlConnection con1 = new SqlConnection(GV.sMSSQL1))
                {
                    while (true)
                    {
                        using (DataTable dtEmails = new DataTable())
                        {
                            Thread.Sleep(GV.ibg_Interval);



                            //string sQuery = @"UPDATE c_email_checks AS A INNER JOIN (SELECT EM.ID, EM.PROJECT_ID, EM.CONTACT_ID FROM c_email_checks EM
                            //WHERE EMAIL_SOURCE = '0' AND EM.DESCRIPTION IS NULL AND (EM.APPENDED_DATE IS NULL OR DATE_ADD(EM.APPENDED_DATE, INTERVAL " + GV.ibg_CheckTimeoutPerBatch +
                            //        " SECOND) > NOW()) ORDER BY RAND() LIMIT " + GV.ibg_LoadCount + ") AS B ON (A.ID = B.ID) SET A.PROCESSED_SERVER = '" + GV.sSessionID +
                            //        "', A.APPENDED_DATE = NOW(); SELECT * FROM c_email_checks WHERE DESCRIPTION IS NULL AND PROCESSED_SERVER = '" + GV.sSessionID +
                            //        "' AND (APPENDED_DATE IS NULL OR DATE_ADD(APPENDED_DATE, INTERVAL " + GV.ibg_CheckTimeoutPerBatch +
                            //        " SECOND) > NOW());";

                            string sProjectTables_Update = string.Empty;
                            try
                            {
                                using (SqlCommand cmdEmails = new SqlCommand("Exec CM..ELV '" + GV.sSessionID + "'," + GV.ibg_BatchExpiry + "," + GV.ibg_LoadCount, con1))
                                //using (MySqlCommand cmdEmails = new MySqlCommand("ELV", con1))
                                {
                                    if (con1.State != ConnectionState.Open)
                                    {
                                        con1.Open();
                                    }
                                    //cmdEmails.CommandType = CommandType.StoredProcedure;
                                    //cmdEmails.Parameters.Add(new MydfSqlParameter("serverid", GV.sSessionID));
                                    //cmdEmails.Parameters.Add(new MfdySqlParameter("inter", GV.ibg_BatchExpiry));
                                    //cmdEmails.Parameters.Add(new MydfSqlParameter("caveats", GV.ibg_LoadCount));

                                    using (SqlDataAdapter daEmails = new SqlDataAdapter(cmdEmails))
                                    {
                                        daEmails.Fill(dtEmails);
                                    }
                                    con1.Close();
                                }

                                if (dtEmails != null && dtEmails.Rows.Count > 0)
                                {
                                    dProcess_StartTime = Convert.ToDateTime(dtEmails.Rows[0]["APPENDED_DATE"]);
                                    while (dtEmails.Select("LEN(ISNULL(DESCRIPTION,'')) = 0").Length > 0)
                                    {
                                        for (int i = 0; i < dtEmails.Rows.Count; i++)
                                        {
                                            if (dtEmails.Rows[i]["DESCRIPTION"].ToString().Trim().Length == 0)
                                            {
                                                Thread.Sleep(5000);

                                                try
                                                {
                                                    WebRequest wrGETURL;
                                                    wrGETURL = WebRequest.Create(GV.sbg_API.Replace("|EmailIDString|", dtEmails.Rows[i]["Email"].ToString().Replace("\n", "")));
                                                    WebProxy myProxy = new WebProxy("myproxy", 80);
                                                    myProxy.BypassProxyOnLocal = true;
                                                    wrGETURL.Proxy             = WebProxy.GetDefaultProxy();
                                                    wrGETURL.Timeout           = GV.ibg_CheckTimeoutPerEmail;
                                                    using (Stream objStream = wrGETURL.GetResponse().GetResponseStream())
                                                    {
                                                        using (StreamReader objReader = new StreamReader(objStream))
                                                        {
                                                            string sLine     = string.Empty;
                                                            string sLineTemp = string.Empty;
                                                            while (sLineTemp != null)
                                                            {
                                                                sLineTemp = objReader.ReadLine();
                                                                if (sLineTemp != null)
                                                                {
                                                                    sLine += sLineTemp;
                                                                }
                                                            }

                                                            if (!sLine.Contains("<html>"))//Incase ELV down
                                                            {
                                                                if (sLine.Contains("|"))
                                                                {
                                                                    dtEmails.Rows[i]["DETAIL"]      = sLine.Split('|')[0].Trim();
                                                                    dtEmails.Rows[i]["DESCRIPTION"] = sLine.Split('|')[1].Trim();
                                                                }
                                                                else
                                                                {
                                                                    if (sLine.Trim().Length > 0)
                                                                    {
                                                                        dtEmails.Rows[i]["DESCRIPTION"] = sLine.Trim();
                                                                    }
                                                                    //else//Incase ELV doesn't respond any result
                                                                    //    dtEmails.Rows[i]["DESCRIPTION"] = "NEW DESCRIPTION[Invalid Result]";
                                                                }
                                                            }
                                                            else
                                                            {
                                                                Thread.Sleep(10000);
                                                            }
                                                        }
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    Thread.Sleep(10000); //Hold for a while if the Web API has to be clear out
                                                    break;               //Break the for loop and re-enter the parant while loop
                                                }
                                            }
                                        }
                                    }


                                    foreach (DataRow drEmails in dtEmails.Rows)
                                    {
                                        string sDescription = drEmails["DESCRIPTION"].ToString();
                                        string sDetails     = drEmails["DETAIL"].ToString();

                                        if (sDescription.Trim().Length > 0)
                                        {
                                            if (dtEmailStatus.Select("PicklistField = '" + sDescription.Replace("'", "''").Replace("\\", string.Empty) + "'").Length > 0)
                                            {
                                                DataRow drEmailBounce_Names = dtEmailStatus.Select("PicklistField = '" + sDescription.Replace("'", "''").Replace("\\", string.Empty) + "'")[0];
                                                string  sBounceStatus       = dtEmailStatus.Select("PicklistField = '" + sDescription.Replace("'", "''").Replace("\\", string.Empty) + "'")[0]["PicklistValue"].ToString();
                                                if (sBounceStatus == "HARD")
                                                {
                                                    sBounceStatus = "BOUNCED";
                                                }

                                                sProjectTables_Update += "UPDATE " + drEmails["PROJECT_ID"] + "_mastercontacts set EMAIL_VERIFIED = '" + sBounceStatus + "', BOUNCE_STATUS = '" + sDescription.Replace("'", "''").Replace("\\", string.Empty) +
                                                                         "', BOUNCE_LOADED_DATE = GETDATE(), BOUNCE_LOADED_BY = 'CM' WHERE CONTACT_ID_P=" + drEmails["CONTACT_ID"] + ";";

                                                //drEmails["DESCRIPTION"] = sDescription;
                                                //drEmails["DETAIL"] = sDetails;
                                                //drEmails["PROCESSED_SERVER"] = GV.sSessionID;
                                            }
                                            else
                                            {
                                                drEmails["DESCRIPTION"] = "NEW DESCRIPTION[" + sDescription + "]";
                                                //drEmails["DETAIL"] = sDetails;
                                                //drEmails["PROCESSED_SERVER"] = GV.sSessionID;
                                                //Trigger Email
                                                //sTables_Update += "UPDATE " + drEmails["PROJECT_ID"] + "_mastercontacts set EMAIL_VERIFIED = 'Category not found', BOUNCE_STATUS = '" + drrEmail[0]["statusdescription"].ToString().Replace("'", "''") + "', BOUNCE_LOADED_DATE = NOW() WHERE CONTACT_ID_P=23;";
                                            }
                                        }
                                    }

                                    if (GM.GetDateTime(true) < dProcess_StartTime.AddSeconds(GV.ibg_BatchExpiry))
                                    {
                                        using (SqlConnection con2 = new SqlConnection(GV.sMSSQL1))
                                        {
                                            using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM c_email_checks Where 1=0", con2))
                                            {
                                                using (SqlCommandBuilder cb = new SqlCommandBuilder(da))
                                                {
                                                    if (con2.State != ConnectionState.Open)
                                                    {
                                                        con2.Open();
                                                    }

                                                    cb.ConflictOption = ConflictOption.OverwriteChanges;
                                                    da.UpdateCommand  = cb.GetUpdateCommand();
                                                    da.UpdateCommand.CommandTimeout = 600;

                                                    GV.sPerformance += "Update Email Table Start:\t" + GV.PerformanceWatch.Elapsed.TotalSeconds + Environment.NewLine;
                                                    da.Update(dtEmails);
                                                    GV.sPerformance += "Update Email Table End:\t" + GV.PerformanceWatch.Elapsed.TotalSeconds + Environment.NewLine;
                                                }
                                            }

                                            if (sProjectTables_Update.Length > 0)
                                            {
                                                using (SqlCommand cmdUpdateTables = new SqlCommand(sProjectTables_Update, con2))
                                                {
                                                    if (con2.State != ConnectionState.Open)
                                                    {
                                                        con2.Open();
                                                    }
                                                    GV.sPerformance += "Update Project Table Start:\t" + GV.PerformanceWatch.Elapsed.TotalSeconds + Environment.NewLine;
                                                    cmdUpdateTables.ExecuteNonQuery();
                                                    GV.sPerformance += "Update Project Table End:\t" + GV.PerformanceWatch.Elapsed.TotalSeconds + Environment.NewLine;
                                                }
                                            }
                                            con2.Close();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //if(!ex.Message.Contains("Deadlock"))
                                GM.Error_Log(System.Reflection.MethodBase.GetCurrentMethod(), ex, true, false, sProjectTables_Update);

                                // continue;
                            }
                        }//dtEmails
                    }
                }
            }
            catch (Exception ex)
            {
                GM.Error_Log(System.Reflection.MethodBase.GetCurrentMethod(), ex, true, false);
            }
        }
コード例 #29
0
        private bool ActivatePragmaSql()
        {
            string error = String.Empty;

            /*
             * if (String.IsNullOrEmpty(cmbCodeName.Text.Trim()))
             * {
             * error += "\r\n" + " - Product code name";
             * }
             */

            if (String.IsNullOrEmpty(cmbPurchaseType.Text.Trim()))
            {
                error += "\r\n" + " - Purchase type";
            }

            if (String.IsNullOrEmpty(txtActivationKey.Text.Trim()))
            {
                error += "\r\n" + " - Activation key";
            }

            if (String.IsNullOrEmpty(txtMachineKey.Text.Trim()))
            {
                error += "\r\n" + " - Machine key";
            }

            if (!IsDemo && String.IsNullOrEmpty(txtEMail.Text.Trim()))
            {
                error += "\r\n" + " - EMail";
            }

            if (!String.IsNullOrEmpty(error))
            {
                MessageService.ShowError("Required fields listed below are empty!\r\n" + error);
                return(false);
            }


            // Create request licence object
            LicUtils      licUtils = new LicUtils();
            PragmaLicense lic      = new PragmaLicense();

            lic.Product         = Product.PragmaSQL;
            lic.ProductCodeName = new ProductInfo().CurrentCodeName;

            //lic.ProductCodeName = (ProductCodeName)licUtils.ParseEnum(typeof(ProductCodeName), cmbCodeName.Text);
            lic.PurchaseType  = (PurchaseType)licUtils.ParseEnum(typeof(PurchaseType), cmbPurchaseType.Text);
            lic.ActivationKey = txtActivationKey.Text;
            lic.MachineKey    = new MachineID(txtMachineKey.Text);
            lic.MachineIdType = MachineIdType.Composite2;
            lic.LicType       = LicType.Machine;
            lic.EMail         = txtEMail.Text;


            if (lic.PurchaseType == PurchaseType.Demo)
            {
                lic.ValidFrom = DateTime.Now;
                lic.ValidTo   = DateTime.Now.AddDays(121);
            }

            // Sign the licence request via web service
            string         licXml = lic.ToXmlString();
            LicenceSignSvc svc    = new LicenceSignSvc();

            try
            {
                WebProxy prx = WebProxy.GetDefaultProxy();
                if (prx != null)
                {
                    prx.Credentials = CredentialCache.DefaultCredentials;
                    svc.Proxy       = prx;
                }
            }
            catch (Exception ex)
            {
                frmException.ShowAppError("Default static proxy settings can not be retreived!", ex);
            }

            string signedLicXml = svc.SignLicence(licXml);

            XmlDocument signedXml = new XmlDocument();

            signedXml.LoadXml(signedLicXml);

            // Check if resulting string is an error xml
            if (ErrorXml.IsError(signedLicXml))
            {
                ServiceCallError er  = ErrorXml.CreateServiceCallError(signedXml);
                string           msg = "Product can not be activated!\r\n";
                msg += "Error:" + er.ErrorMessage;
                msg += !String.IsNullOrEmpty(er.InnerErrorMessage) ? "Detail:" + er.InnerErrorMessage : String.Empty;
                MessageService.ShowError(msg);
                return(false);
            }

            if (lic.PurchaseType == PurchaseType.Demo)
            {
                LayoutConfig dex = new LayoutConfig();
                dex.Items.Add(licUtils.GetSimpleDate(DateTime.Now));
                dex.SaveToFile();
            }

            signedXml.Save(_licFile);
            return(true);
        }
コード例 #30
0
ファイル: SerialReader.cs プロジェクト: samirajean/NFC-App
        //Transmit to Server (Allah y7r2o bl Java)
        public void Transmit(string aid, string uid)
        {
            //string dTime = DateTime.Now.ToString("HHmm");
            //string dDate = DateTime.Now.ToString("ddMMyy");
            //string dateTime = string.Concat(dTime, dDate);

            //Payload = <UID,AID> + <dTime,dDate>

            //string fullPayload = "";
            //fullPayload = string.Concat(idValues, dateTime);

            string sURL;

            sURL = "http://197.50.41.222:8084/Rms/AddLog?idSerial=" + uid + "&hwNum=" + aid;

            WebRequest wrGETURL;

            wrGETURL = WebRequest.Create(sURL);

            WebProxy myProxy = new WebProxy("myproxy", 80);

            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;

            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int    i     = 0;

            Console.WriteLine("Reading server output");
            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    Console.WriteLine("{0}:{1}", i, sLine);
                }
            }


            /* string newIDValues = String.Join(" ",
             *   idValues.ToCharArray().Aggregate("",
             *           (result, c) => result += ((!string.IsNullOrEmpty(result) &&
             *                                      (result.Length + 1) % 3 == 0) ? " " : "") + c.ToString())
             *       .Split(' ').ToList().Select(
             *           x => x.Length == 1
             *               ? String.Format("{0}{1}", Int32.Parse(x) - 1, x)
             *               : x).ToArray());*/

            //Array of Bytes Ready to the Server
            //4 or 7 bytes - NFC ID
            //2 bytes - AID

            //Removed
            //1 byte - hour
            //1 byte - min
            //1 byte - day
            //1 byte - month
            //1 byte - year
            //Total : 14 bytes

            /*byte[] bytesStream = newIDValues
             *  .Split(' ') // Split into items
             *  .Select(item => Convert.ToByte(item, 16)) // Convert each item into byte
             *  .ToArray();*/
        }