Beispiel #1
0
    public void QueueIfOnline(Action task)
    {
        lock (tasksIfOnline)
        {
            tasksIfOnline.Enqueue(task);
        }

        if(!this.checking)
        {
            // Quickly check this setting which is not accurate
            if(Application.internetReachability != NetworkReachability.NotReachable)
            {
                // Go on and make a real request to see if we can access the internet
                this.request = WebRequest.Create("http://www.google.com/");
                this.request.Method = "GET";
                this.request.Proxy = null;
                this.request.BeginGetResponse(new AsyncCallback(AsyncWebRequest), null);

                this.checking = true;
            }
            else
            {
                Debug.Log("No internet, so clearing tasks");
                this.RespondToInternetCheck(false);

                this.checking = false;
            }
        }
    }
 public async Task<WebClientStringResult> GetString(WebRequest request)
 {
     logger.Debug(string.Format("UnixLibCurlWebClient:GetString(Url:{0})", request.Url));
     var result = await Run(request);
     logger.Debug(string.Format("UnixLibCurlWebClient:GetString Returning {0} => {1}", result.Status, (result.Content == null ? "<NULL>" : Encoding.UTF8.GetString(result.Content))));
     return Mapper.Map<WebClientStringResult>(result);
 }
 public RequestState()
 {
     BufferRead = new byte[BufferSize];
     RequestData = new StringBuilder(String.Empty);
     Request = null;
     ResponseStream = null;
 }
Beispiel #4
0
 //private ->public
 public virtual void reqFinished(WebRequest req)
 {
     if (req.www.error != null) {
         Debug.LogError (" req error:" + req.dumpRequest());
     } else {
         Hashtable t = MiniJsonExtensions.hashtableFromJson (req.www.text);
         if (t == null) {
             Debug.LogError ("http call return empty");
             this.onError("Null HashTable","Null HashTable",null);
             return;
         }
         // {"protocolVersion":1,"serverTime":"2013-11-29 15:24:42,727","serverTimestamp":1385709882,"data":[{"requestId":null,"messages":{},"result":"aWeha_JMFgzaF5zWMR3tnObOtLZNPR4rO70DNdfWPvc.eyJ1c2VySWQiOiIyMCIsImV4cGlyZXMiOiIxMzg1NzA5ODgyIn0","status":0}]}
         ArrayList datas = t["data"] as ArrayList;
         if(datas == null || datas.Count != 1){
             Debug.LogError ("http call return no data");
             this.onError("Null Data","Null Data",null);
             return;
         }
         Hashtable data = datas[0] as Hashtable;
         string status = "" + data ["status"];
         Hashtable result = data["result"] as Hashtable;
         if(result == null && data["result"] is string){
             result = data;
         }
         if(result!=null)Debug.Log (Utils.dumpHashTable (result));
         if (status != "0" ) {
             Debug.LogError ("status=" + status );
             onError (status, status, result);
         } else{
             onComplete(result);
         }
     }
 }
    public void BeginProcessRequest(Site site)
    {
        string sql = "";
        int iResult = 0;
        this.Site = site;

        oDataIO = new DataIO();
        SqlConnection Conn = new SqlConnection();
        Conn = oDataIO.GetDBConnection("ProfilesDB");
        sqlCmd = new SqlCommand();
        sqlCmd.Connection = Conn;

        site.IsDone = false;
        _request = WebRequest.Create(site.URL);

        // Enter log record
        sql = "insert into FSLogOutgoing(FSID,SiteID,Details,SentDate,QueryString) "
             + " values ('" + site.FSID.ToString() + "'," + site.SiteID.ToString() + ",0,GetDate()," + cs(site.SearchPhrase) + ")";
        sqlCmd.CommandText = sql;
        sqlCmd.CommandType = System.Data.CommandType.Text;
        iResult = sqlCmd.ExecuteNonQuery();

        if (sqlCmd.Connection.State == System.Data.ConnectionState.Open)
            sqlCmd.Connection.Close();

        _request.BeginGetResponse(new AsyncCallback(EndProcessRequest), site);
    }
        /// <summary>
        /// Send a simple Post request
        /// </summary>
        /// <param name="ip">IP of client</param>
        /// <returns></returns>
        /// <remarks>Used port 80</remarks>
        public static string SendPostRequest(string ip)
        {
            WebRequest webRequest = new WebRequest(ip, "POST");
            var response = webRequest.GetResponse();

            return response;
        }
Beispiel #7
0
        public WebRequest Session()
        {
            WebRequest wr = new WebRequest();

            Scaffold scaffold = new Scaffold(R, "/app/debug/debug.html", "", new string[] { "body" });
            string jsonVs = R.Util.Str.GetString(R.Session["viewstates"]);
            string jsonUser = R.Util.Serializer.WriteObjectAsString(R.User);
            ViewStates vss = (ViewStates)R.Util.Serializer.ReadObject(jsonVs, Type.GetType("Rennder.ViewStates"));
            List<string> body = new List<string>();
            double totalLen = R.Session["viewstates"].Length;
            double len = 0;

            body.Add("<h1>User (" + (jsonUser.Length * 2) + " bytes)</h1>" + jsonUser);
            body.Add("<h1>Viewstates (" + totalLen.ToString("N0") + " bytes)</h1>" + jsonVs);

            foreach(structViewStateInfo item in vss.Views)
            {
                ViewState vssItem = (ViewState)R.Util.Serializer.ReadObject(R.Util.Str.GetString(R.Session["viewstate-" + item.id]), Type.GetType("Rennder.ViewState"));
                len = R.Session["viewstate-" + item.id].Length;
                totalLen += len;
                body.Add("<h1>Viewstate \"" + item.id + "\" (" + len.ToString("N0") + " bytes)</h1>" + R.Util.Serializer.WriteObjectAsString(vssItem));

            }

            body.Add("<h1>Total Memory Used: " + totalLen.ToString("N0") + " bytes");

            scaffold.Data["body"] = ("<pre>" + string.Join("</pre></div><div><pre>", body.ToArray()).Replace("\\\"", "\"").Replace("\\n", "").Replace("},", "},\n").Replace("],", "],\n") + "</pre>");

            //finally, scaffold debug HTML
            wr.html = scaffold.Render();
            return wr;
        }
Beispiel #8
0
        public void SendRequest(WebRequest request)
        {
            ResponseUri = request.RequestUri;

            request.Header = request.Method + " " + ResponseUri.PathAndQuery + " HTTP/1.0\r\n" + request.Headers;
            Socket.Send(Encoding.ASCII.GetBytes(request.Header));
        }
Beispiel #9
0
 public void process(WebRequest request)
 {
     Sentence sentence = "这是一个回答";
     var tags = new List<Keyword> {"测试"};
     service.answer(sentence, tags);
     request.Output.Display(new View("Install.cshtml"));
 }
Beispiel #10
0
        // Wrapper for Run which takes care of CloudFlare challenges, calls RunCurl
        override protected async Task<WebClientByteResult> Run(WebRequest request)
        {
            WebClientByteResult result = await RunCurl(request);

            // check if we've received a CloudFlare challenge
            string[] server;
            if (result.Status == HttpStatusCode.ServiceUnavailable && result.Headers.TryGetValue("server", out server) && server[0] == "cloudflare-nginx")
            {
                logger.Info("UnixLibCurlWebClient: Received a new CloudFlare challenge");

                // solve the challenge
                string pageContent = Encoding.UTF8.GetString(result.Content);
                Uri uri = new Uri(request.Url);
                string clearanceUri = CloudFlareChallengeSolverSolve(pageContent, uri);
                logger.Info(string.Format("UnixLibCurlWebClient: CloudFlare clearanceUri: {0}", clearanceUri));

                // wait...
                await Task.Delay(5000);

                // request clearanceUri to get cf_clearance cookie
                var response = await CurlHelper.GetAsync(clearanceUri, request.Cookies, request.Referer);
                logger.Info(string.Format("UnixLibCurlWebClient: received CloudFlare clearance cookie: {0}", response.Cookies));

                // add new cf_clearance cookies to the original request
                request.Cookies = response.Cookies + request.Cookies;

                // re-run the original request with updated cf_clearance cookie
                result = await RunCurl(request);

                // add cf_clearance cookie to the final result so we update the config for the next request
                result.Cookies = response.Cookies + " " + result.Cookies;
            }
            return result;
        }
 public bool can_process(WebRequest request)
 {
     var request_and_query = request.Input.RequestPath.Split('?');
     var request_list = request_and_query[0].Split('/');
     var request_last = request_list[request_list.Length-1];
     return command_name + suffix==request_last;
 }
        public override void ProcessRequest(WebRequest request)
        {
            System.IO.FileInfo info = null;
            if (!String.IsNullOrEmpty(Terraria.Main.worldPathName))
            {
                info = new System.IO.FileInfo(Terraria.Main.worldPathName);
            }

            request.Writer.Buffer(Terraria.Main.worldName ?? String.Empty);
            request.Writer.Buffer(Terraria.Main.maxTilesX);
            request.Writer.Buffer(Terraria.Main.maxTilesY);

            if (info != null && info.Exists)
            {
                request.Writer.Buffer(info.Length);
            }
            else
            {
                request.Writer.Buffer(0L);
            }

            request.Writer.Buffer(Heartbeat.Enabled);
            request.Writer.Buffer(Heartbeat.ServerName);
            request.Writer.Buffer(Heartbeat.ServerDescription);
            request.Writer.Buffer(Heartbeat.ServerDomain);
            request.Writer.Buffer(Heartbeat.PublishToList);

            request.WriteOut();
        }
    void FixedUpdate()
    {
        Debug.Log("sending HTTP request! to:");
            Debug.Log(url);
            mycoord = WebRequest.Create(url);
            Stream objStream;
            objStream = mycoord.GetResponse().GetResponseStream();
        StreamReader objReader = new StreamReader(objStream);

            sLine = objReader.ReadLine ();
            Debug.Log("Got response!");
            if(sLine.Length > 4) {
                coordinates = sLine;
            }

        Debug.Log(coordinates);

        int x = System.Convert.ToInt32 (coordinates [1]);
        int y = System.Convert.ToInt32 (coordinates [3]);
        float newX = 0 + (x * 2);
        newX -= 96; //for some reason unity jumps my cardboard main to 96,-96
        float newZ = 0 - (y * 2);
        newZ += 96;
        transform.position = new Vector3(newX, 1.5f,newZ);
    }
Beispiel #14
0
		static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials)
		{
			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null || credentials == null)
				return null;

			NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			if (userName == null || userName == "")
				return null;

			string password = cred.Password;
			string domain = cred.Domain;
			byte [] bytes;

			// If domain is set, MS sends "domain\user:password". 
			if (string.IsNullOrWhiteSpace(domain))
				bytes = GetBytes (userName + ":" + password);
			else
				bytes = GetBytes (domain + "\\" + userName + ":" + password);

			string auth = "Basic " + Convert.ToBase64String (bytes);
			return new Authorization (auth);
		}
Beispiel #15
0
        // Make an Api request
        public static string Request(string action, Dictionary<string, string> parameters = null)
        {
            // Build the url
            string destination = puushHome + "api/" + action;

            // Create request
            WebRequest req = new WebRequest();

            // Set the desination
            req.Destination(destination);

            // Create post content
            HttpContent content = new FormUrlEncodedContent(parameters);

            // Call the get request
            req.Post(content);

            // Wait for Response to be populated
            while (req.Response == null)
            {
            }

            // Return the response
            return req.Response;
        }
 /// <summary>
 /// Gets the response and modify the headers.
 /// </summary>
 /// <returns>The response.</returns>
 /// <param name="request">Request.</param>
 public override WebResponse getResponse(WebRequest request)
 {
     WebResponse response = base.getResponse(request);
     //
     // Only if Url matches
     //
     if (request.getUrl().toExternalForm().Contains("com")) {
         string content = response.getContentAsString("UTF-8");
         java.util.ArrayList newheaders = new java.util.ArrayList();
         java.util.List headers = response.getResponseHeaders();
         java.util.Iterator it = headers.iterator();
         //
         // Remove the 'Access-Control-Allow-Origin' header
         //
         while (it.hasNext()) {
             com.gargoylesoftware.htmlunit.util.NameValuePair o = (com.gargoylesoftware.htmlunit.util.NameValuePair)it.next();
             if (o.getName().Equals("Access-Control-Allow-Origin")) {
                 string value = response.getResponseHeaderValue("Access-Control-Allow-Origin");
                 Console.WriteLine("Found header 'Access-Control-Allow-Origin' = \"{0}\" and stripping it from new headers for response", value);
                 continue; //headers.remove(o);
             }
             newheaders.add(o);
         }
         byte[] utf = System.Text.Encoding.UTF8.GetBytes(content);
         WebResponseData data = new WebResponseData(utf,
             response.getStatusCode(), response.getStatusMessage(), newheaders);
         response = new WebResponse(data, request, response.getLoadTime());
         return response;
     }
     return response;
 }
        //TODO simple JSON writer
        //struct Info
        //{
        //    public string Provider { get; set; }
        //}
        public override void ProcessRequest(WebRequest request)
        {
            //We don't need a list here, but I rather get away from the lock quicker.
            var dependencies = new System.Collections.Generic.List<ResourceDependancy>();
            WebServer.ForEachPage((page) =>
            {
                var dpd = page.GetDependencies();
                if (dpd != null)
                {
                    dependencies.AddRange(dpd);
                }
            });

            //Since we are using a list we can make it a bit easier
            request.Writer.Buffer(dependencies.Count);

            foreach (var item in dependencies)
            {
                request.Writer.Buffer((byte)item.Type);
                request.Writer.Buffer(item.Url);
            }

            dependencies.Clear();
            dependencies = null;

            request.WriteOut("application/octet-stream");
        }
Beispiel #18
0
 public async Task<WebClientByteResult> GetBytes(WebRequest request)
 {
     logger.Debug(string.Format("UnixLibCurlWebClient:GetBytes(Url:{0})", request.Url));
     var result = await Run(request);
     logger.Debug(string.Format("UnixLibCurlWebClient:GetBytes Returning {0} => {1} bytes", result.Status, (result.Content == null ? "<NULL>" : result.Content.Length.ToString())));
     return result;
 }
        public WebRequest CreateFrom(HttpContext context)
        {
            var webrequest = new WebRequest();
            webrequest.RequestedUrl = context.Request.Url.ToString();
            webrequest.QueryArguments = context.Request.QueryString;

            return webrequest;
        }
Beispiel #20
0
        public void Connect(WebRequest request)
        {
            ResponseUri = request.RequestUri;

            Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEP = new IPEndPoint(Dns.GetHostEntry(ResponseUri.Host).AddressList[0], ResponseUri.Port);
            Socket.Connect(remoteEP);
        }
        public void Process(WebRequest webRequest)
        {
            //Get the request parameter
            int id = Convert.ToInt32(webRequest.QueryArguments.GetValues("packageID")[0]);

            //Get the specific Package from the repository
            _storage.Add(ViewStorageKeys.Package, _repository.GetByPackageId(id));
            _pageNavigator.NavigateTo(PageDirectory.Package);
        }
        //TODO simple JSON writer
        //struct Info
        //{
        //    public string Provider { get; set; }
        //}
        public override void ProcessRequest(WebRequest request)
        {
            request.StatusCode = 200;
            request.RepsondHeader(200, "OK", "application/octet-stream", 1);

            request.Send(request.AuthenticatedAs != null);

            request.End();
        }
Beispiel #23
0
 public static WebRequest GenerateRequest(string batch)
 {
     Dictionary<string,string> d = new Dictionary<string, string>();
     d.Add("batch",batch);
     WebRequest req = new WebRequest();
     req.seq = g_seq++;
     req.param = d;
     return req;
 }
 public bool CheckValidationResult(
       ServicePoint srvPoint
     , X509Certificate certificate
     , WebRequest request
     , int certificateProblem)
 {
     //Return True to force the certificate to be accepted.
     return true;
 }
    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);

        var thisResponse = response as HttpWebResponse;
        this.CookieContainer.Add(thisResponse.Cookies);

        return response;
    }
        public string Authenticate(WebRequest request)
        {
            //username=MD5(HA1:nonce:HA2),realm
            //Initially I was thinking we could simply use the hash as the KEY, and the username as the VALUE.
            //But i rather have the user being asked for and then compare, rather that matching on ALL user hashs and using whatever username was found.
            //The odds are small, but I have no justification for it as of yet so I am sticking with the username key.
            if (request.Headers.ContainsKey("Auth"))
            {
                var auth = request.Headers["Auth"];
                var split = auth.Split('=');
                if (split.Length == 2)
                {
                    var username = split[0];
                    split = split[1].Split(',');
                    if (split.Length == 2 && split[0].Length == 32)
                    {
                        var hash = split[0];
                        var realm = split[1];

                        if (realm == WebServer.ProviderName)
                        {
                            var key = request.IPAddress + '+' + username;
                            var ha1 = _database.Find(username);
                            if (_lastNonceLookup.ContainsKey(key) && ha1 != null)
                            {
                                var servernonce = _lastNonceLookup[key];
                                var ha2 = ComputeHash("auth:" + request.Path);
                                var serverHash = ComputeHash(ha1 + ':' + servernonce + ':' + ha2);

                                if (serverHash == hash)
                                {
                                    //Push out the new nonce
                                    var nextnonce = Guid.NewGuid().ToString();
                                    _lastNonceLookup[key] = nextnonce;
                                    request.ResponseHeaders.Add("next-nonce", nextnonce);

                                    return username;
                                }
                            }
                            else
                            {
                                //No user exists, so give the request a new nonce and let them revalidate
                                var nextnonce = Guid.NewGuid().ToString();
                                _lastNonceLookup.Add(key, nextnonce);
                                request.ResponseHeaders.Add("next-nonce", nextnonce);

                                request.RepsondHeader(403, "OK", "text/hml", 0);
                                request.End();
                            }
                        }
                    }
                }
            }

            return null;
        }
Beispiel #27
0
		public bool IsAllowed (WebRequest request)
		{
			ex = security_exception;

			foreach (string header in request.Headers) {
				if (String.Compare ("Content-Type", header, StringComparison.OrdinalIgnoreCase) != 0)
					ex = not_supported_exception;
			}
			return false;
		}
Beispiel #28
0
 private string ReadResponse(WebRequest request)
 {
     using (var responseStream = request.GetResponse().GetResponseStream())
     {
         using (var respReader = new StreamReader(responseStream))
         {
             return respReader.ReadLine();
         }
     }
 }
Beispiel #29
0
 //private ->public
 public override void reqFinished(WebRequest req)
 {
     if (req.www.error != null) {
         Debug.LogError (" req error:" + req.dumpRequest());
     } else {
         Hashtable h = new Hashtable();
         h.Add("text",req.www.text);
         onComplete(h);
     }
 }
        /// <summary>
        /// Returns a clone of the object.
        /// </summary>
        /// <param name="request"> The session scripting.</param>
        /// <returns> A clone of the object.</returns>
        public static object Clone(WebRequest request)
        {
            if ( ser == null )
            {
                RequestSerializer _ser = new RequestSerializer();
            }

            XmlNode node = ser.WriteXmlNode(typeof(WebRequest), request, "WebRequest");
            XmlNode clone = node.Clone();
            return ser.ReadXmlNode(typeof(WebRequest), clone, "WebRequest");
        }
Beispiel #31
0
        static void CheckMD5(IProgressReporterDialogue frmProgressReporter, string md5url, string baseurl)
        {
            log.InfoFormat("get checksums {0} - base {1}", md5url, baseurl);

            string responseFromServer = "";

            WebRequest request = WebRequest.Create(md5url);

            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the response.
            // Get the stream containing content returned by the server.
            // Open the stream using a StreamReader for easy access.
            using (WebResponse response = request.GetResponse())
                using (Stream dataStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        // Display the status.
                        log.Info(((HttpWebResponse)response).StatusDescription);
                        // Read the content.
                        responseFromServer = reader.ReadToEnd();
                    }

            Regex regex = new Regex(@"([^\s]+)\s+[^/]+/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                if (frmProgressReporter != null)
                {
                    frmProgressReporter.UpdateProgressAndStatus(-1, "Hashing Files");
                }

                // cleanup dll's with the same exe name
                var           dlls  = Directory.GetFiles(Settings.GetRunningDirectory(), "*.dll", SearchOption.TopDirectoryOnly);
                var           exes  = Directory.GetFiles(Settings.GetRunningDirectory(), "*.exe", SearchOption.TopDirectoryOnly);
                List <string> files = new List <string>();

                // hash everything
                MatchCollection matchs = regex.Matches(responseFromServer);
                for (int i = 0; i < matchs.Count; i++)
                {
                    string hash = matchs[i].Groups[1].Value.ToString();
                    string file = matchs[i].Groups[2].Value.ToString();

                    files.Add(file);
                }

                // cleanup unused dlls and exes
                dlls.ForEach(dll =>
                {
                    try
                    {
                        var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(dll.ToLower()));

                        if (result == false)
                        {
                            File.Delete(dll);
                        }
                    }
                    catch { }
                });

                exes.ForEach(exe =>
                {
                    try
                    {
                        var result = files.Any(task => Path.Combine(Settings.GetRunningDirectory(), task).ToLower().Equals(exe.ToLower()));

                        if (result == false)
                        {
                            File.Delete(exe);
                        }
                    }
                    catch { }
                });

                // background md5
                List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >();

                for (int i = 0; i < matchs.Count; i++)
                {
                    string hash = matchs[i].Groups[1].Value.ToString();
                    string file = matchs[i].Groups[2].Value.ToString();

                    Task <bool> ismatch = Task <bool> .Factory.StartNew(() => MD5File(file, hash));

                    tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch));
                }
                // get count and wait for all hashing to be done
                int count = tasklist.Count(a =>
                {
                    a.Item3.Wait();
                    return(!a.Item3.Result);
                });

                // parallel download
                ParallelOptions opt = new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 3
                };

                int done = 0;

                Parallel.ForEach(tasklist, opt, task =>
                                 //foreach (var task in tasklist)
                {
                    string file = task.Item1;
                    string hash = task.Item2;
                    // check if existing matchs hash
                    task.Item3.Wait();
                    bool match = task.Item3.Result;

                    if (!match)
                    {
                        done++;
                        log.Info("Newer File " + file);

                        if (frmProgressReporter != null && frmProgressReporter.doWorkArgs.CancelRequested)
                        {
                            frmProgressReporter.doWorkArgs.CancelAcknowledged = true;
                            throw new Exception("User Request");
                        }

                        // check is we have already downloaded and matchs hash
                        if (!MD5File(file + ".new", hash))
                        {
                            if (frmProgressReporter != null)
                            {
                                frmProgressReporter.UpdateProgressAndStatus((int)((done / (double)count) * 100),
                                                                            Strings.Getting + file + "\n" + done + " of " + count + " of total " +
                                                                            tasklist.Count);
                            }

                            string subdir = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar;

                            subdir = subdir.Replace("" + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar,
                                                    "" + Path.DirectorySeparatorChar);

                            if (baseurl.ToLower().Contains(".zip"))
                            {
                                GetNewFileZip(frmProgressReporter, baseurl, subdir,
                                              Path.GetFileName(file));
                            }
                            else
                            {
                                GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir,
                                           Path.GetFileName(file));
                            }

                            // check the new downloaded file matchs hash
                            if (!MD5File(file + ".new", hash))
                            {
                                throw new Exception("File downloaded does not match hash: " + file);
                            }
                        }
                        else
                        {
                            log.Info("already got new File " + file);
                        }
                    }
                    else
                    {
                        log.Info("Same File " + file);

                        if (frmProgressReporter != null)
                        {
                            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Checking + file);
                        }
                    }
                });
            }
        }
Beispiel #32
0
        static void Main(string[] args)
        {
            Console.WriteLine("Application starting...");

            // Define boundary:
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            // Web Request:
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(_Url);

            wr.Headers.Clear();

            // Method and headers:
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method      = "POST";
            wr.KeepAlive   = true;

            // Basic auth:
            string login       = _APIKey + ":X"; // It could be your username:password also.
            string credentials = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(login));

            wr.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;

            // Body:
            using (var rs = wr.GetRequestStream())
            {
                // Email:
                writeBoundaryBytes(rs, boundary, false);
                writeContentDispositionFormDataHeader(rs, "email");
                writeString(rs, "*****@*****.**");
                writeCRLF(rs);

                // Subject:
                writeBoundaryBytes(rs, boundary, false);
                writeContentDispositionFormDataHeader(rs, "subject");
                writeString(rs, "Ticket Title");
                writeCRLF(rs);

                // Description:
                writeBoundaryBytes(rs, boundary, false);
                writeContentDispositionFormDataHeader(rs, "description");
                writeString(rs, "Ticket description.");
                writeCRLF(rs);

                // Status:
                writeBoundaryBytes(rs, boundary, false);
                writeContentDispositionFormDataHeader(rs, "status");
                writeString(rs, "2");
                writeCRLF(rs);

                // Priority:
                writeBoundaryBytes(rs, boundary, false);
                writeContentDispositionFormDataHeader(rs, "priority");
                writeString(rs, "2");
                writeCRLF(rs);

                // Attachment:
                writeBoundaryBytes(rs, boundary, false);
                writeContentDispositionFileHeader(rs, "attachments[]", "x.txt", "text/plain");
                FileStream fs   = new FileStream("/path/to/my/file.txt", FileMode.Open, FileAccess.Read);
                byte[]     data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                fs.Close();
                rs.Write(data, 0, data.Length);
                writeCRLF(rs);

                // End marker:
                writeBoundaryBytes(rs, boundary, true);

                rs.Close();

                // Response processing:
                try
                {
                    Console.WriteLine("Submitting Request");
                    var    response  = (HttpWebResponse)wr.GetResponse();
                    Stream resStream = response.GetResponseStream();
                    string Response  = new StreamReader(resStream, Encoding.ASCII).ReadToEnd();
                    //return status code
                    Console.WriteLine("Status Code: {1} {0}", ((HttpWebResponse)response).StatusCode, (int)((HttpWebResponse)response).StatusCode);
                    //return location header
                    Console.WriteLine("Location: {0}", response.Headers["Location"]);
                    //return the response
                    Console.Out.WriteLine(Response);
                }
                catch (WebException ex)
                {
                    Console.WriteLine("API Error: Your request is not successful. If you are not able to debug this error properly, mail us at [email protected] with the follwing X-Request-Id");
                    Console.WriteLine("X-Request-Id: {0}", ex.Response.Headers["X-Request-Id"]);
                    Console.WriteLine("Error Status Code : {1} {0}", ((HttpWebResponse)ex.Response).StatusCode, (int)((HttpWebResponse)ex.Response).StatusCode);
                    using (var stream = ex.Response.GetResponseStream())
                        using (var reader = new StreamReader(stream))
                        {
                            Console.Write("Error Response: ");
                            Console.WriteLine(reader.ReadToEnd());
                        }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERROR");
                    Console.WriteLine(ex.Message);
                }
            }
        }
Beispiel #33
0
        public static void CheckForUpdate(bool NotifyNoUpdate = false)
        {
            if (Program.WindowsStoreApp)
            {
                return;
            }

            var baseurl = ConfigurationManager.AppSettings["UpdateLocationVersion"];

            if (dobeta)
            {
                baseurl = ConfigurationManager.AppSettings["BetaUpdateLocationVersion"];
            }

            if (baseurl == "")
            {
                return;
            }

            string path = Path.GetDirectoryName(Application.ExecutablePath);

            path = path + Path.DirectorySeparatorChar + "version.txt";

            ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(
                    (sender, certificate, chain, policyErrors) => { return(true); });

            log.Debug(path);

            // Create a request using a URL that can receive a post.
            string requestUriString = baseurl;

            log.Info("Checking for update at: " + requestUriString);
            var webRequest = WebRequest.Create(requestUriString);

            webRequest.Timeout = 5000;

            // Set the Method property of the request to POST.
            webRequest.Method = "GET";

            // ((HttpWebRequest)webRequest).IfModifiedSince = File.GetLastWriteTimeUtc(path);

            bool updateFound = false;

            // Get the response.
            using (var response = webRequest.GetResponse())
            {
                // Display the status.
                log.Debug("Response status: " + ((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.

                if (File.Exists(path))
                {
                    var fi = new FileInfo(path);

                    Version LocalVersion = new Version();
                    Version WebVersion   = new Version();

                    if (File.Exists(path))
                    {
                        using (Stream fs = File.OpenRead(path))
                        {
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                LocalVersion = new Version(sr.ReadLine());
                            }
                        }
                    }

                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        WebVersion = new Version(sr.ReadLine());
                    }

                    log.Info("New file Check: local " + LocalVersion + " vs Remote " + WebVersion);

                    if (LocalVersion < WebVersion)
                    {
                        updateFound = true;
                    }
                }
                else
                {
                    updateFound = true;
                    log.Info("File does not exist: Getting " + path);
                    // get it
                }
            }

            if (updateFound)
            {
                // do the update in the main thread
                MainV2.instance.Invoke((MethodInvoker) delegate
                {
                    string extra = "";

                    if (dobeta)
                    {
                        extra = "BETA ";
                    }

                    var dr = CustomMessageBox.Show(
                        extra + Strings.UpdateFound + " [link;" + baseurl.Replace("version.txt", "ChangeLog.txt") + ";ChangeLog]",
                        Strings.UpdateNow, MessageBoxButtons.YesNo);

                    if (dr == (int)DialogResult.Yes)
                    {
                        DoUpdate();
                    }
                    else
                    {
                        return;
                    }
                });
            }
            else if (NotifyNoUpdate)
            {
                CustomMessageBox.Show(Strings.UpdateNotFound);
            }
        }
Beispiel #34
0
 public StopVisit()
 {
     log.InfoFormat("RouteAccept WebRequest server {0}", ConfigurationSettings.AppSettings["MPKServer"]);
     myWebRequestMPK         = (HttpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings["MPKServer"]);
     myWebRequestMPK.Timeout = 10000;
 }
Beispiel #35
0
        bool Crawl(SgmlDtd dtd, XmlDocument doc, TextWriter log) {
            depth++;
            StringBuilder indent = new StringBuilder();
            for (int i = 0; i < depth; i++)
                indent.Append(" ");
      
            count++;
            Uri baseUri = new Uri(doc.BaseURI);
            XmlElement baseElmt = (XmlElement)doc.SelectSingleNode("/html/head/base");
            if (baseElmt != null) {
                string href = baseElmt.GetAttribute("href");
                if (href != "") {
                    try {
                        baseUri = new Uri(href);
                    }
                    catch (Exception ) {
                        Console.WriteLine("### Error parsing BASE href '"+href+"'");
                    }
                }
            }
            foreach (XmlElement a in doc.SelectNodes("//a")) {
                string href = a.GetAttribute("href");
                if (href != "" && href != null && depth<5) {
                    Uri local = new Uri(baseUri, href);
                    if (domain && baseUri.Host != local.Host)
                        continue;
                    string ext = Path.GetExtension(local.AbsolutePath).ToLower();
                    if (ext == ".jpg" || ext == ".gif" || ext==".mpg")
                        continue;
                    string url = local.AbsoluteUri;
                    if (!visited.ContainsKey(url)) {
                        visited.Add(url, url);
                        log.WriteLine(indent+"Loading '"+url+"'");
                        log.Flush();
                        StreamReader stm = null;
                        try {
                            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
                            wr.Timeout = 10000; 
                            if (proxy != null) wr.Proxy = new WebProxy(proxy);
                            wr.PreAuthenticate = false; 
                            // Pass the credentials of the process. 
                            wr.Credentials = CredentialCache.DefaultCredentials; 

                            WebResponse resp = wr.GetResponse();
                            Uri actual = resp.ResponseUri;
                            if (actual.AbsoluteUri != url) {
                                local = new Uri(actual.AbsoluteUri);
                                log.WriteLine(indent+"Redirected to '"+actual.AbsoluteUri+"'");
                                log.Flush();
                            }           
                            if (resp.ContentType != "text/html") {
                                log.WriteLine(indent+"Skipping ContentType="+resp.ContentType);
                                log.Flush();
                                resp.Close();
                            } 
                            else {
                                stm = new StreamReader(resp.GetResponseStream());
                            }
                        } 
                        catch (Exception e) {
                            log.WriteLine(indent+"### Error opening URL: " + e.Message);
                            log.Flush();
                        }
                        if (stm != null) {
                            SgmlReader reader = new SgmlReader();
                            reader.Dtd = dtd;
                            reader.SetBaseUri(local.AbsoluteUri);
                            reader.InputStream = stm;
                            reader.WebProxy = proxy;

                            XmlDocument d2 = new XmlDocument();
                            d2.XmlResolver = null; // don't do any downloads!
                            try {
                                d2.Load(reader);
                                reader.Close();
                                stm.Close();
                                if (!Crawl(dtd, d2, log))
                                    return false;
                            } 
                            catch (Exception e) {
                                log.WriteLine(indent+"### Error parsing document '"+local.AbsoluteUri+"', "+e.Message);
                                log.Flush();
                                reader.Close();
                            }
                        }
                    }
                }
            }
            depth--;
            return true;
        }
Beispiel #36
0
        private UpnpNatDeviceInfo BuildUpnpNatDeviceInfo(IPAddress localAddress, Uri location)
        {
            NatDiscoverer.TraceSource.LogInfo("Found device at: {0}", location.ToString());

            var hostEndPoint = new IPEndPoint(IPAddress.Parse(location.Host), location.Port);

            WebResponse response = null;

            try
            {
                var request = WebRequest.CreateHttp(location);
                request.Headers.Add("ACCEPT-LANGUAGE", "en");
                request.Method = "GET";

                response = request.GetResponse();

                var httpresponse = response as HttpWebResponse;

                if (httpresponse != null && httpresponse.StatusCode != HttpStatusCode.OK)
                {
                    var message = string.Format("Couldn't get services list: {0} {1}", httpresponse.StatusCode, httpresponse.StatusDescription);
                    throw new Exception(message);
                }

                var xmldoc = ReadXmlResponse(response);

                NatDiscoverer.TraceSource.LogInfo("{0}: Parsed services list", hostEndPoint);

                var ns = new XmlNamespaceManager(xmldoc.NameTable);
                ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0");
                var services = xmldoc.SelectNodes("//ns:service", ns);

                foreach (XmlNode service in services)
                {
                    var serviceType = service.GetXmlElementText("serviceType");
                    if (!IsValidControllerService(serviceType))
                    {
                        continue;
                    }

                    NatDiscoverer.TraceSource.LogInfo("{0}: Found service: {1}", hostEndPoint, serviceType);

                    var serviceControlUrl = service.GetXmlElementText("controlURL");
                    NatDiscoverer.TraceSource.LogInfo("{0}: Found upnp service at: {1}", hostEndPoint, serviceControlUrl);

                    NatDiscoverer.TraceSource.LogInfo("{0}: Handshake Complete", hostEndPoint);
                    return(new UpnpNatDeviceInfo(localAddress, location, serviceControlUrl, serviceType));
                }

                throw new Exception("No valid control service was found in the service descriptor document");
            }
            catch (WebException ex)
            {
                // Just drop the connection, FIXME: Should i retry?
                NatDiscoverer.TraceSource.LogError("{0}: Device denied the connection attempt: {1}", hostEndPoint, ex);
                var inner = ex.InnerException as SocketException;
                if (inner != null)
                {
                    NatDiscoverer.TraceSource.LogError("{0}: ErrorCode:{1}", hostEndPoint, inner.ErrorCode);
                    NatDiscoverer.TraceSource.LogError("Go to http://msdn.microsoft.com/en-us/library/system.net.sockets.socketerror.aspx");
                    NatDiscoverer.TraceSource.LogError("Usually this happens. Try resetting the device and try again. If you are in a VPN, disconnect and try again.");
                }
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
        public ActionResult CharacterEdit(int CharacterID, int Class)
        {
            string classString = Class.ToString();

            HttpWebRequest dndApiRequest = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/classes/{classString}");

            dndApiRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse dndApiResponse = (HttpWebResponse)dndApiRequest.GetResponse();

            if (dndApiResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(dndApiResponse.GetResponseStream());

                string data = responseData.ReadToEnd();

                JObject jsonClasses = JObject.Parse(data);
                int     size        = jsonClasses["proficiency_choices"].Count();
                ViewBag.HitDieSize = jsonClasses["hit_die"];
                ViewBag.Name       = jsonClasses["name"];
                ViewBag.Classes    = jsonClasses["proficiency_choices"][size - 1];

                ViewBag.Choose = jsonClasses["proficiency_choices"][size - 1]["choose"];
                ViewBag.Pro    = jsonClasses["proficiencies"];
                ViewBag.Saves  = jsonClasses["saving_throws"];
            }

            HttpWebRequest dndRaceApiRequest = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/races");

            dndRaceApiRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse dndRaceApiResponse = (HttpWebResponse)dndRaceApiRequest.GetResponse();

            if (dndRaceApiResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(dndRaceApiResponse.GetResponseStream());

                string data = responseData.ReadToEnd();

                JObject jsonRaces = JObject.Parse(data);

                ViewBag.Races = jsonRaces["results"];
            }

            HttpWebRequest spellApiRequest0 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/0");

            spellApiRequest0.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellApiResponse0 = (HttpWebResponse)spellApiRequest0.GetResponse();

            if (spellApiResponse0.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellApiResponse0.GetResponseStream());

                string cantrips = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(cantrips);

                ViewBag.Cantrips = jsonSpells["results"];
            }

            HttpWebRequest spellAPIRequest1 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/1");

            spellAPIRequest1.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse1 = (HttpWebResponse)spellAPIRequest1.GetResponse();

            if (spellAPIresponse1.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse1.GetResponseStream());

                string Spells1 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells1);

                ViewBag.Spells1 = jsonSpells["results"];
            }

            HttpWebRequest spellAPIRequest2 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/2");

            spellAPIRequest2.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse2 = (HttpWebResponse)spellAPIRequest2.GetResponse();

            if (spellAPIresponse2.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse2.GetResponseStream());

                string Spells2 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells2);

                ViewBag.Spells2 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest3 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/3");

            spellAPIRequest3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse3 = (HttpWebResponse)spellAPIRequest3.GetResponse();

            if (spellAPIresponse3.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse3.GetResponseStream());

                string Spells3 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells3);

                ViewBag.Spells3 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest4 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/4");

            spellAPIRequest4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse4 = (HttpWebResponse)spellAPIRequest4.GetResponse();

            if (spellAPIresponse4.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse4.GetResponseStream());

                string Spells4 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells4);

                ViewBag.Spells4 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest5 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/5");

            spellAPIRequest5.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse5 = (HttpWebResponse)spellAPIRequest5.GetResponse();

            if (spellAPIresponse5.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse5.GetResponseStream());

                string Spells5 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells5);

                ViewBag.Spells5 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest6 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/6");

            spellAPIRequest6.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse6 = (HttpWebResponse)spellAPIRequest6.GetResponse();

            if (spellAPIresponse6.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse6.GetResponseStream());

                string Spells6 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells6);

                ViewBag.Spells6 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest7 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/7");

            spellAPIRequest7.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse7 = (HttpWebResponse)spellAPIRequest7.GetResponse();

            if (spellAPIresponse1.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse7.GetResponseStream());

                string Spells7 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells7);

                ViewBag.Spells7 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest8 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/8");

            spellAPIRequest8.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse8 = (HttpWebResponse)spellAPIRequest8.GetResponse();

            if (spellAPIresponse8.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse8.GetResponseStream());

                string Spells8 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells8);

                ViewBag.Spells8 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest9 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/9");

            spellAPIRequest9.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse9 = (HttpWebResponse)spellAPIRequest9.GetResponse();

            if (spellAPIresponse9.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse9.GetResponseStream());

                string Spells9 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells9);

                ViewBag.Spells9 = jsonSpells["results"];
            }

            viewbagofholdingEntities ORM = new viewbagofholdingEntities();

            Character characterToEdit = ORM.Characters.Find(CharacterID);

            if (User.Identity.IsAuthenticated)
            {
                ViewBag.User = User.Identity.GetUserId();
                string userid = User.Identity.GetUserId();
                if (characterToEdit.UserID != userid)
                {
                    return(RedirectToAction("ViewCharacter", new { CharacterID }));
                }
            }

            ViewBag.CharacterData = characterToEdit;

            return(View());
        }
Beispiel #38
0
        private static void Main(string[] args)
        {
            if (DateTime.Now.Year < 2016)
            {
                Console.WriteLine("F**K YOU THE CLOCK IS WRONG.");
                return;
            }

            DBConnection = new NpgsqlConnection(
                Registry.GetValue(@"HKEY_CURRENT_USER\Software\MindMap", "PostgreInitString", null).ToString());
   // "mindmap;Server=mmdb2.ckihnq6kjyi9.us-west-2.rds.amazonaws.com;Port=5432;User Id=postgres;Password=shannonshannon;");
            //             "Database=mindmap;Server=127.0.0.1;Port=5432;User Id=postgres;Password=pwd;");

            DBConnection.Open();

            bool fLoopin = true;
            while (fLoopin)
            {
                int today = DateTime.Now.Subtract(TwoK).Days;

                // give me 1,000 names. 
                string sQ = string.Format(
                    "select name, postsperyear, sampleday, offline_last_detected_on from nameidmap where sampleday < {0} order by sampleday asc limit 1000 ;", today - 60);
                NpgsqlCommand command = new NpgsqlCommand(sQ, DBConnection);
                command.CommandTimeout = 0;
                NpgsqlDataReader reader = command.ExecuteReader();
                List<string> list = new List<string>();
                fLoopin = false;
                while (reader.Read())
                {
                    fLoopin = true; // we have more os we loop more.
                    // that's mobile lj!
                    if (reader.GetString(0).ToUpper() == "M") continue;
                    if (reader.GetString(0).ToUpper() == "POST") continue;
                    if (reader.GetString(0).ToUpper() == "SMTP") continue;
                    if (reader.GetString(0).ToUpper() == "COM") continue;
                    if (reader.GetString(0).ToUpper() == "MAIL") continue;
                    if (reader.GetString(0).ToUpper() == "DASHBOARD") continue;
                    if (reader.GetString(0).ToUpper() == "ROADSPARKLES") continue;
                    if (reader.GetString(0).ToUpper() == "MY") continue;
                    if (reader.GetString(0).ToUpper() == "STATUS___") continue;
                    if (reader.GetString(0).ToUpper() == "FILES") continue;


                    // we know the set we're considering has not been sampled within 60 days.
                    // zero ppy is our only best indicator of inactive accout.
                    // so if the ppy is not zero, OR if it's zero but our last sample was over a year ago,
                    // then we wanna re-sample.
                    bool fAdd = false;
                    // so long as you have a nonzero ppy, you're in if we've never sensed that you're offline, or if that sense was more than a year ago
                    // ppy is -1 by default, which is non-zero.
                    if (reader.GetInt16(1) != 0 && reader.IsDBNull(3))
                        fAdd = true;

                    // you're in if i haven't heard from you in a year (or ever)
                    if (reader.GetInt16(2) < (today - 365))
                        fAdd = true;

                    if (fAdd)
                    {
                        list.Add(reader.GetString(0));
                    }
                }
                reader.Close();

                Console.WriteLine("I'd really like to foaf this many users: " + list.Count);

                foreach (string name in list)
                {
                    today = DateTime.Now.Subtract(TwoK).Days;
                    NpgsqlCommand command2 = new NpgsqlCommand(string.Format("select sampleday, numposts from nameidmap where name='{0}'", name), DBConnection);

                    TRY_DB_AGAIN:
                    NpgsqlDataReader reader2 = null;
                    try {
                        reader2 = command2.ExecuteReader();
                    }
                    catch (Exception)
                    {
                        goto TRY_DB_AGAIN;
                    }
                    reader2.Read();
                    int dayOfLastSample = reader2.GetInt16(0);
                    int numPostsAtLastSample = reader2.GetInt32(1);
                    reader2.Close();
                    string uri = string.Format("http://www.livejournal.com/users/{0}/data/foaf", name);

                    string fd = "";
                    {
                        int iErrors = 0;
                        TryWebCallAgain:
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                        request.UserAgent = "http://ljmindmap.com/; [email protected]";
                        WebResponse response = null;
                        try
                        {
                            LJTrafficCop.WaitMyTurn();
                            LJTrafficCop.WaitMyTurn(); // we just have to move more slowly maybe.

                            response = request.GetResponse();
                        }
                        /*                    catch (Exception e)
                                            {
                                                Console.WriteLine("Pausing due to web error: " + e.ToString());
                                                Console.WriteLine("uri is " + uri);
                                                // implement quick, dirty exponential backoff right here.
                                                iErrors++;
                                                Console.WriteLine("Sleeping: " + iErrors);
                                                Thread.Sleep(5000 * iErrors);

                                                goto TryWebCallAgain;
                                            }
                         * */
                        catch (WebException exception3)
                        {
                            if ((exception3.ToString().Contains("404") || exception3.ToString().Contains("410")) || exception3.ToString().Contains("403"))
                            {
                                SetSampleDayToNow(name);
                                new NpgsqlCommand(
                                    string.Format("update nameidmap set offline_last_detected_on={0}, postsperyear=0, iaddperyear=0 where name='{1}';", today, name),
                                    DBConnection).ExecuteNonQuery();
                                Console.WriteLine("offline_last_detected_on today");

                                continue;
                            }
                            Console.WriteLine(uri);
                            Console.WriteLine(exception3.ToString());
                            Console.WriteLine("instead of trying again, i'm sleeping two seconds and going to the next dude.");
                            Thread.Sleep(2000); // this fires during bandwidth interruptions (and perhaps other times)
                                                //goto DO_OVER;
                            continue;
                        }

                        Stream s = response.GetResponseStream();
                        StreamReader sr = new StreamReader(s);
                        try
                        {
                            fd = sr.ReadToEnd();
                        }
                        catch (WebException exception3)
                        {
                            if ((exception3.ToString().Contains("404") || exception3.ToString().Contains("410")) || exception3.ToString().Contains("403"))
                            {
                                SetSampleDayToNow(name);
                                new NpgsqlCommand(
                                    string.Format("update nameidmap set offline_last_detected_on={0}, postsperyear=0, iaddperyear=0 where name='{1}';", today, name),
                                    DBConnection).ExecuteNonQuery();
                                Console.WriteLine("offline_last_detected_on today");

                                continue;
                            }
                            Console.WriteLine(uri);
                            Console.WriteLine(exception3.ToString());
                            Console.WriteLine("DELAY helps nada. instead of trying again, what if we skip this one?");
                            Thread.Sleep(1000);
                            //goto DO_OVER;
                            continue;
                        }

                        if (fd.Contains("Bot Policy")) // this isn't f*****g working and it's scary
                        {
                            Console.WriteLine(fd);
                            Console.WriteLine("Pausing ten seconds due to throttle trigger.");
                            Thread.Sleep(10 * 1000);
                            goto TryWebCallAgain;
                        }
                    }

                    /*
                catch (XmlException exception)
                {
                    if (exception.ToString().Contains("There are multiple root elements."))       { Console.WriteLine("Some failure where the account's gone. Dunno.");                SetSampleDayToNow(name); continue; }
                    if (exception.ToString().Contains("Invalid character in the given encoding")) { Console.WriteLine("Old DBCS or whatever in bio means blown foaf parse. le sigh."); SetSampleDayToNow(name); continue; }
                    if (exception.ToString().Contains("unexpected token")) { Console.WriteLine("unexpected token in foaf. whatevs."); SetSampleDayToNow(name); continue; }
                    if (exception.ToString().Contains("Unexpected end of file has occurred. The following elements are not closed:")) { Console.WriteLine("Whack job bio caused bad xml eof whatever."); SetSampleDayToNow(name); continue; }
                    Console.WriteLine(exception.ToString()); Thread.Sleep(0xea60); goto DO_OVER;
                }
                catch (IOException exception2)
                { Console.WriteLine(exception2.ToString()); goto DO_OVER; }
                catch (WebException exception3)
                {   if ((exception3.ToString().Contains("404") || exception3.ToString().Contains("410")) || exception3.ToString().Contains("403"))
                    {
                        SetSampleDayToNow(name);
                        new NpgsqlCommand(
                            string.Format("update nameidmap set offline_last_detected_on={0}, postsperyear=0, iaddperyear=0 where name='{1}';", today, name),
                            DBConnection).ExecuteNonQuery();
                        Console.WriteLine("offline_last_detected_on today");

                        continue;
                    }
                    Console.WriteLine(uri);
                    Console.WriteLine(exception3.ToString());
                    Console.WriteLine("DELAY helps nada. instead of trying again, what if we skip this one?");
                    Thread.Sleep(1000);
                    //goto DO_OVER;
                    continue;
                }    */

                    XDocument document = null;
                    try
                    {
                        document = XDocument.Parse(fd);
                    }
                    catch (XmlException x)
                    {
                        // don't f****n know.
                        Console.WriteLine(uri);
                        Console.WriteLine(x.ToString());
                        Console.WriteLine("instead of trying again, i'm sleeping two seconds and going to the next dude.");
                        Thread.Sleep(2000); // this fires during bandwidth interruptions (and perhaps other times)
                        continue;
                    }

                    XElement personElement = document.Element("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF").Element("{http://xmlns.com/foaf/0.1/}Person");

                    // If we don't have a person element, just set the sample day to now so the next sample is futurey.
                    string myUpdateString;

                    if (personElement == null)
                    {
                        myUpdateString = string.Format("update nameidmap set sampleday={0} where name='{1}'", today, name); // f**k you ya time-waster, move ahead.
                    }
                    else
                    {
                        // int count = personElement.Elements("{http://xmlns.com/foaf/0.1/}knows").Count();
                        // yeah it returns data. is that data ok to use in extrapolation fields numiread_sampleday ??? compare and find out!

                        string nick = personElement.Element("{http://xmlns.com/foaf/0.1/}nick").Value;
                        if (nick != name) // rename scenario!?
                        {
                            // have we noted this rename before? WE NOTE IT ON NICK in made_by_rename_detected_on, and on NAME as killed_by_rename_detected_on
                            command = new NpgsqlCommand(string.Format("select made_by_rename_detected_on from nameidmap where name='{0}';", nick), DBConnection);
                            reader = command.ExecuteReader();
                            reader.Read();
                            if (reader.HasRows) // maybe we've never heard of 'em.
                            {
                                bool isDBNull = reader.IsDBNull(0);
                                reader.Close();
                                if (isDBNull)
                                {
                                    Console.WriteLine("Old name: " + name + " New name: " + nick);
                                    // never detected b4. note it!
                                    new NpgsqlCommand(
                                        string.Format("update nameidmap set made_by_rename_detected_on={0}, offline_last_detected_on=null where name='{1}';", today, nick),
                                        DBConnection).ExecuteNonQuery();

                                    new NpgsqlCommand(
                                        string.Format("update nameidmap set offline_last_detected_on={0}, postsperyear=0, iaddperyear=0 where name='{1}';", today, name),
                                        DBConnection).ExecuteNonQuery();

                                    // everything else is ok i suppose. so fall through and keep on
                                }
                            }
                            else
                                Console.WriteLine("Hey, this is clearly a rename so new that it's not in my nameidmap, but i don't add entries so f**k it.");
                        }

                        string city = "";
                        XElement cityNode = personElement.Element("{http://blogs.yandex.ru/schema/foaf/}city");
                        if (cityNode != null)
                        {
                            city = cityNode.Attribute("{http://purl.org/dc/elements/1.1/}title").Value.Replace(@"\", "");
                        }
                        XElement blogActivityNode = personElement.Element("{http://blogs.yandex.ru/schema/foaf/}blogActivity");
                        int numPostsAtThisSample = 0;
                        if (blogActivityNode != null)
                        {
                            XElement postsNode = blogActivityNode.Element("{http://blogs.yandex.ru/schema/foaf/}Posts");
                            XElement postedNode = postsNode.Element("{http://blogs.yandex.ru/schema/foaf/}posted");
                            //                        numPostsAtThisSample = int.Parse(personElement.Element("{http://blogs.yandex.ru/schema/foaf/}blogActivity").Value);
                            numPostsAtThisSample = int.Parse(postedNode.Value); // this is where i dug in deeper... must be tested.
                        }
                        if (numPostsAtLastSample > -1)
                        {
                            short newPostsInSamplePeriod = (short)(numPostsAtThisSample - numPostsAtLastSample);
                            int daysBetweenSamples = today - dayOfLastSample;
                            short postsperyear = (short)(newPostsInSamplePeriod * 365 / daysBetweenSamples);

                            if (postsperyear == 0)
                            {
                                // ppy is zero. i am c urious about the foaf:weblog node, in particular its dateLastUpdated. this is just experimental for now.
                                XElement webLog = personElement.Element("{http://xmlns.com/foaf/0.1/}weblog");
                                if (null != webLog)
                                {
                                    XAttribute weblogNodeUpdateAttribute = webLog.Attribute("{http://www.livejournal.org/rss/lj/1.0/}dateLastUpdated");
                                    if (null != weblogNodeUpdateAttribute)
                                    {
                                        string timeString = weblogNodeUpdateAttribute.Value;
                                        DateTime dt = DateTime.Parse(timeString);
                                        if (DateTime.Now.Subtract(dt).Days <= 365)
                                            postsperyear = 1; // we juice it up.
                                    }
                                }
                            }

                            myUpdateString = string.Format(
                                    "update nameidmap set postsperyear={3}, sampleday={0}, numposts={1}, city='{4}', offline_last_detected_on=null where name='{2}'",
                                    today, numPostsAtThisSample, name, postsperyear, city);

                            if (postsperyear != 0)
                            {
                                // if there's signs of activity, do we have an fdata for this user? if not, then we want to get it.
                                // just getting it and populating three fields--numreadme, numiread_sampleday, and numiread_on_sampleday (being polite)--is adequate
                                // but first is there any fdata for this user?
                                command = new NpgsqlCommand(string.Format("select day from fdata where name='{0}' LIMIT 1;", name), DBConnection);
                                reader = command.ExecuteReader();
                                reader.Read();
                                bool fHasFD = reader.HasRows;
                                reader.Close();
                                if (false == fHasFD)
                                {
                                    Console.WriteLine("hi");  // i have no fdata for this account. i'm totally scared to f**k this up. just pause.
                                }
                            }
                        }
                        else
                        {
                            myUpdateString = string.Format("update nameidmap set sampleday={0}, numposts={1}, city='{3}', offline_last_detected_on=null where name='{2}'",
                                    today, numPostsAtThisSample, name, city);
                        }
                    }
                    Console.WriteLine(myUpdateString);
                    new NpgsqlCommand(myUpdateString, DBConnection).ExecuteNonQuery();
                }
            }
        }
Beispiel #39
0
        private bool DownloadTrack(Track song, string apiKey)
        {
            bool downloaded = false;

            if (IsActive)
            {
                using (WebClient client = new WebClient())
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(song.LocalPath));

                    if (song.IsHD)
                    {
                        string extension = null;

                        try
                        {
                            WebRequest request = WebRequest.Create(song.EffectiveDownloadUrl + string.Format("?client_id={0}", apiKey));

                            request.Method = "HEAD";
                            using (WebResponse response = request.GetResponse())
                            {
                                extension = Path.GetExtension(response.Headers["Content-Disposition"]
                                                              .Replace("attachment;filename=", "").Replace("\"", ""));
                            }
                        }
                        catch (Exception)
                        {
                            // the download link might be invalid
                            WebRequest request = WebRequest.Create(song.stream_url + string.Format("?client_id={0}", apiKey));

                            request.Method = "HEAD";
                            using (WebResponse response = request.GetResponse())
                            {
                                extension = Path.GetExtension(response.Headers["Content-Disposition"]
                                                              .Replace("attachment;filename=", "").Replace("\"", ""));
                            }
                        }

                        song.LocalPath += extension;
                    }
                    else
                    {
                        song.LocalPath += ".mp3";
                    }

                    client.DownloadFile(song.EffectiveDownloadUrl + string.Format("?client_id={0}", apiKey), song.LocalPath);


                    // metadata tagging
                    TagLib.File tagFile = TagLib.File.Create(song.LocalPath);
                    tagFile.Tag.AlbumArtists = new string[] { song.Username };
                    tagFile.Tag.Performers   = new string[] { song.Username };
                    tagFile.Tag.Title        = song.Title;
                    tagFile.Tag.Genres       = new string[] { song.genre };
                    tagFile.Tag.Comment      = song.description;
                    tagFile.Save();

                    lock (SongsDownloadedLock)
                    {
                        ++TotalSongsDownloaded;
                        downloaded = true;
                    }
                }
            }

            return(downloaded);
        }
Beispiel #40
0
        public Monitor Ping()
        {
            //Return a MonitorReponse here with all the data
            //This method needs to be updateted and optimized

            DateTime dtStart = DateTime.Now;
            this.infoText = "Success";
            
            //Todo: This were removed due to extracting engine from main app - put it back in somehow
            //this.HistorySize = Properties.Settings.Default.MonitorHistorySize; 

            try
            {
                //************ SETUP REQUEST ****************//

                running = true;//This is used to prevent another check to start, if one is already running.
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = this.userAgent;
                
                // If RunCollectHtml is disabled then perform HEAD request instead of GET request
                if (!this.rules.RunCollectHtml)
                    request.Method = "HEAD";

                // Check if AllowAutoRedirect is enabled or not...
                request.AllowAutoRedirect = this.rules.AllowRedirect;

                // Ignore Certificate validation failures (ex. untrusted certificate/certificate chains)
                ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); 

                // Check if UserName is empty - User might want to pass a blank Password so send current value
                if(!string.IsNullOrEmpty(this.username))
                    request.Credentials = new NetworkCredential(this.username, this.password);

                // Check if proxy has been specified
                if (this.proxy.Address != null)
                    request.Proxy = this.proxy;

                //************ HANDLE RESPONSE ****************//

                // Create a new 'HttpWebRequest' Object to the mentioned URL.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
                
                this.statusCode = myHttpWebResponse.StatusCode.ToString();
                this.statusDescription = myHttpWebResponse.StatusDescription;
                this.responseUri = myHttpWebResponse.ResponseUri.ToString();
                this.responseContentType = myHttpWebResponse.ContentType;

                // Check if StatusCode is OK, else throw exception
                if (myHttpWebResponse.StatusCode != HttpStatusCode.OK)
                    throw new Exception(myHttpWebResponse.StatusDescription);

                //Everything went well, let's save the response time
                TimeSpan ts = DateTime.Now - dtStart;
                this.responseTime = ts.TotalMilliseconds;

                // Check if RunCollectHtml is enabled
                if(this.rules.RunCollectHtml)
                    this.responseHtml = CollectHTML(myHttpWebResponse); 
                
                //Saves the totaltPingTime for use with avg. ping time
                this.totaltPingTime += this.responseTime;
                this.pingNo++;

                this.lastUpdated = DateTime.Now;

                //Every thing was good do far. The server is up.
                this.status = MonitorStatus.Up;

                //Run the rules set in this monitor, and set the Status and infoText
                this.RunRules();

                // Update historical log
                AddToHistory();
            }
            catch (Exception exp)
            {
                this.responseTime = 0;
                this.status = MonitorStatus.Down;
                this.infoText = "Failed: " + exp.Message;

                AddToHistory();
            }
            finally
            {
                running = false;
                if (request != null)
                    request.Abort();
            }

            return this;
        }
Beispiel #41
0
        public static ArrayList BuscaCep(string cep)
        {
            /// request.AllowAutoRedirect = false;
            HttpWebRequest  request       = (HttpWebRequest)WebRequest.Create("https://viacep.com.br/ws/" + cep + "/json/");
            HttpWebResponse ChecaServidor = (HttpWebResponse)request.GetResponse();
            ArrayList       Lista         = new ArrayList();

            request.AllowAutoRedirect = false;



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

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

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

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

                            //Complemento
                            if (cont == 3)
                            {
                                string[] valor = substring.Split(":".ToCharArray());
                                Lista.Add(valor[1]);
                            }

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

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

                            //Estado (UF)
                            if (cont == 6)
                            {
                                string[] valor = substring.Split(":".ToCharArray());
                                Lista.Add(valor[1]);
                            }
                            if (cont == 7)
                            {
                                string[] valor = substring.Split(":".ToCharArray());
                                Lista.Add(valor[1]);
                            }
                            if (cont == 8)
                            {
                                string[] valor = substring.Split(":".ToCharArray());
                                Lista.Add(valor[1]);
                            }


                            cont++;
                        }
                    }
                }
            }

            return(Lista);
        }
 public IHttpWebRequest Create(string uri)
 {
     return(new WrapHttpWebRequest((HttpWebRequest)WebRequest.Create(uri)));
 }
Beispiel #43
0
 public WebRequestFixture(ILogger <System.Net.S3.S3WebRequest> logger, Amazon.Extensions.NETCore.Setup.AWSOptions options)
 {
     WebRequest.RegisterPrefix("s3", new S3WebRequestCreate(logger, options));
     UriParser.Register(new S3UriParser(), "s3", -1);
 }
        public static async void CheckForUpdate()
        {
            var logger         = LogManager.GetCurrentClassLogger();
            var currentVersion = Version.Parse(VERSION);

            try
            {
                var request  = WebRequest.Create("https://github.com/ciribob/DCS-SimpleRadioStandalone/releases/latest");
                var response = (HttpWebResponse)await Task.Factory
                               .FromAsync(request.BeginGetResponse,
                                          request.EndGetResponse,
                                          null);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var path = response.ResponseUri.AbsolutePath;

                    if (path.Contains("tag/"))
                    {
                        var     githubVersion = path.Split('/').Last().ToLower().Replace("v", "");
                        Version ghVersion     = null;

                        if (Version.TryParse(githubVersion, out ghVersion))
                        {
                            //comparse parts
                            if (ghVersion.CompareTo(currentVersion) > 0)
                            {
                                logger.Warn("Update Available on GitHub: " + githubVersion);
                                var result =
                                    MessageBox.Show("New Version Available!\n\nDo you want to Update?",
                                                    "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Information);

                                // Process message box results
                                switch (result)
                                {
                                case MessageBoxResult.Yes:
                                    //launch browser
                                    Process.Start(response.ResponseUri.ToString());
                                    break;

                                case MessageBoxResult.No:

                                    break;
                                }
                            }
                            else if (ghVersion.CompareTo(currentVersion) == 0)
                            {
                                logger.Warn("Running Latest Version: " + githubVersion);
                            }
                            else
                            {
                                logger.Warn("Running TESTING Version!! : " + VERSION);
                            }
                        }
                        else
                        {
                            logger.Warn("Failed to Parse version: " + githubVersion);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Ignore for now
            }
        }
Beispiel #45
0
        static void GetNewFile(IProgressReporterDialogue frmProgressReporter, string baseurl, string subdir, string file)
        {
            // create dest dir
            string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir;

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

            // get dest path
            string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir +
                          file;

            Exception fail    = null;
            int       attempt = 0;

            // attempt to get file
            while (attempt < 2)
            {
                // check if user canceled
                if (frmProgressReporter.doWorkArgs.CancelRequested)
                {
                    frmProgressReporter.doWorkArgs.CancelAcknowledged = true;
                    throw new Exception("Cancel");
                }

                try
                {
                    string url = baseurl + file + "?" + new Random().Next();
                    // Create a request using a URL that can receive a post.
                    WebRequest request = WebRequest.Create(url);
                    log.Info("GetNewFile " + url);
                    // Set the Method property of the request to GET.
                    request.Method = "GET";
                    // Allow compressed content
                    ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip |
                                                                       DecompressionMethods.Deflate;
                    // tell server we allow compress content
                    request.Headers.Add("Accept-Encoding", "gzip,deflate");
                    // Get the response.
                    using (WebResponse response = request.GetResponse())
                    {
                        // Display the status.
                        log.Info(((HttpWebResponse)response).StatusDescription);
                        // Get the stream containing content returned by the server.
                        Stream dataStream = response.GetResponseStream();

                        // from head
                        long bytes = response.ContentLength;

                        long contlen = bytes;

                        byte[] buf1 = new byte[4096];

                        // if the file doesnt exist. just save it inplace
                        string fn = path + ".new";

                        using (FileStream fs = new FileStream(fn, FileMode.Create))
                        {
                            DateTime dt = DateTime.Now;

                            log.Debug("ContentLength: " + file + " " + bytes);

                            while (dataStream.CanRead)
                            {
                                try
                                {
                                    if (dt.Second != DateTime.Now.Second)
                                    {
                                        if (frmProgressReporter != null)
                                        {
                                            frmProgressReporter.UpdateProgressAndStatus(
                                                (int)(((double)(contlen - bytes) / (double)contlen) * 100),
                                                Strings.Getting + file + ": " +
                                                (((double)(contlen - bytes) / (double)contlen) * 100)
                                                .ToString("0.0") +
                                                "%"); //+ Math.Abs(bytes) + " bytes");
                                        }
                                        dt = DateTime.Now;
                                    }
                                }
                                catch
                                {
                                }

                                int len = dataStream.Read(buf1, 0, buf1.Length);
                                if (len == 0)
                                {
                                    log.Debug("GetNewFile: 0 byte read " + file);
                                    break;
                                }
                                bytes -= len;
                                fs.Write(buf1, 0, len);
                            }

                            log.Info("GetNewFile: " + file + " Done with length: " + fs.Length);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    fail = ex;
                    attempt++;
                    continue;
                }

                // break if we have no exception
                break;
            }

            if (attempt == 2)
            {
                throw fail;
            }
        }
Beispiel #46
0
        internal bool HttpDownload(string url, string localFile)
        {
            string directory = Path.GetDirectoryName(localFile);

            //Console.WriteLine($"下载路径:{url},本地路径:{directory},文件名:{Path.GetFileName(localFile)}");
            Common.WriteLog_Information("下载路径:{0},本地路径:{1},文件名:{2}", url, directory, Path.GetFileName(localFile));
            bool       success     = false;
            FileStream writeStream = null;
            Stream     readStream  = null;
            string     backupFile  = localFile + Updater.UpdateTempFileName;

            if (File.Exists(localFile))
            {
                File.Move(localFile, backupFile);
                Common.WriteLog_Information("备份文件:{0} => {1}", localFile, backupFile);
            }
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            writeStream = new FileStream(localFile, FileMode.Create);
            DownloadFileInfo downloadingFile = null;

            try
            {
                downloadingFile = new DownloadFileInfo(localFile, backupFile, 0, 0);

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Proxy = null;
                WebResponse webResponse   = webRequest.GetResponse();
                long        contentLength = webResponse.ContentLength;

                downloadingFile.ContentLength = contentLength;
                OnDownloading(new DownloadInfo(DownloadState.BeginDownload, downloadingFile));

                readStream = webResponse.GetResponseStream();
                byte[] buffer         = new byte[8192];
                int    downloadedSize = readStream.Read(buffer, 0, buffer.Length);

                downloadingFile.DownloadedSize += downloadedSize;
                OnDownloading(new DownloadInfo(DownloadState.Downloading, downloadingFile));

                while (downloadedSize > 0)
                {
                    writeStream.Write(buffer, 0, downloadedSize);
                    downloadedSize = readStream.Read(buffer, 0, buffer.Length);

                    downloadingFile.DownloadedSize += downloadedSize;
                    OnDownloading(new DownloadInfo(DownloadState.Downloading, downloadingFile));

                    Application.DoEvents();
                }

                OnDownloading(new DownloadInfo(DownloadState.Downloaded, downloadingFile));

                success = true;
            }
            catch (Exception ex)
            {
                throw Common.Exception <Exception>(ex.Message + Environment.NewLine + "错误代码:0x0f01");
            }
            finally
            {
                if (writeStream != null)
                {
                    writeStream.Close();
                }
                if (readStream != null)
                {
                    readStream.Close();
                }
            }
            return(success);
        }
Beispiel #47
0
      /// <summary>get the address(s) of proxy servers from Control Panel / Internet Options</summary>
      /// <param name="serverURL">the url of the web-server with which the RC will interact</param>
      private string GetDynamicProxy(string serverURL, NameValueCollection outgoingHeaders)
      {
         var byteArray = new byte[10000];
         var chrArray = new char[20000];
         Encoding encoding = Encoding.UTF8;

         //Open http session
         IntPtr hSession = WinHttpOpen("Test App", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, _winhttpNoProxyName,
                                       _winhttpNoProxyBypass, 0);
         var wao = new WINHTTP_AUTOPROXY_OPTIONS();
         var wpi = new WINHTTP_PROXY_INFO();
         wao.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
         wao.dwAutoDetectFlags = 0;
         wao.fAutoLoginIfChallenged = true;
         // Get the proxy config file (pac).
         wao.lpszAutoConfigUrl =
            (String)
            Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\Currentversion\\Internet Settings").GetValue(
               "AutoConfigURL");
         wao.dwAutoDetectFlags = (WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A);

         if (wao.lpszAutoConfigUrl != null)
            wao.lpszAutoConfigUrl = wao.lpszAutoConfigUrl.Trim();

         bool result = WinHttpGetProxyForUrl(hSession, serverURL, ref wao, ref wpi);

         // If we didn't succeed to read the pac file maybe its an ins file
         if (!result && !string.IsNullOrEmpty(wao.lpszAutoConfigUrl))
         {
            try
            {
               int usedLen;
               int charLen = 0;
               Decoder decoder = encoding.GetDecoder();

               // Get the content of the file
               var requesterURLCon = (HttpWebRequest)WebRequest.Create(wao.lpszAutoConfigUrl);
               requesterURLCon.AllowAutoRedirect = true;
               requesterURLCon.Method = "GET";
               requesterURLCon.Credentials = CredentialCache.DefaultCredentials;
               if (outgoingHeaders.Count > 0 && Logger.Instance.LogLevel == Logger.LogLevels.Basic)
                  requesterURLCon.Headers.Add(outgoingHeaders.GetKey(0), outgoingHeaders.GetValues(0)[0]);

               // read the answer
               WebResponse webResponse = requesterURLCon.GetResponse();
               var inpStreamReader = new StreamReader(webResponse.GetResponseStream(), encoding);
               Stream stream = inpStreamReader.BaseStream;
#if !PocketPC
               stream = new BufferedStream(stream);
#endif
               while ((usedLen = stream.Read(byteArray, 0, byteArray.Length)) > 0)
               {
                  // Make sure we have enough space for the growing message
                  if (charLen + usedLen > chrArray.Length)
                  {
                     var newArray = new char[chrArray.Length + 10000];
                     chrArray.CopyTo(newArray, 0);
                     chrArray = newArray;
                  }
                  charLen += decoder.GetChars(byteArray, 0, usedLen, chrArray, charLen);
               }
               var answer = new String(chrArray, 0, charLen);
               Logger.Instance.WriteServerToLog("pac file" + answer);

               // Get the pac file from the correct entry in the ins file
               int startIndex = answer.IndexOf("AutoConfigJSURL");
               Logger.Instance.WriteServerToLog("pac file" + startIndex);
               if (startIndex != -1)
               {
                  int endIndex = answer.IndexOf(".pac", startIndex);
                  Logger.Instance.WriteServerToLog("pac file" + endIndex);
                  string str = answer.Substring(startIndex + 16, endIndex - startIndex - 16 + 4);
                  Logger.Instance.WriteServerToLog("str" + str);
                  wao.lpszAutoConfigUrl = str;
                  WinHttpGetProxyForUrl(hSession, serverURL, ref wao, ref wpi);
               }
            }
            catch (System.Exception ex)
            {
               Logger.Instance.WriteExceptionToLog(ex, string.Format("PAC file \"{0}\" was not found!", wao.lpszAutoConfigUrl));
            }
         }

         //Close http session
         WinHttpCloseHandle(hSession);

         if (wpi.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY)
            return "DIRECT";
         return wpi.lpszProxy;
      }
Beispiel #48
0
        private string webcamNitpicker(string ip, int port)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/no/way/youcanhave.thispage"); //ловушка для редиректа на двухсотую

            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            //webRequest.ServicePoint.MaxIdleTime = 5000;
            //webRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
            //ServicePointManager.MaxServicePointIdleTime = 3000;

            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    return(null);
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/ChangePwd.htm");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/" + " - Probably undef_webcam type4");
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/live.html");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;

            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/live.html" + " - Maybe it's Techno Vision Security System blyat type R-1?");
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/view/index.shtml");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/view/index.shtml" + " OR " + "http://" + ip + ":" + port + "/mjpg/video.mjpg" + " - AXIS Video type1");
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/view/indexFrame.shtml");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/view/indexFrame.shtml" + " - Maybe it's AXIS Video type2?");
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/anony/mjpg.cgi");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/anony/mjpg.cgi" + " - Maybe it's undef_webcam type3?"); //на фейках срабатывает anyrandom.cgi, проверить на работающих экземплярах
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/images/zoom-in.jpg");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/" + " - Maybe it's undef_webcam[plugin] type5?");
                }
            }
            catch (System.Net.WebException) { };

            webRequest = (HttpWebRequest)WebRequest.Create("http://" + ip + ":" + port + "/image/time_setting.gif");
            webRequest.AllowAutoRedirect = false;
            webRequest.Timeout           = 3000;
            webRequest.ReadWriteTimeout  = 3000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode.ToString() == "OK")
                {
                    resultCounter++;
                    return("[IPcam][N!] " + "http://" + ip + ":" + port + "/" + " - Maybe it's undef_webcam[plugin] type6?");
                }
            }
            catch (System.Net.WebException) { };

            return(null);
        }
        public ActionResult CharacterSubmit(Character newCharacter, string[] Proficiencies, string[] SpellsKnown)
        {
            string featuresString = "";

            string characterLevel;

            for (int i = 1; i <= newCharacter.CharLevel; i++)
            {
                characterLevel = i.ToString();
                HttpWebRequest dndFeatureApiRequest = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/classes/{Names[newCharacter.Class - 1]}/level/{characterLevel}");

                dndFeatureApiRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

                HttpWebResponse dndFeatureApiResponse = (HttpWebResponse)dndFeatureApiRequest.GetResponse();

                if (dndFeatureApiResponse.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader featureResponseData = new StreamReader(dndFeatureApiResponse.GetResponseStream());

                    string featuredata = featureResponseData.ReadToEnd();

                    JObject jsonFeatures = JObject.Parse(featuredata);

                    for (int j = 0; j < jsonFeatures["features"].Count(); j++)
                    {
                        featuresString += jsonFeatures["features"][j]["name"] + ",";
                    }
                }
            }


            newCharacter.Features = featuresString;

            characterLevel = newCharacter.CharLevel.ToString();
            HttpWebRequest dndSpellSlotApiRequest = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/classes/{Names[newCharacter.Class - 1]}/level/{characterLevel}");

            dndSpellSlotApiRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";
            HttpWebResponse dndSpellSlotApiResponse = (HttpWebResponse)dndSpellSlotApiRequest.GetResponse();

            if (dndSpellSlotApiResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader SpellSlotResponseData = new StreamReader(dndSpellSlotApiResponse.GetResponseStream());

                string spellslotdata = SpellSlotResponseData.ReadToEnd();

                JObject jsonSpellSlot = JObject.Parse(spellslotdata);

                if (jsonSpellSlot["spellcasting"] != null)
                {
                    if (jsonSpellSlot["spellcasting"]["cantrips_known"] != null)
                    {
                        newCharacter.Cantrips = (int)jsonSpellSlot["spellcasting"]["cantrips_known"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_1"] != null)
                    {
                        newCharacter.SpellSlot1 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_1"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_2"] != null)
                    {
                        newCharacter.SpellSlot2 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_2"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_3"] != null)
                    {
                        newCharacter.SpellSlot3 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_3"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_4"] != null)
                    {
                        newCharacter.SpellSlot4 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_4"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_5"] != null)
                    {
                        newCharacter.SpellSlot5 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_5"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_6"] != null)
                    {
                        newCharacter.SpellSlot6 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_6"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_7"] != null)
                    {
                        newCharacter.SpellSlot7 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_7"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_8"] != null)
                    {
                        newCharacter.SpellSlot8 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_8"];
                    }
                    if (jsonSpellSlot["spellcasting"]["spell_slots_level_9"] != null)
                    {
                        newCharacter.SpellSlot9 = (int)jsonSpellSlot["spellcasting"]["spell_slots_level_9"];
                    }
                }
            }

            if (SpellsKnown != null)
            {
                string spells = "";

                foreach (string spell in SpellsKnown)
                {
                    spells += spell + ",";
                }
                newCharacter.SpellsKnown = spells;
            }

            string s = "";

            foreach (string p in Proficiencies)
            {
                s += p + ",";
            }
            newCharacter.Proficiencies = s;
            //Session["t"] = newCharacter.Proficiencies;
            //Session["t2"] = newCharacter.Proficiencies[1];
            viewbagofholdingEntities ORM = new viewbagofholdingEntities();

            ORM.Characters.Add(newCharacter);
            ORM.SaveChanges();
            return(RedirectToAction("Tracker"));
        }
Beispiel #50
0
        /// <summary>
        /// Gets the latest release tag from Github.
        /// </summary>
        /// <returns>Returns an <see cref="UpdateCheck"/>.</returns>
        private static UpdateCheck GetLatestVersion()
        {
            // Somewhere to store the results
            UpdateCheck results = new UpdateCheck
            {
                CheckSuccess = false,
            };

            try
            {
                // The API URL to check for the latest release
                // Returns a JSON payload containing all the details of the latest release
                string releasesUrl = "https://api.github.com/repos/benlye/flash-multi/releases/latest";

                // Set TLS1.2, as required by the Github API
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                // Create the WebRequest
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(releasesUrl);

                // Set the UserAgent, as required by the Github API
                webRequest.UserAgent = $"flash-multi-{Application.ProductVersion}";

                // Disable keepalive so we don't hold a connection open
                webRequest.KeepAlive = false;

                // Get the response and read it
                using (WebResponse myResponse = webRequest.GetResponse())
                    using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        // Read all of the output from the StreamReader
                        string result = sr.ReadToEnd();

                        // Parse the release tag out of the JSON
                        // This contains the version string
                        int    tagStart = result.IndexOf("\"tag_name\":");
                        int    tagEnd   = result.IndexOf(",", tagStart);
                        string tagLine  = result.Substring(tagStart, tagEnd - tagStart);
                        string tag      = tagLine.Split('"')[3];

                        // Add the release tag to the results
                        results.LatestVersion = Version.Parse(tag);

                        // Parse the release URL out of the JSON
                        // This is the URL of the Github page containing details of the latest release
                        int    urlStart = result.IndexOf("\"html_url\":");
                        int    urlEnd   = result.IndexOf(",", urlStart);
                        string urlLine  = result.Substring(urlStart, urlEnd - urlStart);
                        string url      = urlLine.Split('"')[3];

                        // Add the release URL to the results
                        results.ReleaseUrl = url;
                    }

                // Define a regular expression to test the version number looks how we expect it to
                Regex versionRegex = new Regex(@"\d+\.\d+\.\d+");

                // Check that the URL and version number are as we expect
                if (results.ReleaseUrl.StartsWith("https://github.com/benlye/flash-multi/releases/") && versionRegex.Match(results.LatestVersion.ToString()).Success)
                {
                    // All looks good; the check succeeded
                    Debug.WriteLine($"Update check succeeded. Latest version is {results.LatestVersion}");
                    results.CheckSuccess = true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error getting latest version: {ex.Message}");
            }

            // Return the results
            return(results);
        }
        public ActionResult CharacterCreator(int Class)
        {
            string classString = Class.ToString();

            HttpWebRequest dndApiRequest = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/classes/{classString}");

            dndApiRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse dndApiResponse = (HttpWebResponse)dndApiRequest.GetResponse();

            if (dndApiResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(dndApiResponse.GetResponseStream());

                string data = responseData.ReadToEnd();

                JObject jsonClasses = JObject.Parse(data);
                int     size        = jsonClasses["proficiency_choices"].Count();
                ViewBag.HitDieSize = jsonClasses["hit_die"];
                ViewBag.Name       = jsonClasses["name"];
                ViewBag.Classes    = jsonClasses["proficiency_choices"][size - 1];
                ViewBag.ClassID    = jsonClasses["index"];
                ViewBag.Choose     = jsonClasses["proficiency_choices"][size - 1]["choose"];
                ViewBag.Pro        = jsonClasses["proficiencies"];
                ViewBag.Saves      = jsonClasses["saving_throws"];
            }

            HttpWebRequest dndRaceApiRequest = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/races");

            dndRaceApiRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse dndRaceApiResponse = (HttpWebResponse)dndRaceApiRequest.GetResponse();

            if (dndRaceApiResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(dndRaceApiResponse.GetResponseStream());

                string data = responseData.ReadToEnd();

                JObject jsonRaces = JObject.Parse(data);

                ViewBag.Races = jsonRaces["results"];
            }
            string[] Names = new string[] { "barbarian", "bard", "cleric", "druid", "fighter", "monk", "paladin", "ranger", "rogue", "sorcerer", "warlock", "wizard" };


            HttpWebRequest spellApiRequest0 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/0");

            spellApiRequest0.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellApiResponse0 = (HttpWebResponse)spellApiRequest0.GetResponse();

            if (spellApiResponse0.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellApiResponse0.GetResponseStream());

                string cantrips = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(cantrips);

                ViewBag.Cantrips = jsonSpells["results"];
            }

            HttpWebRequest spellAPIRequest1 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/1");

            spellAPIRequest1.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse1 = (HttpWebResponse)spellAPIRequest1.GetResponse();

            if (spellAPIresponse1.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse1.GetResponseStream());

                string Spells1 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells1);

                ViewBag.Spells1 = jsonSpells["results"];
            }

            HttpWebRequest spellAPIRequest2 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/2");

            spellAPIRequest2.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse2 = (HttpWebResponse)spellAPIRequest2.GetResponse();

            if (spellAPIresponse2.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse2.GetResponseStream());

                string Spells2 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells2);

                ViewBag.Spells2 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest3 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/3");

            spellAPIRequest3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse3 = (HttpWebResponse)spellAPIRequest3.GetResponse();

            if (spellAPIresponse3.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse3.GetResponseStream());

                string Spells3 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells3);

                ViewBag.Spells3 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest4 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/4");

            spellAPIRequest4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse4 = (HttpWebResponse)spellAPIRequest4.GetResponse();

            if (spellAPIresponse4.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse4.GetResponseStream());

                string Spells4 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells4);

                ViewBag.Spells4 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest5 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/5");

            spellAPIRequest5.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse5 = (HttpWebResponse)spellAPIRequest5.GetResponse();

            if (spellAPIresponse5.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse5.GetResponseStream());

                string Spells5 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells5);

                ViewBag.Spells5 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest6 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/6");

            spellAPIRequest6.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse6 = (HttpWebResponse)spellAPIRequest6.GetResponse();

            if (spellAPIresponse6.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse6.GetResponseStream());

                string Spells6 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells6);

                ViewBag.Spells6 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest7 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/7");

            spellAPIRequest7.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse7 = (HttpWebResponse)spellAPIRequest7.GetResponse();

            if (spellAPIresponse1.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse7.GetResponseStream());

                string Spells7 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells7);

                ViewBag.Spells7 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest8 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/8");

            spellAPIRequest8.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse8 = (HttpWebResponse)spellAPIRequest8.GetResponse();

            if (spellAPIresponse8.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse8.GetResponseStream());

                string Spells8 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells8);

                ViewBag.Spells8 = jsonSpells["results"];
            }
            HttpWebRequest spellAPIRequest9 = WebRequest.CreateHttp($"http://www.dnd5eapi.co/api/spells/{Names[Class - 1]}/level/9");

            spellAPIRequest9.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

            HttpWebResponse spellAPIresponse9 = (HttpWebResponse)spellAPIRequest9.GetResponse();

            if (spellAPIresponse9.StatusCode == HttpStatusCode.OK)
            {
                StreamReader responseData = new StreamReader(spellAPIresponse9.GetResponseStream());

                string Spells9 = responseData.ReadToEnd();

                JObject jsonSpells = JObject.Parse(Spells9);

                ViewBag.Spells9 = jsonSpells["results"];
            }

            if (User.Identity.IsAuthenticated)
            {
                ViewBag.User = User.Identity.GetUserId();
            }

            return(View());
        }
Beispiel #52
0
        public static void Main(string[] args)
        {
            Program.args = args;

            //Console.WriteLine(
            //    "If your error is about Microsoft.DirectX.DirectInput, please install the latest directx redist from here http://www.microsoft.com/en-us/download/details.aspx?id=35 \n\n");
            //Console.WriteLine("Debug under mono    MONO_LOG_LEVEL=debug mono MissionPlanner.exe");

            Thread = Thread.CurrentThread;

            System.Windows.Forms.Application.EnableVisualStyles();
            XmlConfigurator.Configure();
            // log.Info("******************* Logging Configured *******************");
            System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

            ServicePointManager.DefaultConnectionLimit = 10;

            System.Windows.Forms.Application.ThreadException += Application_ThreadException;

            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // fix ssl on mono
            ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(
                    (sender, certificate, chain, policyErrors) => { return(true); });

            if (args.Length > 0 && args[0] == "/update")
            {
                Utilities.Update.DoUpdate();
                return;
            }

            name = "farring-GCS";

            try
            {
                if (File.Exists(Settings.GetRunningDirectory() + "logo.txt"))
                {
                    name = File.ReadAllLines(Settings.GetRunningDirectory() + "logo.txt",
                                             Encoding.UTF8)[0];
                }
            }
            catch
            {
            }

            if (File.Exists(Settings.GetRunningDirectory() + "logo.png"))
            {
                Logo = new Bitmap(Settings.GetRunningDirectory() + "logo.png");
            }

            if (File.Exists(Settings.GetRunningDirectory() + "icon.png"))
            {
                // 128*128
                IconFile = new Bitmap(Settings.GetRunningDirectory() + "icon.png");
            }
            else
            {
                IconFile = MissionPlanner.Properties.Resources.mpdesktop.ToBitmap();
            }

            if (File.Exists(Settings.GetRunningDirectory() + "splashbg.png")) // 600*375
            {
                SplashBG = new Bitmap(Settings.GetRunningDirectory() + "splashbg.png");
            }


            Splash = new MissionPlanner.Splash();
            if (SplashBG != null)
            {
                Splash.BackgroundImage     = SplashBG;
                Splash.pictureBox1.Visible = false;
            }

            if (IconFile != null)
            {
                Splash.Icon = Icon.FromHandle(((Bitmap)IconFile).GetHicon());
            }

            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Splash.Text = name + " " + Application.ProductVersion + " build " + strVersion;
            //--Splash.Show();

            Application.DoEvents();
            Application.DoEvents();

            // setup theme provider
            CustomMessageBox.ApplyTheme                         += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            Controls.MainSwitcher.ApplyTheme                    += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            MissionPlanner.Controls.InputBox.ApplyTheme         += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            Controls.BackstageView.BackstageViewPage.ApplyTheme += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;

            // setup settings provider
            MissionPlanner.Comms.CommsBase.Settings += CommsBase_Settings;

            // set the cache provider to my custom version
            GMap.NET.GMaps.Instance.PrimaryCache = new Maps.MyImageCache();
            // add my custom map providers
            // AB ZhaoYJ@2017-08-30 for cleanup map provider
            // GMap.NET.MapProviders.GMapProviders.List.Add(Maps.WMSProvider.Instance);
            // GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Custom.Instance);
            // GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Earthbuilder.Instance);
            // GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Statkart_Topo2.Instance);
            // GMap.NET.MapProviders.GMapProviders.List.Add(Maps.MapBox.Instance);
            // GMap.NET.MapProviders.GMapProviders.List.Add(Maps.MapboxNoFly.Instance);
            // GMap.NET.MapProviders.GMapProviders.List.Add(GDAL.GDALProvider.Instance);

            // add proxy settings
            GMap.NET.MapProviders.GMapProvider.WebProxy             = WebRequest.GetSystemWebProxy();
            GMap.NET.MapProviders.GMapProvider.WebProxy.Credentials = CredentialCache.DefaultCredentials;

            WebRequest.DefaultWebProxy             = WebRequest.GetSystemWebProxy();
            WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

            if (name == "VVVVZ")
            {
                // set pw
                Settings.Instance["password"]         = "******";
                Settings.Instance["password_protect"] = "True";
                // prevent wizard
                Settings.Instance["newuser"] = "******";
                // invalidate update url
                System.Configuration.ConfigurationManager.AppSettings["UpdateLocationVersion"] = "";
            }

            CleanupFiles();

            //log.InfoFormat("64bit os {0}, 64bit process {1}", System.Environment.Is64BitOperatingSystem,
            //    System.Environment.Is64BitProcess);

            try
            {
                //System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.RealTime;
                Thread.CurrentThread.Name = "Base Thread";
                Application.Run(new MainV2());
            }
            catch (Exception ex)
            {
                log.Fatal("Fatal app exception", ex);
                Console.WriteLine(ex.ToString());

                Console.WriteLine("\nPress any key to exit!");
                Console.ReadLine();
            }

            try
            {
                // kill sim background process if its still running
                if (Controls.SITL.simulator != null)
                {
                    Controls.SITL.simulator.Kill();
                }
            }
            catch
            {
            }
        }
  static void Main()
  {  
   
    try
    {
      // Create a HttpWebrequest object to the desired URL. 
      HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");

    
  /**
    * If you are behind a firewall and you do not have your browser proxy setup
    * you need to use the following proxy creation code.

      // Create a proxy object.
      WebProxy myProxy = new WebProxy();

      // Associate a new Uri object to the _wProxy object, using the proxy address
      // selected by the user.
      myProxy.Address = new Uri("http://myproxy");
       
        
      // Finally, initialize the Web request object proxy property with the _wProxy
      // object.
      myHttpWebRequest.Proxy=myProxy;
    ***/

      // Create an instance of the RequestState and assign the previous myHttpWebRequest
      // object to its request field.  
      RequestState myRequestState = new RequestState();  
      myRequestState.request = myHttpWebRequest;


      // Start the asynchronous request.
      IAsyncResult result=
        (IAsyncResult) myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);

      // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
      ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

      // The response came in the allowed time. The work processing will happen in the 
      // callback function.
      allDone.WaitOne();
      
      // Release the HttpWebResponse resource.
      myRequestState.response.Close();
    }
    catch(WebException e)
    {
      Console.WriteLine("\nMain Exception raised!");
      Console.WriteLine("\nMessage:{0}",e.Message);
      Console.WriteLine("\nStatus:{0}",e.Status);
      Console.WriteLine("Press any key to continue..........");
    }
    catch(Exception e)
    {
      Console.WriteLine("\nMain Exception raised!");
      Console.WriteLine("Source :{0} " , e.Source);
      Console.WriteLine("Message :{0} " , e.Message);
      Console.WriteLine("Press any key to continue..........");
      Console.Read();
    }
  }
Beispiel #54
0
        public void DownloadAllFromFtpDirectory(string source, int type)
        {
            string resultHost = host + ftpSubDir;

            logHelper.showLog("\nDownload all from: " + resultHost + source, null);
            string tempDir;

            FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(resultHost + source);

            listRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
            listRequest.Credentials = new NetworkCredential(user, pass);;

            List <string> lines = new List <string>();
            string        tempFile;

            try
            {
                using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
                    using (Stream listStream = listResponse.GetResponseStream())
                        using (StreamReader listReader = new StreamReader(listStream))
                        {
                            while (!listReader.EndOfStream)
                            {
                                tempFile = listReader.ReadLine();
                                if (tempFile != "." && tempFile != "..")//&& allowedExtensions.Any(Path.GetExtension(tempFile).Contains)
                                {
                                    //Console.Write(Path.GetExtension(tempFile) + "\n");
                                    tempFile = Path.GetFileName(tempFile);
                                    //logHelper.showLog("File: " + tempFile, null);
                                    lines.Add(tempFile);
                                }
                            }
                        }

                if (type == 0)
                {
                    tempDir = tempDirIn;
                }
                else
                {
                    tempDir = tempDirOut;
                }

                //create temp dir, if not exists
                if (!Directory.Exists(tempDirIn))
                {
                    Directory.CreateDirectory(tempDirIn);
                }
                if (!Directory.Exists(tempDirOut))
                {
                    Directory.CreateDirectory(tempDirOut);
                }

                foreach (string line in lines)
                {
                    if (DownloadFile(host, ftpSubDir + source + "/" + line, user, pass, tempDir))
                    {
                        logHelper.showLog("Successfully downloaded: " + line, null);
                        //delete file in ftp
                        if (deleteFile(resultHost + source + "/" + line))
                        {
                            logHelper.showLog("Ftp file successfully deleted: " + line, null);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                Console.Write(ex.Message + "\n");
            }
        }
Beispiel #55
0
        private static void Main()
        {
            var currentDirectory  = new NativeStorage(".");
            var solutionDirectory = new NativeStorage("..");

            currentDirectory.DeleteDirectory("./staging");

            if (!Directory.Exists("releases"))
            {
                Directory.CreateDirectory("releases");
            }

            var stagingDirectory = currentDirectory.GetStorageForDirectory("staging");
            var currentDate      = DateTime.Now.ToString("yyyy.Mdd.");

            currentDate += currentDirectory.GetDirectories("releases").Count(s => s.Contains(currentDate));

            var releaseDirectory = currentDirectory.GetStorageForDirectory($"./releases/App-{currentDate}");

            Console.WriteLine($"Package: Qsor");
            Console.WriteLine($"Release Version: {currentDate}");
            Console.WriteLine($"Release Directory: {releaseDirectory.GetFullPath(".")}");
            Console.WriteLine($"Changelog: \n{ChangelogGenerator.GenerateChangelog()}");

            var logo = solutionDirectory.GetFullPath("Qsor.Game/Resources/Textures/Logo-256x256.png");
            var icon = solutionDirectory.GetFullPath("Qsor.Desktop/icon.ico");

            RunCommand("dotnet", $"publish -f netcoreapp3.1 Qsor.Desktop --configuration Release --runtime win-x64 -p:Version={currentDate} -o {stagingDirectory.GetFullPath(".")}",
                       solutionDirectory.GetFullPath("."));

            RunCommand("./tools/rcedit-x64.exe", $"\"{stagingDirectory.GetFullPath(".")}\\Qsor.exe\" --set-icon \"{icon}\"");

            RunCommand(NugetPath, $"pack Qsor.Desktop/qsor.nuspec -Version {currentDate} -Properties Configuration=Release -OutputDirectory {stagingDirectory.GetFullPath(".")} -BasePath {stagingDirectory.GetFullPath(".")}",
                       solutionDirectory.GetFullPath("."));

            RunCommand(SquirrelPath, $"--releasify {stagingDirectory.GetFullPath($"./Qsor.{currentDate}.nupkg")} --releaseDir {releaseDirectory.GetFullPath(".")} --no-msi --icon {icon} --setupIcon {icon} --loadingGif {logo}",
                       stagingDirectory.GetFullPath("."));

            RunCommand("git", $"tag {currentDate}");
            RunCommand("git", $"push origin {currentDate}");

            File.Move(releaseDirectory.GetFullPath("Setup.exe"), releaseDirectory.GetFullPath("install.exe"));

            stagingDirectory.DeleteDirectory(".");

            var req = new JsonWebRequest <GitHubRelease>($"https://api.github.com/repos/Mempler/Qsor/releases")
            {
                Method = HttpMethod.Post,
            };

            Console.WriteLine($"Creating release {currentDate}...");

            req.AddRaw(JsonConvert.SerializeObject(new GitHubRelease
            {
                Name  = currentDate,
                Draft = true,
                Body  = ChangelogGenerator.GenerateChangelog()
            }));

            req.AddHeader("Authorization", $"token {GithubAccessToken}");
            req.Perform();

            var targetRelease = req.ResponseObject;

            var assetUploadUrl = targetRelease.UploadUrl.Replace("{?name,label}", "?name={0}");

            foreach (var a in Directory.GetFiles(releaseDirectory.GetFullPath(".")).Reverse())
            {
                if (Path.GetFileName(a).StartsWith('.'))
                {
                    continue;
                }

                Console.WriteLine($"- Pushing asset {a}...");
                var upload = new WebRequest(assetUploadUrl, Path.GetFileName(a))
                {
                    Method      = HttpMethod.Post,
                    Timeout     = 240000,
                    ContentType = "application/octet-stream",
                };

                upload.AddRaw(File.ReadAllBytes(a));
                upload.AddHeader("Authorization", $"token {GithubAccessToken}");
                upload.Perform();
            }
        }
Beispiel #56
0
        private static string ProcessMailMerge(string fileId, TrackerData fileData)
        {
            Guid userId;

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            var sended = false;

            try
            {
                SecurityContext.AuthenticateMe(userId);

                if (string.IsNullOrEmpty(fileData.Url))
                {
                    throw new ArgumentException("emptry url");
                }

                if (fileData.MailMerge == null)
                {
                    throw new ArgumentException("MailMerge is null");
                }

                var    message = fileData.MailMerge.Message;
                Stream attach  = null;
                switch (fileData.MailMerge.Type)
                {
                case MailMergeType.AttachDocx:
                case MailMergeType.AttachPdf:
                    var downloadRequest = (HttpWebRequest)WebRequest.Create(fileData.Url);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
                    {
                        const int bufferSize = 2048;
                        var       buffer     = new byte[bufferSize];
                        int       readed;
                        attach = new MemoryStream();
                        while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                        {
                            attach.Write(buffer, 0, readed);
                        }
                        attach.Position = 0;
                    }

                    if (string.IsNullOrEmpty(fileData.MailMerge.Title))
                    {
                        fileData.MailMerge.Title = "Attach";
                    }

                    var attachExt = fileData.MailMerge.Type == MailMergeType.AttachDocx ? ".docx" : ".pdf";
                    var curExt    = FileUtility.GetFileExtension(fileData.MailMerge.Title);
                    if (curExt != attachExt)
                    {
                        fileData.MailMerge.Title += attachExt;
                    }

                    break;

                case MailMergeType.Html:
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(fileData.Url);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                        using (var stream = httpWebResponse.GetResponseStream())
                            if (stream != null)
                            {
                                using (var reader = new StreamReader(stream, Encoding.GetEncoding(Encoding.UTF8.WebName)))
                                {
                                    message = reader.ReadToEnd();
                                }
                            }
                    break;
                }

                using (var mailMergeTask =
                           new MailMergeTask
                {
                    From = fileData.MailMerge.From,
                    Subject = fileData.MailMerge.Subject,
                    To = fileData.MailMerge.To,
                    Message = message,
                    AttachTitle = fileData.MailMerge.Title,
                    Attach = attach
                })
                {
                    var response = mailMergeTask.Run();
                    Global.Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}",
                                             fileData.MailMerge.RecordIndex, fileData.MailMerge.RecordCount, response);
                }
                sended = true;
            }
            catch (Exception ex)
            {
                Global.Logger.Error(
                    string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}",
                                  (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount),
                                  userId, fileData.Url),
                    ex);
            }

            if (fileData.MailMerge != null &&
                fileData.MailMerge.RecordIndex == fileData.MailMerge.RecordCount - 1)
            {
                var errorCount = fileData.MailMerge.RecordErrorCount;
                if (!sended)
                {
                    errorCount++;
                }

                NotifyClient.SendMailMergeEnd(userId, fileData.MailMerge.RecordCount, errorCount);
            }

            return(sended
                       ? "0"   //error:0 - sended
                       : "1"); //error:1 - some error
        }
Beispiel #57
0
        public async Task TohoDBGet(CommandContext ctx, [RemainingText] string song)
        {
            var interactivity = ctx.Client.GetInteractivity();
            var init          = await ctx.RespondAsync("Searching");

            int select = 0;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://touhoudb.com/api/songs?query=" + song + "&maxResults=10&sort=FavoritedTimes&preferAccurateMatches=true&nameMatchMode=Auto&fields=Lyrics,PVs&lang=English");

            request.Method = "GET";
            request.Accept = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (!((int)response.StatusCode == 200))
            {
                await ctx.RespondAsync("Song not found (Note: In weird cases it finds the song but still returns 0 results, since this crashes the bot, its not showing anything here)");

                return;
            }
            Stream       dataStream         = response.GetResponseStream();
            StreamReader reader             = new StreamReader(dataStream);
            string       responseFromServer = reader.ReadToEnd();
            var          myresponse         = JsonConvert.DeserializeObject <VocaDBGetData>(responseFromServer);

            response.Close();
            if (myresponse.items.Count == 0)
            {
                await init.ModifyAsync("nothing found uwu (Note: In weird cases it finds the song but still returns 0 results, since this crashes the bot, its not showing anything here)");

                return;
            }
            if (myresponse.items.Count > 1)
            {
                var embed2 = new DiscordEmbedBuilder
                {
                    Color       = new DiscordColor("#68D3D2"),
                    Title       = "TouhouDB Search",
                    Description = "Multiple entries were found, select one!"
                };
                int      an    = 0;
                string[] nums  = { ":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":keycap_ten:" };
                string   songs = "";
                var      blank = DiscordEmoji.FromGuildEmote(ctx.Client, 435447550196318218);
                foreach (var entries in myresponse.items)
                {
                    songs += $"React {DiscordEmoji.FromName(ctx.Client, nums[an])} for {entries.name} by {entries.artistString} \n";
                    await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, nums[an]));

                    an++;
                }
                embed2.AddField("Found Songs", songs);
                await init.ModifyAsync("", embed : embed2.Build());

                var one   = DiscordEmoji.FromName(ctx.Client, ":one:");
                var two   = DiscordEmoji.FromName(ctx.Client, ":two:");
                var three = DiscordEmoji.FromName(ctx.Client, ":three:");
                var four  = DiscordEmoji.FromName(ctx.Client, ":four:");
                var five  = DiscordEmoji.FromName(ctx.Client, ":five:");
                var six   = DiscordEmoji.FromName(ctx.Client, ":six:");
                var seven = DiscordEmoji.FromName(ctx.Client, ":seven:");
                var eight = DiscordEmoji.FromName(ctx.Client, ":eight:");
                var nine  = DiscordEmoji.FromName(ctx.Client, ":nine:");
                var ten   = DiscordEmoji.FromName(ctx.Client, ":keycap_ten:");
                try {
                    var reSelect = await interactivity.WaitForReactionAsync(xe => (xe.Emoji == one || xe.Emoji == two || xe.Emoji == three || xe.Emoji == four || xe.Emoji == five || xe.Emoji == six || xe.Emoji == seven || xe.Emoji == eight || xe.Emoji == nine || xe.Emoji == ten) && xe.Message == init, ctx.Message.Author, TimeSpan.FromSeconds(60));

                    if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":one:"))
                    {
                        select = 0;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":two:"))
                    {
                        select = 1;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":three:"))
                    {
                        select = 2;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":four:"))
                    {
                        select = 3;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":five:"))
                    {
                        select = 4;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":six:"))
                    {
                        select = 5;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":seven:"))
                    {
                        select = 6;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":eight:"))
                    {
                        select = 7;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":nine:"))
                    {
                        select = 8;
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":keycap_ten:"))
                    {
                        select = 9;
                    }
                }
                catch
                {
                    return;
                }
                await init.DeleteAllReactionsAsync();
            }
            HttpWebRequest drequest = (HttpWebRequest)WebRequest.Create("https://touhoudb.com/api/songs/" + myresponse.items[select].id + "/derived?lang=English");

            drequest.Method = "GET";
            drequest.Accept = "application/json";
            HttpWebResponse dresponse = (HttpWebResponse)drequest.GetResponse();

            if (!((int)dresponse.StatusCode == 200))
            {
                await ctx.RespondAsync("Song not found");

                return;
            }
            Stream       ddataStream         = dresponse.GetResponseStream();
            StreamReader dreader             = new StreamReader(ddataStream);
            string       dresponseFromServer = dreader.ReadToEnd();

            dresponse.Close();
            var ddresponse = JsonConvert.DeserializeObject <List <VTUDBrGet> >(dresponseFromServer);
            int oof2       = myresponse.items[select].pvs.FindIndex(x => x.url.Contains("youtu"));
            int oof3       = myresponse.items[select].pvs.FindIndex(x => x.url.Contains("nico"));

            BaseiInfo(ctx, init, select, myresponse, ddresponse);
            await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":pushpin:"));

            if (myresponse.items[select].lyrics.Count != 0)
            {
                await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":page_facing_up:"));
            }
            if (myresponse.items[select].pvs.Count != 0)
            {
                await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":movie_camera:"));
            }
            if (ddresponse.Count != 0)
            {
                await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:"));
            }
            await init.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":x:"));

            bool loop = true;

            while (loop == true)
            {
                var emoji  = DiscordEmoji.FromName(ctx.Client, ":pushpin:");
                var emoji2 = DiscordEmoji.FromName(ctx.Client, ":page_facing_up:");
                var emoji3 = DiscordEmoji.FromName(ctx.Client, ":movie_camera:");
                var emoji4 = DiscordEmoji.FromName(ctx.Client, ":x:");
                var emoji5 = DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:");
                try
                {
                    var reSelect = await interactivity.WaitForReactionAsync(xe => (xe.Emoji == emoji || xe.Emoji == emoji2 || xe.Emoji == emoji3 || xe.Emoji == emoji4 || xe.Emoji == emoji5) && xe.Message == init, ctx.Message.Author, TimeSpan.FromSeconds(123));

                    if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":pushpin:"))
                    {
                        BaseiInfo(ctx, init, select, myresponse, ddresponse);
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":page_facing_up:"))
                    {
                        LyricEm(ctx, init, select, myresponse, ddresponse);
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":movie_camera:"))
                    {
                        PVShowInfo(ctx, init, select, myresponse, ddresponse, oof2);
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":revolving_hearts:"))
                    {
                        Derratives(ctx, init, select, myresponse, ddresponse);
                    }
                    else if (reSelect.Result.Emoji == DiscordEmoji.FromName(ctx.Client, ":x:"))
                    {
                        loop = false;
                        await init.DeleteAllReactionsAsync();
                    }
                    else
                    {
                        loop = false;
                        await init.DeleteAllReactionsAsync();
                    }
                }
                catch
                {
                    return;
                }
            }
        }
Beispiel #58
0
 private void DoWebRequest(Uri uri)
 {
     WebRequest.Create(uri).GetResponse().Close();
 }
Beispiel #59
0
    public string SendXMLRequest(string URL, string SOAPAction, string xmlRequest, ref string Status, ref bool FailFlag, NetworkCredential networkCreds = null)
    {
        // For SSL we need to say we trust the cert.
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                delegate
                {
                    return true;
                }
                );
        
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
        req.Method = "POST";
        req.ContinueTimeout = ServiceConnectionTimeOut <= 0 ? 350 : ServiceConnectionTimeOut;
        req.ContentType = "text/xml;charset=UTF-8";
        req.Headers.Add("SOAPAction", SOAPAction);
        req.Proxy = WebRequest.GetSystemWebProxy();

        if (networkCreds == null)
        {
            req.UseDefaultCredentials = true;
            req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
        }
        else
        {
            //customized for ATT D2 Architecture to Pass Network Credentials
            req.UseDefaultCredentials = false;
            req.Credentials = networkCreds;
            //customized for ATT D2 Architecture
        }

        byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
        req.ContentLength = reqBytes.Length;
        
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(reqBytes, 0, reqBytes.Length);
            }

        HttpWebResponse resp;
        string xmlResponse = null;
        try
        {

            resp = (HttpWebResponse)req.GetResponse();

            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                xmlResponse = sr.ReadToEnd();
            }
            Status = resp.StatusDescription;
            return xmlResponse;
        }
        catch (WebException ex)
        {
            Status = ex.Message;
            FailFlag = true;

            using (var stream = ex.Response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                xmlResponse = reader.ReadToEnd();
                return xmlResponse;
            }
        }
    }    
Beispiel #60
0
        static void handleException(Exception ex)
        {
            if (ex.Message == "Safe handle has been closed")
            {
                return;
            }

            MissionPlanner.Utilities.Tracking.AddException(ex);

            log.Debug(ex.ToString());

            GetStackTrace(ex);

            // hyperlinks error
            if (ex.Message == "Requested registry access is not allowed." ||
                ex.ToString().Contains("System.Windows.Forms.LinkUtilities.GetIELinkBehavior"))
            {
                return;
            }
            if (ex.Message == "The port is closed.")
            {
                CustomMessageBox.Show("Serial connection has been lost");
                return;
            }
            if (ex.Message == "A device attached to the system is not functioning.")
            {
                CustomMessageBox.Show("Serial connection has been lost");
                return;
            }
            if (ex.GetType() == typeof(OpenTK.Graphics.GraphicsContextException))
            {
                CustomMessageBox.Show("Please update your graphics card drivers. Failed to create opengl surface\n" + ex.Message);
                return;
            }
            if (ex.GetType() == typeof(MissingMethodException) || ex.GetType() == typeof(TypeLoadException))
            {
                CustomMessageBox.Show("Please Update - Some older library dlls are causing problems\n" + ex.Message);
                return;
            }
            if (ex.GetType() == typeof(ObjectDisposedException) || ex.GetType() == typeof(InvalidOperationException))
            // something is trying to update while the form, is closing.
            {
                log.Error(ex);
                return; // ignore
            }
            if (ex.GetType() == typeof(FileNotFoundException) || ex.GetType() == typeof(BadImageFormatException))
            // i get alot of error from people who click the exe from inside a zip file.
            {
                CustomMessageBox.Show(
                    "You are missing some DLL's. Please extract the zip file somewhere. OR Use the update feature from the menu " +
                    ex.ToString());
                // return;
            }
            // windows and mono
            if (ex.StackTrace != null && ex.StackTrace.Contains("System.IO.Ports.SerialStream.Dispose") ||
                ex.StackTrace != null && ex.StackTrace.Contains("System.IO.Ports.SerialPortStream.Dispose"))
            {
                log.Error(ex);
                return; // ignore
            }

            log.Info("Th Name " + Thread.Name);

            DialogResult dr =
                CustomMessageBox.Show("An error has occurred\n" + ex.ToString() + "\n\nReport this Error???",
                                      "Send Error", MessageBoxButtons.YesNo);

            if (DialogResult.Yes == dr)
            {
                try
                {
                    string data = "";
                    foreach (System.Collections.DictionaryEntry de in ex.Data)
                    {
                        data += String.Format("-> {0}: {1}", de.Key, de.Value);
                    }

                    string message = "";

                    try
                    {
                        Controls.InputBox.Show("Message", "Please enter a message about this error if you can.",
                                               ref message);
                    }
                    catch
                    {
                    }

                    // Create a request using a URL that can receive a post.
                    WebRequest request = WebRequest.Create("http://vps.oborne.me/mail.php");
                    request.Timeout = 10000; // 10 sec
                    // Set the Method property of the request to POST.
                    request.Method = "POST";
                    // Create POST data and convert it to a byte array.
                    string postData = "message=" + Environment.OSVersion.VersionString + " " +
                                      System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
                                      + " " + Application.ProductVersion
                                      + "\nException " + ex.ToString().Replace('&', ' ').Replace('=', ' ')
                                      + "\nStack: " + ex.StackTrace.ToString().Replace('&', ' ').Replace('=', ' ')
                                      + "\nTargetSite " + ex.TargetSite + " " + ex.TargetSite.DeclaringType
                                      + "\ndata " + data
                                      + "\nmessage " + message.Replace('&', ' ').Replace('=', ' ');
                    byte[] byteArray = Encoding.ASCII.GetBytes(postData);
                    // Set the ContentType property of the WebRequest.
                    request.ContentType = "application/x-www-form-urlencoded";
                    // Set the ContentLength property of the WebRequest.
                    request.ContentLength = byteArray.Length;
                    // Get the request stream.
                    using (Stream dataStream = request.GetRequestStream())
                    {
                        // Write the data to the request stream.
                        dataStream.Write(byteArray, 0, byteArray.Length);
                    }
                    // Get the response.
                    using (WebResponse response = request.GetResponse())
                    {
                        // Display the status.
                        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                        // Get the stream containing content returned by the server.
                        using (Stream dataStream = response.GetResponseStream())
                        {
                            // Open the stream using a StreamReader for easy access.
                            using (StreamReader reader = new StreamReader(dataStream))
                            {
                                // Read the content.
                                string responseFromServer = reader.ReadToEnd();
                                // Display the content.
                                Console.WriteLine(responseFromServer);
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.ToString());
                    log.Error(exp);
                    CustomMessageBox.Show("Could not send report! Typically due to lack of internet connection.");
                }
            }
        }