Пример #1
0
		public static string Login(string apiKey, string username, string password)
		{
			string response = ResponseTool.CheckAPIKey(apiKey, clientAPIKey);
			if (response != null) return response;

			using (var conn = DataManager.CreateConnectionObject())
			{
				conn.Open();
				using (var command = conn.CreateCommand())
				{
					string passwordEncrypted = SecurityManager.Hash(password);
					command.CommandText = string.Format("SELECT ID FROM Clients WHERE Username = '******' and Password = '******'", username, passwordEncrypted);
					using (var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var webResponse = new WebResponse(ResponseTypes.Succeeded)
							{
								ClientID = reader["ID"].ToString()
							};
							return ResponseTool.GenerateXML(webResponse);
						}
						else
						{
							var webResponse = new WebResponse(ResponseTypes.Error)
							{
								ErrorMessage = "Failed to find client"
							};
							return ResponseTool.GenerateXML(webResponse);
						}
					}
				}
			}
		}
Пример #2
0
        public async Task<IWebStreamResponse> GetWebStreamAsync(Uri url, bool waitForContent, CancellationToken cancellationToken,
            Uri referrer = null, long? from = null, long? to = null, WebResponse webResponse = null)
        {
            var completionOption = waitForContent ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead;

            if (null == referrer && null == from && null == to)
            {
                //Debug.WriteLine("HttpClientWebReader.GetWebStreamAsync() url {0} wait {1}", url, waitForContent);

                var response = await _httpClient.GetAsync(url, completionOption, cancellationToken).ConfigureAwait(false);

                Update(url, ContentKind.Unknown, response, webResponse);

                return new HttpClientWebStreamResponse(response);
            }
            else
            {
                //Debug.WriteLine("HttpClientWebReader.GetWebStreamAsync() url {0} wait {1} referrer {2} [{3}-{4}]",
                //    url, waitForContent, null == referrer ? "<none>" : referrer.ToString(), from, to);

                var request = new HttpRequestMessage(HttpMethod.Get, url);

                var response = await _httpClient.SendAsync(request, completionOption, cancellationToken, referrer, from, to).ConfigureAwait(false);

                Update(url, ContentKind.Unknown, response, webResponse);

                return new HttpClientWebStreamResponse(request, response);
            }
        }
Пример #3
0
        /// <summary>
        /// Builds a document from the content of the web response.
        /// A warning is logged if an exception is thrown while parsing the XML content
        /// (for instance when the content is not a valid XML and can't be parsed).
        /// @throws IOException if the page could not be created
        /// @throws SAXException if the parsing fails
        /// @throws ParserConfigurationException if a DocumentBuilder cannot be created
        /// </summary>
        /// <param name="WebResponse">the response from the server</param>
        /// <returns>the parse result</returns>
        public static XmlDocument BuildDocument(WebResponse webResponse)
        {
            XmlDocument xml = new XmlDocument();
            if (webResponse == null)
            {
                return xml;
            }

            InputStreamReader reader = new InputStreamReader(webResponse.GetContentAsStream(), Encoding.GetEncoding(webResponse.GetContentCharset()));

            // we have to do the blank input check and the parsing in one step
            TrackBlankContentReader tracker = new TrackBlankContentReader(reader);

            try
            {
                xml.Load(tracker);
                return xml;
            }
            catch (XmlException e)
            {
                if (tracker.WasBlank)
                {
                    return new XmlDocument();
                }
                throw e;
            }
        }
Пример #4
0
 /// <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("mb.aspx")) {
         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;
 }
        public static WebResponse ExtractResponse( HttpWebResponse response, string filename )
        {
            WebResponse webResponse = null;
            Stream streamResponse = response.GetResponseStream();

            #if !SILVERLIGHT
            if ( response.ContentEncoding.ToLower().Contains( "deflate" ) )
                streamResponse = new DeflateStream( streamResponse, CompressionMode.Decompress );
            else if ( response.ContentEncoding.ToLower().Contains( "gzip" ) )
                streamResponse = new GZipStream( streamResponse, CompressionMode.Decompress );
            #endif

            StreamReader streamRead = null;
            try
            {
                webResponse = new WebResponse();
                webResponse.ResponseBytes = NetworkUtils.StreamToByteArray( streamResponse );
                webResponse.ResponseString = NetworkUtils.ByteArrayToStr( webResponse.ResponseBytes );

                if ( !string.IsNullOrEmpty( filename ) )
                    MXDevice.File.Save(filename, webResponse.ResponseBytes);
            }
            finally
            {
                // Close the stream object
                if ( streamResponse != null )
                    streamResponse.Close();

                if ( streamRead != null )
                    streamRead.Close();
            }

            return webResponse;
        }
Пример #6
0
            private void set_option(string rel)
            {
                string url = "http://" + URI + "/web/cgi-bin/hi3510/param.cgi?"+rel+"&usr="******"&pwd=" + Password;

                Console.WriteLine("Call "+url+" - start");
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create (url);
                req.KeepAlive = false;
                req.Headers.Add ("Accept-Encoding", "gzip,deflate");
                req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                req.UseDefaultCredentials = true;
                req.Credentials = new NetworkCredential (Login, Password);
                req.Proxy = null;
                req.Timeout = 1000;
                WebResponse resp = null;
                req.KeepAlive = false;

                pause = true;
                try{
                    resp = req.GetResponse();
                    resp.Close();
                } catch(Exception e) {
                    Console.WriteLine (e.Message);
                }

                req = null;

                Console.WriteLine("Call "+url+" - end");
            }
		/// <summary>
		/// Handels the incomming CKFinder command.
		/// </summary>
		/// <param name="context">The incoming <see cref="IMansionWebContext"/>.</param>
		/// <param name="response"> </param>
		/// <exception cref="ConnectorException">Thrown when an error occured while handling the command.</exception>
		public void Handle(IMansionWebContext context, WebResponse response)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (response == null)
				throw new ArgumentNullException("response");

			try
			{
				//set values
				Request = context.Request;
				Response = response;

				// get the upload service
				AssetService = context.Nucleus.ResolveSingle<IAssetService>();

				// get the asset type
				AssetType = AssetService.ParseResourceType(context, Request.RequestUrl.QueryString["type"] ?? string.Empty);

				// get the current folder
				CurrentAssetFolder = AssetService.ParseFolder(context, AssetType, Request.RequestUrl.QueryString["currentFolder"] ?? "/");

				// invoke concrete implementation
				DoHandle(context);
			}
			catch (ThreadAbortException)
			{
				// thread is aborted, so don't throw any new exceptions
			}
			catch (Exception)
			{
				throw new ConnectorException(ErrorCodes.Unknown);
			}
		}
Пример #8
0
 public WebResponse GetResponse()
 {
     MemoryStream memoryStream = (MemoryStream) base.GetRequestStream();
     int send = _socket.Send(memoryStream.ToArray());
     Thread.Sleep(2000);
     WebResponse response = new WebResponse(_socket);
     return response;
 }
Пример #9
0
		public WebException(string message, 
				    Exception innerException,
		   		    WebExceptionStatus status, 
		   		    WebResponse response)
			: base (message, innerException)
		{
			this.status = status;
			this.response = response;
		}
Пример #10
0
        public async Task<IWebStreamResponse> GetWebStreamAsync(Uri url, bool waitForContent, CancellationToken cancellationToken,
            Uri referrer = null, long? from = null, long? to = null, WebResponse webResponse = null)
        {
            var request = _webReaderManager.CreateRequest(url, referrer, this, ContentType, allowBuffering: waitForContent, fromBytes: from, toBytes: to);

            var response = await _webReaderManager.GetAsync(request, cancellationToken).ConfigureAwait(false);

            Update(url, response, webResponse);

            return new HttpConnectionWebStreamResponse(response);
        }
Пример #11
0
    public static string ReadWebResponse(WebResponse response)
    {
        string result = "";

        using (Stream stream = response.GetResponseStream())
        {
            StreamReader sr = new StreamReader(stream);
            result = sr.ReadToEnd();
            sr.Close();
        }
        return result;
    }
        public void ShouldReturnEmptyListIfInvalid()
        {
            var response = new WebResponse<IList<SourceSystem>>
            {
                IsValid = false,
                Message = new List<SourceSystem> { new SourceSystem() }
            };

            var result = response.HandleResponse();

            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Count);
        }
        public void ShouldReturnItemsInResponseIfValid()
        {
            var response = new WebResponse<IList<SourceSystem>>
            {
                IsValid = true,
                Message = new List<SourceSystem> { new SourceSystem(), new SourceSystem() }
            };

            var result = response.HandleResponse();

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);
        }
Пример #14
0
		public static string CreateUser(string apiKey, string gameID, string username, string password)
		{
			string response = ResponseTool.CheckAPIKey(apiKey, gameAPIKey);
			if (response != null) return response;

			using (var conn = DataManager.CreateConnectionObject())
			{
				conn.Open();
				using (var command = conn.CreateCommand())
				{
					// make sure username doesn't already exist
					command.CommandText = string.Format("SELECT ID FROM Users WHERE GameID = '{0}' and Username = '******'", gameID, username);
					using (var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var webResponse = new WebResponse(ResponseTypes.Error)
							{
								ErrorMessage = "Username already exists"
							};
							return ResponseTool.GenerateXML(webResponse);
						}
					}

					// create account
					string passwordEncrypted = SecurityManager.Hash(password);
					var userID = Guid.NewGuid();
					string values = string.Format("('{0}', '{1}', '{2}', '{3}', '{4}')", userID, gameID, username, passwordEncrypted, DateTime.UtcNow);
					command.CommandText = "INSERT INTO Users (ID, GameID, Username, Password, DateCreated) VALUES " + values;
					if (command.ExecuteNonQuery() == 1)
					{
						var webResponse = new WebResponse(ResponseTypes.Succeeded)
						{
							UserID = userID.ToString(),
							Username = username
						};
						return ResponseTool.GenerateXML(webResponse);
					}
					else
					{
						var webResponse = new WebResponse(ResponseTypes.Error)
						{
							ErrorMessage = "Failed to properly create user"
						};
						return ResponseTool.GenerateXML(webResponse);
					}
				}
			}
		}
    /// <summary>
    /// Gets the web response as a XML document
    /// </summary>
    protected static string GetWebResponseAsText(WebResponse response)
    {
        string streamText = "";
        var responseStream = response.GetResponseStream();
        using (responseStream)
        {
            var streamReader = new StreamReader(responseStream);
            using (streamReader)
            {
                streamText = streamReader.ReadToEnd();
                streamReader.Close();
            }
            responseStream.Close();
        }

        return streamText;
    }
Пример #16
0
        public static WebResponse ValidateResponse( WebResponse response, WebResponseType[] validTypes, string message )
        {
            var valid = false;

            foreach ( var responseType in validTypes ) {
                if ( response.ResponseType == responseType ) {
                    valid = true;
                    break;
                }
            }

            if ( !valid ) {
                throw UnexpectedWebResponseGenerator.CreateException( message, response );
            }

            return response;
        }
        public static Exception CreateException( string message, WebResponse response )
        {
            Exception exception;

            switch ( response.ResponseType ) {

                case WebResponseType.Exception:
                    var exceptionResponse = (ExceptionWebResponse)response;

                    exception = exceptionResponse.Exception;
                    break;

                case WebResponseType.Html:
                    exception = new InvalidOperationException( NScrapeResources.UnexpectedHtmlPage );
                    break;

                case WebResponseType.Image:
                    exception = new InvalidOperationException( NScrapeResources.UnexpectedImage );
                    break;

                case WebResponseType.Unsupported:
                    var unsupportedResponse = (UnsupportedWebResponse)response;

                    exception = new WebException( string.Format( CultureInfo.CurrentCulture, NScrapeResources.UnsupportedResponseContentType, unsupportedResponse.ContentType ) );
                    break;

                case WebResponseType.Redirect:
                    exception = new InvalidOperationException( NScrapeResources.UnexpectedRedirect );
                    break;

                case WebResponseType.PlainText:
                    exception = new InvalidOperationException( NScrapeResources.UnexpectedPlainText );
                    break;

                case WebResponseType.Xml:
                    exception = new InvalidOperationException( NScrapeResources.UnexpectedXml );
                    break;

                default:
                    exception = new WebException( string.Format( CultureInfo.CurrentCulture, NScrapeResources.UnsupportedResponseType, response.ResponseType ) );
                    break;
            }

            return new WebException( message, exception );
        }
Пример #18
0
		public static string RequestScores(string apiKey, string leaderboardID, string offset, string range, string sortOrder)
		{
			string response = ResponseTool.CheckAPIKey(apiKey, gameAPIKey);
			if (response != null) return response;

			using (var conn = DataManager.CreateConnectionObject())
			{
				conn.Open();
				using (var command = conn.CreateCommand())
				{
					var webResponse = new WebResponse(ResponseTypes.Succeeded);
					webResponse.Scores = new List<WebResponse_Score>();

					// get all leaderboard usersIDs
					command.CommandText = string.Format("SELECT ID, UserID, Score FROM Scores WHERE LeaderboardID = '{0}' ORDER BY Score {3} OFFSET {1} ROWS FETCH NEXT {2} ROWS ONLY", leaderboardID, offset, range, sortOrder == "Ascending" ? "ASC" : "DESC");
					using (var reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							webResponse.Scores.Add(new WebResponse_Score()
							{
								ID = reader["ID"].ToString(),
								UserID = reader["UserID"].ToString(),
								Score = long.Parse(reader["Score"].ToString())
							});
						}
					}

					// get all usernames for IDs
					foreach (var score in webResponse.Scores)
					{
						command.CommandText = string.Format("SELECT Username FROM Users WHERE ID = '{0}'", score.UserID);
						using (var reader = command.ExecuteReader())
						{
							while (reader.Read())
							{
								score.Username = reader["Username"].ToString();
							}
						}
					}

					return ResponseTool.GenerateXML(webResponse);
				}
			}
		}
		internal HttpResponseMessage(WebResponse response, HttpRequestMessage request)
		{
			var stream = response.GetResponseStream();
			if (stream != null)
				Content = new StreamContent(stream) { Headers = new HttpContentHeaders(response.Headers) };
			if (response.SupportsHeaders)
			{
				Headers = new HttpResponseHeaders(response.Headers);
			}
			if (response is HttpWebResponse)
			{
				var httpResponse = response as HttpWebResponse;
				StatusCode = httpResponse.StatusCode;
				IsSuccessStatusCode = ((int)StatusCode >= 200 && (int)StatusCode <= 299);
				ReasonPhrase = httpResponse.StatusDescription;
			}
			RequestMessage = request;
		}
Пример #20
0
		public static string CreateGame(string apiKey, string clientID, string name)
		{
			string response = ResponseTool.CheckAPIKey(apiKey, clientAPIKey);
			if (response != null) return response;

			using (var conn = DataManager.CreateConnectionObject())
			{
				conn.Open();
				using (var command = conn.CreateCommand())
				{
					// make sure name doesn't already exist
					command.CommandText = string.Format("SELECT ID FROM Games WHERE Name = '{0}'", name);
					using (var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var webResponse = new WebResponse(ResponseTypes.Error)
							{
								ErrorMessage = "Game Name already exists"
							};
							return ResponseTool.GenerateXML(webResponse);
						}
					}

					// create account
					string values = string.Format("(NEWID(), '{0}', '{1}', '{2}')", clientID, name, DateTime.UtcNow);
					command.CommandText = "INSERT INTO Games (ID, ClientID, Name, DateCreated) VALUES " + values;
					if (command.ExecuteNonQuery() == 1)
					{
						var webResponse = new WebResponse(ResponseTypes.Succeeded);
						return ResponseTool.GenerateXML(webResponse);
					}
					else
					{
						var webResponse = new WebResponse(ResponseTypes.Error)
						{
							ErrorMessage = "Failed to properly create game"
						};
						return ResponseTool.GenerateXML(webResponse);
					}
				}
			}
		}
    /// <summary>
    /// Gets the web response as a XML document
    /// </summary>
    protected static System.Xml.XmlDocument GetWebResponseAsXml(WebResponse response)
    {
        string streamText = "";
        var responseStream = response.GetResponseStream();
        using (responseStream)
        {
            var streamReader = new StreamReader(responseStream);
            using (streamReader)
            {
                streamText = streamReader.ReadToEnd();
                streamReader.Close();
            }
            responseStream.Close();
        }

        var xmlDoc = new System.Xml.XmlDocument();
        xmlDoc.LoadXml(streamText);
        return xmlDoc;
    }
Пример #22
0
        public async Task<byte[]> GetByteArrayAsync(Uri url, CancellationToken cancellationToken, WebResponse webResponse = null)
        {
            if (null != BaseAddress && !url.IsAbsoluteUri)
                url = new Uri(BaseAddress, url);

            using (var response = await _webReaderManager.SendAsync(url, this, cancellationToken).ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();

                Update(url, response, webResponse);

                using (var ms = new MemoryStream())
                {
                    await response.ContentReadStream.CopyToAsync(ms, 4096, cancellationToken).ConfigureAwait(false);

                    return ms.ToArray();
                }
            }
        }
Пример #23
0
        public IWebResponse Invoke(Ds3Request request)
        {
            int redirectCount = 0;

            using (var content = request.GetContentStream())
            {
                do
                {
                    if (sdkNetworkSwitch.TraceInfo) { Trace.WriteLine(string.Format(Resources.RequestLogging, request.GetType().ToString())); }
                    if (sdkNetworkSwitch.TraceVerbose) { Trace.WriteLine(request.getDescription(BuildQueryParams(request.QueryParams))); }

                    HttpWebRequest httpRequest = CreateRequest(request, content);
                    try
                    {
                        long send = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
                        var response = new WebResponse((HttpWebResponse)httpRequest.GetResponse());
                        long millis = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - send;
                        if (Is307(response))
                        {
                            redirectCount++;
                            if (sdkNetworkSwitch.TraceWarning) { Trace.Write(string.Format(Resources.Encountered307NTimes, redirectCount), "Ds3Network"); }
                        }
                        else
                        {
                            if (sdkNetworkSwitch.TraceInfo) { Trace.WriteLine(string.Format(Resources.ResponseLogging, response.StatusCode.ToString(), millis)); }
                            return response;
                        }
                    }
                    catch (WebException e)
                    {
                        if (e.Response == null)
                        {
                            throw e;
                        }
                        return new WebResponse((HttpWebResponse)e.Response);
                    }
                } while (redirectCount < _maxRedirects);
            }

            throw new Ds3RedirectLimitException(Resources.TooManyRedirectsException);
        }
Пример #24
0
        static async void CheckMD5(ProgressReporterDialogue frmProgressReporter, string url)
        {
            var baseurl = ConfigurationManager.AppSettings["UpdateLocation"];

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

            L10N.ReplaceMirrorUrl(ref baseurl);

            string responseFromServer = "";

            WebRequest request = WebRequest.Create(url);

            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+upgrade/(.*)", RegexOptions.IgnoreCase);

            if (regex.IsMatch(responseFromServer))
            {
                List <Tuple <string, string, Task <bool> > > tasklist = new List <Tuple <string, string, Task <bool> > >();

                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();

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

                    tasklist.Add(new Tuple <string, string, Task <bool> >(file, hash, ismatch));
                }

                log.Info("MD5File Running");

                foreach (var task in tasklist)
                {
                    string file = task.Item1;
                    string hash = task.Item2;
                    // check if existing matchs hash
                    bool match = await task.Item3;
                    if (!match)
                    {
                        log.Info("Newer File " + file);

                        // check is we have already downloaded and matchs hash
                        if (!MD5File(file + ".new", hash).Result)
                        {
                            if (frmProgressReporter != null)
                            {
                                frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Getting + file);
                            }

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

                            GetNewFile(frmProgressReporter, baseurl + subdir.Replace('\\', '/'), subdir,
                                       Path.GetFileName(file));

                            // check the new downloaded file matchs hash
                            if (!MD5File(file + ".new", hash).Result)
                            {
                                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);
                        }
                    }
                }
            }
        }
        private string sincronizacionContabilidadCompletada(asiento_contable asiento_contable)
        {
            client            = new HttpClient();
            accountingRequest = new AccountingRequest();

            accountingRequest.auxiliar    = "4";
            accountingRequest.moneda      = "DOP";
            accountingRequest.descripcion = "Integracion InventarioSDQ-Contabilidad.";

            List <AccountingDetalle> detalle           = new List <AccountingDetalle>();
            AccountingDetalle        accountingDetalle = new AccountingDetalle();

            accountingDetalle.numero_cuenta    = "6";
            accountingDetalle.tipo_transaccion = "DB";
            accountingDetalle.monto            = asiento_contable.monto;
            detalle.Add(accountingDetalle);

            accountingDetalle = new AccountingDetalle();
            accountingDetalle.numero_cuenta    = "82";
            accountingDetalle.tipo_transaccion = "CR";
            accountingDetalle.monto            = asiento_contable.monto;
            detalle.Add(accountingDetalle);

            accountingRequest.detalle = detalle;

            string URL         = " https://prjaccounting20190327125427.azurewebsites.net/api/accounting/post";
            string requestBody = new JavaScriptSerializer().Serialize(accountingRequest);

            Console.Out.WriteLine(">>>>> RESUEST BODY: ");
            Console.Out.WriteLine(requestBody);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.Method        = "POST";
            request.ContentType   = "application/json";
            request.ContentLength = requestBody.Length;
            using (Stream webStream = request.GetRequestStream())
                using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
                {
                    requestWriter.Write(requestBody);
                }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        Console.Out.WriteLine(response);
                        return(response);
                    }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

            return(null);
        }
Пример #26
0
        public override int DiscoverSubCategories(Category parentCategory)
        {
            string url = ((RssLink)parentCategory).Url;

            List <Category> categories = new List <Category>();
            string          webData    = GetWebData(url);

            webData = Helpers.StringUtils.GetSubString(webData, "main-section", "footer");
            int splitInd   = webData.IndexOf("orange");
            int nWithImage = 0;

            if (!string.IsNullOrEmpty(webData))
            {
                List <string> names = new List <string>();
                Match         m     = regEx_dynamicSubCategories.Match(webData);
                while (m.Success)
                {
                    RssLink cat = new RssLink();
                    cat.Name = HttpUtility.HtmlDecode(m.Groups["title"].Value);
                    if (!names.Contains(cat.Name))
                    {
                        cat.Url = m.Groups["url"].Value;
                        cat.HasSubCategories = false;
                        categories.Add(cat);
                        cat.ParentCategory = parentCategory;
                        names.Add(cat.Name);
                        if (splitInd == -1 || m.Index <= splitInd)
                        {
                            nWithImage++;
                        }
                    }
                    m = m.NextMatch();
                }

                if (parentCategory.Other != null)
                {
                    string pngName = (string)parentCategory.Other;
                    try
                    {
                        Bitmap png = null;

                        string bareFinalUrl = System.IO.Path.ChangeExtension(pngName, String.Empty);
                        for (int i = 0; i < nWithImage; i++)
                        {
                            string finalUrl = bareFinalUrl + '_' + i.ToString() + ".PNG";
                            categories[i].Thumb = finalUrl;
                            string imageLocation = Helpers.FileUtils.GetThumbFile(finalUrl);
                            if (!File.Exists(imageLocation))
                            {
                                if (png == null)
                                {
                                    WebRequest  request        = WebRequest.Create(pngName);
                                    WebResponse response       = request.GetResponse();
                                    Stream      responseStream = response.GetResponseStream();
                                    png = new Bitmap(responseStream);
                                }
                                int      newHeight = png.Height / nWithImage;
                                Bitmap   newPng    = new Bitmap(png.Width, newHeight);
                                Graphics g         = Graphics.FromImage(newPng);
                                g.DrawImage(png, 0, -i * newHeight);
                                g.Dispose();

                                newPng.Save(imageLocation);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Log.Info("image not found : " + pngName);
                    }
                }
                parentCategory.SubCategoriesDiscovered = true;
            }

            parentCategory.SubCategories = categories;
            return(parentCategory.SubCategories.Count);
        }
Пример #27
0
        // http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx
        private static string Decode(WebResponse w)
        {
            BufferManager bufferManager = BufferManager.Instance;

            //
            // first see if content length header has charset = calue
            //
            string charset = null;

            {
                string content_type = w.Headers["content-type"];

                if (content_type != null)
                {
                    int index = content_type.IndexOf("charset=");

                    if (index != -1)
                    {
                        charset = content_type.Substring(index + 8);
                    }
                }
            }

            // save data to a rawStream
            var rawStream = new BufferStream(bufferManager);

            using (Stream stream = w.GetResponseStream())
                using (var safeBuffer = bufferManager.CreateSafeBuffer(1024 * 4))
                {
                    int length;

                    while ((length = stream.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0)
                    {
                        rawStream.Write(safeBuffer.Value, 0, length);

                        if (rawStream.Length > 1024 * 1024 * 32)
                        {
                            throw new Exception("too large");
                        }
                    }
                }

            //
            // if ContentType is null, or did not contain charset, we search in body
            //
            if (charset == null)
            {
                rawStream.Seek(0, SeekOrigin.Begin);

                using (StreamReader reader = new StreamReader(new WrapperStream(rawStream, true), Encoding.ASCII))
                {
                    string meta = reader.ReadToEnd();

                    if (!string.IsNullOrWhiteSpace(meta))
                    {
                        int start_index = meta.IndexOf("charset=");

                        if (start_index != -1)
                        {
                            int end_index = meta.IndexOf("\"", start_index);

                            if (end_index != -1)
                            {
                                start_index += 8;

                                charset = meta.Substring(start_index, end_index - start_index);
                            }
                        }
                    }
                }
            }

            Encoding encoding = null;

            if (charset == null)
            {
                encoding = Encoding.UTF8; //default encoding
            }
            else
            {
                try
                {
                    encoding = Encoding.GetEncoding(charset);
                }
                catch (Exception)
                {
                    encoding = Encoding.UTF8;
                }
            }

            rawStream.Seek(0, SeekOrigin.Begin);

            using (StreamReader reader = new StreamReader(rawStream, encoding))
            {
                return(reader.ReadToEnd());
            }
        }
Пример #28
0
        /// <summary>
        /// Turn on and off MassRuns in project level
        /// </summary>
        /// <param name="Run"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        public static void _ExecuteMassRuns(bool Run = true, int ProjectId = 0)
        {
            // For more information eead this post on Autodesk's blog
            // http://autodesk.typepad.com/bpa/2013/05/new-update-on-gbs-adn-api.html

            // Get Uri for updating mass run in project level
            // You can control mass run either in project level or in user level. The process is similar but the Uri is different.
            // To update massrun is user level look for APIV1Uri.ControlMassRunInUserLevel
            string ControlMassRuns = GBSUri.GBSAPIUri +
                                     string.Format(APIV1Uri.ControlMassRunInProjectLevel, ProjectId.ToString());

            // First Get request is to get the permission
            // Sign URL using Revit auth
            var MassRunRequestUri = revitAuthProvider.SignRequest(ControlMassRuns, HttpMethod.Get, null);

            // Send the request to GBS
            var request = (HttpWebRequest)System.Net.WebRequest.Create(MassRunRequestUri);

            request.Method = "GET";
            // request.PreAuthenticate = true;
            request.ContentType = "application/xml";

            // get the response
            WebResponse response = request.GetResponse();

            // read the response
            // StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            // reader.ReadToEnd();

            // Now that we have the permission let's change it based on user's request for this project
            // Sign URL using Revit auth
            var MassRunUpdateUri = revitAuthProvider.SignRequest(ControlMassRuns, HttpMethod.Put, null);

            // Send the request to GBS
            var changeRequest = (HttpWebRequest)System.Net.WebRequest.Create(MassRunUpdateUri);

            changeRequest.Method          = "PUT";
            changeRequest.PreAuthenticate = true;
            changeRequest.ContentType     = "application/xml";

            using (Stream requestStream = changeRequest.GetRequestStream())


                using (StreamWriter requestWriter = new StreamWriter(requestStream))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        DataContractSerializer serializer = new DataContractSerializer((typeof(bool)));

                        // Here we set up the parameters
                        serializer.WriteObject(ms, Run);

                        byte[] postData = ms.ToArray();
                        requestStream.Write(postData, 0, postData.Length);
                    }
                }

            // get response
            WebResponse changeResponse = changeRequest.GetResponse();

            // read the response
            //using (StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            //{
            //    responseReader.ReadToEnd();
            //}
        }
Пример #29
0
        public ActionResult AddSrNo()
        {
            try
            {
                string devType = Request.Params["prodFlag"].ToString();
                Response.StatusCode = 200;
                string srNos = Request.Params["inputSrNum"].Trim().Replace(" ", "");

                if (srNos == null || srNos.Equals("") || srNos.Trim().Length < 6)
                {
                    Response.StatusCode = 400;
                    return(null);
                }

                string req_soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://AccessComputech.com/MGMT_INFO/\">";
                req_soap = req_soap + Convert.ToString("<soapenv:Header/>");
                req_soap = req_soap + Convert.ToString("<soapenv:Body>");
                req_soap = req_soap + Convert.ToString("<tem:FilterSerialNumbers_MULTI>");
                req_soap = req_soap + Convert.ToString("<tem:argSrNos>");
                req_soap = req_soap + srNos.Trim().Replace("\n", "").Replace("\r", "").Replace("\t", "");
                req_soap = req_soap + Convert.ToString("</tem:argSrNos>");
                req_soap = req_soap + Convert.ToString("</tem:FilterSerialNumbers_MULTI>");
                req_soap = req_soap + Convert.ToString("</soapenv:Body>");
                req_soap = req_soap + Convert.ToString("</soapenv:Envelope>");

                HttpWebRequest webRequest__1 = (HttpWebRequest)(WebRequest.Create("https://www.acpl.in.net/FM220_REGISTRATION_SERVICE/MgmtInfoPage.asmx"));
                webRequest__1.Headers.Add("SOAPAction", "\"http://AccessComputech.com/MGMT_INFO/FilterSerialNumbers_MULTI\"");
                webRequest__1.Headers.Add("To", "https://www.acpl.in.net/FM220_REGISTRATION_SERVICE/MgmtInfoPage.asmx");
                webRequest__1.ContentType = "text/xml;charset=\"utf-8\"";
                webRequest__1.Accept      = "text/xml";
                webRequest__1.Method      = "POST";
                webRequest__1.Timeout     = 60000;

                using (Stream stm = webRequest__1.GetRequestStream())
                {
                    using (StreamWriter stmw = new StreamWriter(stm))
                    {
                        stmw.Write(req_soap);
                    }
                }
                WebResponse response = default(WebResponse);
                response = webRequest__1.GetResponse();
                Stream       str           = response.GetResponseStream();
                StreamReader sr            = new StreamReader(str);
                string       finalResponse = sr.ReadToEnd();
                string       res;
                using (XmlReader reader = XmlReader.Create(new StringReader(finalResponse)))
                {
                    reader.ReadToFollowing("FilterSerialNumbers_MULTIResult");
                    res = reader.ReadString();
                }
                string respToProc = HttpUtility.HtmlDecode(res);

                using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(respToProc)))
                {
                    reader.ReadToFollowing("ValidDevices");
                    validDevStr = reader.ReadString();

                    reader.ReadToFollowing("InvalidDevices");
                    invalidDevStr = reader.ReadString();

                    reader.ReadToFollowing("ActiveDevices");
                    activeDevStr = reader.ReadString();

                    reader.ReadToFollowing("LifeTimeDevices");
                    lifetimeStr = reader.ReadString();

                    reader.ReadToFollowing("BlockedDevices");
                    blockDevStr = reader.ReadString();
                }

                if (devType.Equals("1") || devType.Equals("2") || devType.Equals("3"))
                {
                    string[] inputStrArray = srNos.Split(',');
                    for (int i = 0; i < inputStrArray.Length; i++)
                    {
                        if (inputStrArray[i].ToUpper().StartsWith("D"))
                        {
                            Response.StatusCode = 400;
                            return(null);
                        }
                    }
                }

                if (devType.Equals("4") || devType.Equals("5"))
                {
                    string[] inputStrArray = srNos.Split(',');
                    for (int i = 0; i < inputStrArray.Length; i++)
                    {
                        if (inputStrArray[i].ToUpper().StartsWith("B"))
                        {
                            Response.StatusCode = 400;
                            return(null);
                        }
                    }
                }

                //if (validDevStr == null || validDevStr.Equals(""))
                //{
                //    //Device is not valid
                //    //ViewBag.Message = "Device is not valid";
                //    Response.StatusCode = 400;
                //    return null;
                //}
            }
            catch (Exception ex)
            {
                //Error response
                Response.StatusCode = 400;
            }

            return(View("DeviceSelectPage"));
        }
Пример #30
0
            private void InstallASI(ASIMod asiToInstall, InstalledASIMod oldASIToRemoveOnSuccess = null, Action operationCompletedCallback = null)
            {
                BackgroundWorker worker = new BackgroundWorker();

                worker.DoWork += (a, b) =>
                {
                    ASIModUpdateGroup g = getUpdateGroupByMod(asiToInstall);
                    string            destinationFilename  = $@"{asiToInstall.InstalledPrefix}-v{asiToInstall.Version}.asi";
                    string            cachedPath           = Path.Combine(CachedASIsFolder, destinationFilename);
                    string            destinationDirectory = MEDirectories.ASIPath(SelectedTarget);
                    if (!Directory.Exists(destinationDirectory))
                    {
                        Log.Information(@"Creating ASI directory: " + destinationDirectory);
                        Directory.CreateDirectory(destinationDirectory);
                    }
                    string finalPath = Path.Combine(destinationDirectory, destinationFilename);
                    string md5;
                    if (File.Exists(cachedPath))
                    {
                        //Check hash first
                        md5 = BitConverter.ToString(System.Security.Cryptography.MD5.Create().ComputeHash(File.ReadAllBytes(cachedPath))).Replace(@"-", "").ToLower();
                        if (md5 == asiToInstall.Hash)
                        {
                            Log.Information($@"Copying local ASI from library to destination: {cachedPath} -> {finalPath}");

                            File.Copy(cachedPath, finalPath, true);
                            operationCompletedCallback?.Invoke();
                            Analytics.TrackEvent(@"Installed ASI", new Dictionary <string, string>()
                            {
                                { @"Filename", Path.GetFileNameWithoutExtension(finalPath) }
                            });
                            return;
                        }
                    }
                    WebRequest request = WebRequest.Create(asiToInstall.DownloadLink);
                    Log.Information(@"Fetching remote ASI from server");

                    using WebResponse response = request.GetResponse();
                    MemoryStream memoryStream = new MemoryStream();
                    response.GetResponseStream().CopyTo(memoryStream);
                    //MD5 check on file for security
                    md5 = BitConverter.ToString(System.Security.Cryptography.MD5.Create().ComputeHash(memoryStream.ToArray())).Replace(@"-", "").ToLower();
                    if (md5 != asiToInstall.Hash)
                    {
                        //ERROR!
                        Log.Error(@"Downloaded ASI did not match the manifest! It has the wrong hash.");
                    }
                    else
                    {
                        Log.Information(@"Fetched remote ASI from server. Installing ASI to " + finalPath);
                        memoryStream.WriteToFile(finalPath);
                        Log.Information(@"ASI successfully installed.");
                        Analytics.TrackEvent(@"Installed ASI", new Dictionary <string, string>()
                        {
                            { @"Filename", Path.GetFileNameWithoutExtension(finalPath) }
                        });
                        if (!Directory.Exists(CachedASIsFolder))
                        {
                            Log.Information(@"Creating cached ASIs folder");
                            Directory.CreateDirectory(CachedASIsFolder);
                        }
                        Log.Information(@"Caching ASI to local ASI library: " + cachedPath);
                        File.WriteAllBytes(cachedPath, memoryStream.ToArray()); //cache it
                        if (oldASIToRemoveOnSuccess != null)
                        {
                            File.Delete(oldASIToRemoveOnSuccess.InstalledPath);
                        }
                    };
                };
                worker.RunWorkerCompleted += (a, b) =>
                {
                    if (b.Error != null)
                    {
                        Log.Error(@"Error occured in ASI installer thread: " + b.Error.Message);
                    }
                    RefreshASIStates();
                    operationCompletedCallback?.Invoke();
                };

                worker.RunWorkerAsync();
            }
Пример #31
0
        public ActionResult IndexPost()
        {
            ViewBag.Title = "Home Page";

            // Retrieve the claims for the current user
            ClaimsIdentity identity = (ClaimsIdentity)this.User.Identity;
            List <string>  claims   = new List <string>();

            foreach (Claim claim in identity.Claims)
            {
                claims.Add(string.Format("{0}: {1}", claim.Type, claim.Value));
            }
            ViewBag.Claims = claims;


            // Call API
            List <string>  results = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_serviceUrl);

            request.Method = "GET";
            request.Accept = "application/json";

            // Get the authentication cookie and add it to the API request
            // This is only necessary because we are calling the API from server-side code
            // If calling from client-side code, the browser would automatically send
            // the cookie with the AJAX request
            HttpCookie authCookie    = this.Request.Cookies["AllInOne"];
            Cookie     requestCookie = new Cookie(authCookie.Name, authCookie.Value, authCookie.Path);

            if (string.IsNullOrEmpty(authCookie.Domain))
            {
                requestCookie.Domain = "localhost";
            }
            else
            {
                requestCookie.Domain = authCookie.Domain;
            }
            CookieContainer cookieContainer = new CookieContainer();

            cookieContainer.Add(requestCookie);
            request.CookieContainer = cookieContainer;

            WebResponse response = request.GetResponse();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List <string>));

            results = (List <string>)serializer.ReadObject(response.GetResponseStream());
            response.Close();
            ViewBag.WebAPIClaims = results;

            // Call the Azure AD Graph
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            AuthenticationContext authContext = new AuthenticationContext(_authority, new NaiveSessionCache(userObjectID, this.HttpContext));
            ClientCredential      credential  = new ClientCredential(_clientId, _clientSecret);
            AuthenticationResult  result      = authContext.AcquireTokenSilentAsync(_graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)).Result;

            List <string> properties = new List <string>();

            request        = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/me?api-version=1.6", _graphResourceId, _tenant));
            request.Method = "GET";
            request.Accept = "application/json";

            // Add a "Bearer" token to the Authorization header containing the access token for the Azure AD Graph
            request.Headers.Add("Authorization", result.CreateAuthorizationHeader());
            response   = request.GetResponse();
            serializer = new DataContractJsonSerializer(typeof(List <string>));
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            JObject      jsonObject     = JObject.Parse(responseReader.ReadToEnd());

            response.Close();

            // Extract some properties of the current user from the Azure AD Graph profile
            properties.Add(string.Format("userPrincipalName: {0}", jsonObject["userPrincipalName"].Value <string>()));
            properties.Add(string.Format("displayName: {0}", jsonObject["displayName"].Value <string>()));
            properties.Add(string.Format("givenName: {0}", jsonObject["givenName"].Value <string>()));
            properties.Add(string.Format("surname: {0}", jsonObject["surname"].Value <string>()));
            ViewBag.Results = properties;

            return(View("Index"));
        }
        //
        // This optional method is only for protocols supporting a revalidation concept
        // For a retried request this method must be called again.
        //
        internal CacheValidationStatus GetRevalidateStatus (WebResponse response, Stream responseStream)
        {
            if (response == null)
                throw new ArgumentNullException("response");

            if (_ProtocolStatus == CacheValidationStatus.DoNotUseCache)
                return CacheValidationStatus.DoNotUseCache;

            // If we returned cached response, switch the state to not call cache anymore.
            if (_ProtocolStatus == CacheValidationStatus.ReturnCachedResponse)
            {
                _ProtocolStatus = CacheValidationStatus.DoNotUseCache;
                return _ProtocolStatus;
            }

            try {
                if(Logging.On) Logging.Enter(Logging.RequestCache, this, "GetRevalidateStatus", (_Validator == null? null: _Validator.Request));

                _Validator.FetchResponse(response);

                if (_ProtocolStatus != CacheValidationStatus.Continue && _ProtocolStatus != CacheValidationStatus.RetryResponseFromServer)
                {
                    if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_revalidation_not_needed, "GetRevalidateStatus()"));
                    return _ProtocolStatus;
                }
                CheckRetrieveOnResponse(responseStream);
            }
            finally {
                if(Logging.On) Logging.Exit(Logging.RequestCache, this, "GetRevalidateStatus", "result = " + _ProtocolStatus.ToString());
            }
            return _ProtocolStatus;
        }
Пример #33
0
        //
        // TODO:
        //    Handle other web responses (multi-output?)
        //
        object [] ReceiveResponse(WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
        {
            SoapMethodStubInfo msi           = message.MethodStubInfo;
            HttpWebResponse    http_response = response as HttpWebResponse;

            if (http_response != null)
            {
                HttpStatusCode code = http_response.StatusCode;

                if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError))
                {
                    string msg = "The request failed with HTTP status {0}: {1}";
                    msg = String.Format(msg, (int)code, code);
                    throw new WebException(msg, null, WebExceptionStatus.ProtocolError, http_response);
                }
                if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK))
                {
                    return(new object[0]);
                }
            }

            //
            // Remove optional encoding
            //
            string   ctype;
            Encoding encoding = WebServiceHelper.GetContentEncoding(response.ContentType, out ctype);

            ctype = ctype.ToLower(CultureInfo.InvariantCulture);
#if NET_2_0
            if ((!message.IsSoap12 || ctype != "application/soap+xml") && ctype != "text/xml")
#else
            if (ctype != "text/xml")
#endif
            { WebServiceHelper.InvalidOperation(
                  String.Format("Not supported Content-Type in the response: '{0}'", response.ContentType),
                  response, encoding); }

            message.ContentType     = ctype;
            message.ContentEncoding = encoding.WebName;

            Stream stream = response.GetResponseStream();

            if (extensions != null)
            {
                stream = SoapExtension.ExecuteChainStream(extensions, stream);
                message.SetStage(SoapMessageStage.BeforeDeserialize);
                SoapExtension.ExecuteProcessMessage(extensions, message, stream, false);
            }

            // Deserialize the response

            SoapHeaderCollection headers;
            object content;

            using (StreamReader reader = new StreamReader(stream, encoding, false)) {
                XmlTextReader xml_reader = new XmlTextReader(reader);

                WebServiceHelper.ReadSoapMessage(xml_reader, msi, SoapHeaderDirection.Out, message.IsSoap12, out content, out headers);
            }

#if NET_2_0
            if (content is Soap12Fault)
            {
                SoapException ex = WebServiceHelper.Soap12FaultToSoapException((Soap12Fault)content);
                message.SetException(ex);
            }
            else
#endif
            if (content is Fault)
            {
                Fault         fault = (Fault)content;
                SoapException ex    = new SoapException(fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
                message.SetException(ex);
            }
            else
            {
                message.OutParameters = (object[])content;
            }

            message.SetHeaders(headers);
            message.UpdateHeaderValues(this, message.MethodStubInfo.Headers);

            if (extensions != null)
            {
                message.SetStage(SoapMessageStage.AfterDeserialize);
                SoapExtension.ExecuteProcessMessage(extensions, message, stream, false);
            }

            if (message.Exception == null)
            {
                return(message.OutParameters);
            }
            else
            {
                throw message.Exception;
            }
        }
Пример #34
0
        public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

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


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

            wr.Method      = "POST";
            wr.KeepAlive   = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            wr.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            var nvc2 = new NameValueCollection();

            nvc2.Add("Accepts-Language", "en-us,en;q=0.5");
            wr.Headers.Add(nvc2);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;


            Stream rs = wr.GetRequestStream();

            bool   firstLoop        = true;
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

            foreach (string key in nvc.Keys)
            {
                if (firstLoop)
                {
                    rs.Write(boundarybytesF, 0, boundarybytesF.Length);
                    firstLoop = false;
                }
                else
                {
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                }
                string formitem      = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header         = string.Format(headerTemplate, paramName, new FileInfo(file).Name, contentType);

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);

            byte[] buffer    = new byte[4096];
            int    bytesRead = 0;

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;

            try
            {
                wresp = wr.GetResponse();
                Stream       stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
        }
Пример #35
0
        private string _doRequest(string path, string data = null, string method = "GET")
        {
            string strReturn = null;

            WebRequest request = WebRequest.Create("https://api.pingdom.com" + path);

            ((HttpWebRequest)request).UserAgent = "Pingdom Notifier by Dixcart";
            string authInfo = Properties.Settings.Default.Username + ":" + Properties.Settings.Default.Password;

            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Headers["Authorization"] = "Basic " + authInfo;
            request.Headers["App-Key"]       = "sp86t6xzpxffcf078e7q9auh9fz572dm";
            ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip;
            request.Method = method;
            if (method == "POST" && data != null)
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(data);
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
            }

            try
            {
                WebResponse response = request.GetResponse();
                switch (((HttpWebResponse)response).StatusCode)
                {
                case HttpStatusCode.OK:
                    //All went ok, handle the response.
                    ChangeIcon("green");
                    MyNotifyIcon.ToolTipText = "Connected";
                    Stream       receiveStream = response.GetResponseStream();
                    StreamReader readStream    = new StreamReader(receiveStream, Encoding.UTF8);
                    strReturn = readStream.ReadToEnd();
                    break;
                }
                response.Close();
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    switch (((HttpWebResponse)e.Response).StatusCode)
                    {
                    case HttpStatusCode.NotFound:
                        ChangeIcon("yellow");
                        //should never trigger in a controlled environ like this
                        break;

                    case HttpStatusCode.InternalServerError:
                        //There has been an error at pingdom's end.
                        ChangeIcon("yellow");
                        break;

                    case HttpStatusCode.Forbidden:
                    case HttpStatusCode.Unauthorized:
                        //Login details are wrong
                        ShowStandardBalloon("Login failed", "Please check login details are correct", "grey");
                        break;

                    default:
                        ShowStandardBalloon("Other Error", e.Message, "grey");
                        break;
                    }
                }
                else
                {
                    ShowStandardBalloon("Other Error", e.Message, "grey");
                }
            }
            catch (Exception e)
            {
                ShowStandardBalloon("Other Error", e.Message, "grey");
            }

            return(strReturn);
        }
Пример #36
0
        static void GetNewFile(ProgressReporterDialogue 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();

                        // update status
                        if (frmProgressReporter != null)
                        {
                            frmProgressReporter.UpdateProgressAndStatus(-1, Strings.Getting + file);
                        }

                        // 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(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)
                                {
                                    break;
                                }
                                bytes -= len;
                                fs.Write(buf1, 0, len);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    fail = ex;
                    attempt++;
                    continue;
                }

                // break if we have no exception
                break;
            }

            if (attempt == 2)
            {
                throw fail;
            }
        }
Пример #37
0
		internal Exception NotFound (string scheme, WebResponse wres)
		{
			if (scheme == "https")
				return new SecurityException ();

			return new WebException ("NotFound", null, WebExceptionStatus.UnknownError, wres);
		}
Пример #38
0
        private static bool updateCheck(ProgressReporterDialogue frmProgressReporter, string baseurl, string subdir)
        {
            bool          update = false;
            List <string> files  = new List <string>();

            // Create a request using a URL that can receive a post.
            log.Info(baseurl);
            WebRequest request = WebRequest.Create(baseurl);

            request.Timeout = 10000;
            // Set the Method property of the request to POST.
            request.Method = "GET";
            // Get the request stream.
            Stream dataStream; //= request.GetRequestStream();

            // 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.
                using (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.
                        Regex regex = new Regex("href=\"([^\"]+)\"", RegexOptions.IgnoreCase);

                        Uri baseuri = new Uri(baseurl, UriKind.Absolute);

                        if (regex.IsMatch(responseFromServer))
                        {
                            MatchCollection matchs = regex.Matches(responseFromServer);
                            for (int i = 0; i < matchs.Count; i++)
                            {
                                if (matchs[i].Groups[1].Value.ToString().Contains(".."))
                                {
                                    continue;
                                }
                                if (matchs[i].Groups[1].Value.ToString().Contains("http"))
                                {
                                    continue;
                                }
                                if (matchs[i].Groups[1].Value.ToString().StartsWith("?"))
                                {
                                    continue;
                                }
                                if (matchs[i].Groups[1].Value.ToString().ToLower().Contains(".etag"))
                                {
                                    continue;
                                }

                                //
                                {
                                    string url    = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString());
                                    Uri    newuri = new Uri(baseuri, url);
                                    files.Add(baseuri.MakeRelativeUri(newuri).ToString());
                                }


                                // dirs
                                if (matchs[i].Groups[1].Value.ToString().Contains("tree/master/"))
                                {
                                    string url =
                                        System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString()) + "/";
                                    Uri newuri = new Uri(baseuri, url);
                                    files.Add(baseuri.MakeRelativeUri(newuri).ToString());
                                }
                                // files
                                if (matchs[i].Groups[1].Value.ToString().Contains("blob/master/"))
                                {
                                    string url    = System.Web.HttpUtility.UrlDecode(matchs[i].Groups[1].Value.ToString());
                                    Uri    newuri = new Uri(baseuri, url);
                                    files.Add(
                                        System.Web.HttpUtility.UrlDecode(newuri.Segments[newuri.Segments.Length - 1]));
                                }
                            }
                        }

                        //Console.WriteLine(responseFromServer);
                        // Clean up the streams.
                    }
                }
            }

            string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir;

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            foreach (string file in files)
            {
                if (frmProgressReporter.doWorkArgs.CancelRequested)
                {
                    frmProgressReporter.doWorkArgs.CancelAcknowledged = true;
                    throw new Exception("Cancel");
                }


                if (file.Equals("/") || file.Equals("") || file.StartsWith("../"))
                {
                    continue;
                }
                if (file.EndsWith("/"))
                {
                    update =
                        updateCheck(frmProgressReporter, baseurl + file,
                                    subdir.Replace('/', Path.DirectorySeparatorChar) + file) && update;
                    continue;
                }
                if (frmProgressReporter != null)
                {
                    frmProgressReporter.UpdateProgressAndStatus(-1, "Checking " + file);
                }

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

                //   baseurl = baseurl.Replace("//github.com", "//raw.github.com");
                //   baseurl = baseurl.Replace("/tree/", "/");

                Exception fail    = null;
                int       attempt = 0;

                while (attempt < 2)
                {
                    try
                    {
                        // Create a request using a URL that can receive a post.
                        request = WebRequest.Create(baseurl + file);
                        log.Info(baseurl + file + " ");
                        // Set the Method property of the request to POST.
                        request.Method = "GET";

                        ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip |
                                                                           DecompressionMethods.Deflate;

                        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.
                            using (dataStream = response.GetResponseStream())
                            {
                                // Open the stream using a StreamReader for easy access.

                                bool updateThisFile = false;

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

                                    //log.Info(response.Headers[HttpResponseHeader.ETag]);
                                    string CurrentEtag = "";

                                    if (File.Exists(path + ".etag"))
                                    {
                                        using (Stream fs = File.OpenRead(path + ".etag"))
                                        {
                                            using (StreamReader sr = new StreamReader(fs))
                                            {
                                                CurrentEtag = sr.ReadLine();
                                            }
                                        }
                                    }

                                    log.Debug("New file Check: " + fi.Length + " vs " + response.ContentLength + " " +
                                              response.Headers[HttpResponseHeader.ETag] + " vs " + CurrentEtag);

                                    if (fi.Length != response.ContentLength ||
                                        response.Headers[HttpResponseHeader.ETag] != CurrentEtag)
                                    {
                                        using (StreamWriter sw = new StreamWriter(path + ".etag.new"))
                                        {
                                            sw.WriteLine(response.Headers[HttpResponseHeader.ETag]);
                                        }
                                        updateThisFile = true;
                                        log.Info("NEW FILE " + file);
                                    }
                                }
                                else
                                {
                                    updateThisFile = true;
                                    log.Info("NEW FILE " + file);
                                    using (StreamWriter sw = new StreamWriter(path + ".etag.new"))
                                    {
                                        sw.WriteLine(response.Headers[HttpResponseHeader.ETag]);
                                    }
                                    // get it
                                }

                                if (updateThisFile)
                                {
                                    if (!update)
                                    {
                                        //DialogResult dr = MessageBox.Show("Update Found\n\nDo you wish to update now?", "Update Now", MessageBoxButtons.YesNo);
                                        //if (dr == DialogResult.Yes)
                                        {
                                            update = true;
                                        }
                                        //else
                                        {
                                            //    return;
                                        }
                                    }
                                    if (frmProgressReporter != null)
                                    {
                                        frmProgressReporter.UpdateProgressAndStatus(-1, "Getting " + file);
                                    }

                                    // from head
                                    long bytes = response.ContentLength;

                                    long contlen = bytes;

                                    byte[] buf1 = new byte[4096];

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

                                        //dataStream.ReadTimeout = 30000;

                                        while (dataStream.CanRead)
                                        {
                                            try
                                            {
                                                if (dt.Second != DateTime.Now.Second)
                                                {
                                                    if (frmProgressReporter != null)
                                                    {
                                                        frmProgressReporter.UpdateProgressAndStatus(
                                                            (int)(((double)(contlen - bytes) / (double)contlen) * 100),
                                                            "Getting " + file + ": " +
                                                            (((double)(contlen - bytes) / (double)contlen) * 100).ToString
                                                                ("0.0") + "%"); //+ Math.Abs(bytes) + " bytes");
                                                    }
                                                    dt = DateTime.Now;
                                                }
                                            }
                                            catch
                                            {
                                            }
                                            log.Debug(file + " " + bytes);
                                            int len = dataStream.Read(buf1, 0, buf1.Length);
                                            if (len == 0)
                                            {
                                                break;
                                            }
                                            bytes -= len;
                                            fs.Write(buf1, 0, len);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        fail = ex;
                        attempt++;
                        update = false;
                        continue;
                    }

                    // break if we have no exception
                    break;
                }

                if (attempt == 2)
                {
                    throw fail;
                }
            }


            //P.StartInfo.CreateNoWindow = true;
            //P.StartInfo.RedirectStandardOutput = true;
            return(update);
        }
Пример #39
0
        /// <summary>
        /// метод отправляет запрос и возвращает ответ от сервера
        /// </summary>
        /// <param name="method">метод запроса</param>
        /// <param name="function"></param>
        /// <param name="param">коллекция параметров</param>
        /// <param name="auth">нужна ли аутентификация для этого запроса</param>
        /// <returns></returns>
        public string CreateQuery(string method, string function, Dictionary <string, string> param = null, bool auth = false)
        {
            lock (_queryHttpLocker)
            {
                string paramData = BuildQueryData(param);
                string url       = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
                string postData  = (method != "GET") ? paramData : "";

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_domain + url);
                webRequest.Method = method;

                if (auth)
                {
                    string nonce           = GetNonce().ToString();
                    string message         = method + url + nonce + postData;
                    byte[] signatureBytes  = Hmacsha256(Encoding.UTF8.GetBytes(_secKey), Encoding.UTF8.GetBytes(message));
                    string signatureString = ByteArrayToString(signatureBytes);

                    webRequest.Headers.Add("api-nonce", nonce);
                    webRequest.Headers.Add("api-key", _id);
                    webRequest.Headers.Add("api-signature", signatureString);
                }

                try
                {
                    if (postData != "")
                    {
                        webRequest.ContentType = "application/x-www-form-urlencoded";
                        var data = Encoding.UTF8.GetBytes(postData);
                        using (var stream = webRequest.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                    }

                    using (WebResponse webResponse = webRequest.GetResponse())
                        using (Stream str = webResponse.GetResponseStream())
                            using (StreamReader sr = new StreamReader(str))
                            {
                                return(sr.ReadToEnd());
                            }
                }
                catch (WebException wex)
                {
                    using (HttpWebResponse response = (HttpWebResponse)wex.Response)
                    {
                        if (response == null)
                        {
                            throw;
                        }

                        using (Stream str = response.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(str))
                            {
                                string error = sr.ReadToEnd();

                                if (ErrorEvent != null)
                                {
                                    ErrorEvent(error);
                                }
                                return(sr.ReadToEnd());
                            }
                        }
                    }
                }
            }
        }
Пример #40
0
        public static bool NeedsUpdate()
        {
            try
            {
                bool needsUpdate = false;

                JSON_Output jsonOutput = new JSON_Output();

                var json = JsonConvert.SerializeObject(jsonOutput);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://ws2.wisvis.com/aws/scanner/json_check_update.rb");
                request.Method  = "POST";
                request.Timeout = 10000;

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                Byte[] byteArray = encoding.GetBytes(json);

                request.ContentLength = byteArray.Length;
                request.ContentType   = @"application/json";

                using (Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }

                // Read response from api
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader       = new StreamReader(responseStream, Encoding.UTF8);
                    var          json_Message = reader.ReadToEnd();
                    var          jsonResponse = JsonConvert.DeserializeObject <JSON_Payload>(json_Message);

                    if (jsonResponse.Message == "True")
                    {
                        needsUpdate = true;
                    }
                    else if (jsonResponse.Message == "False")
                    {
                        needsUpdate = false;
                    }
                    else
                    {
                        // If we got here, something went wrong with the api.
                        throw new System.InvalidOperationException("Invalid parameter returned.");
                    }
                    reader.Close();
                }
                response.Close();

                if ((((HttpWebResponse)response).StatusDescription) != "OK")
                {
                    throw new System.InvalidOperationException("Attempted to connect but a connection could not be established.");
                }

                // Check update status after streams have been cleaned up.
                switch (needsUpdate)
                {
                case true:
                    return(true);

                case false:
                    return(false);

                default:
                    return(false);
                }
            }
            catch (Exception e)
            {
                Error error = new Error();
                error.ReportError(e.ToString());
                return(false);
            }
        }
Пример #41
0
        public static string Post(string url, Dictionary <object, object> param)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent   = "RK_C# 1.1";
            //request.Timeout = 30000;

            #region POST方法

            //如果需要POST数据
            if (!(param == null || param.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int           i      = 0;
                foreach (string key in param.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, param[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, param[key]);
                    }
                    i++;
                }

                byte[] data = System.Text.Encoding.UTF8.GetBytes(buffer.ToString());
                try
                {
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                catch
                {
                    return("无法连接.请检查网络.");
                }
            }

            #endregion

            WebResponse response    = null;
            string      responseStr = string.Empty;
            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                //throw;
            }
            finally
            {
                request  = null;
                response = null;
            }

            return(responseStr);
        }
Пример #42
0
		public override WebResponse EndGetResponse (IAsyncResult asyncResult)
		{
			try {
				CheckProtocolViolation ();

				if (async_result != asyncResult)
					throw new ArgumentException ("asyncResult");

				if (aborted) {
					throw new WebException ("Aborted", WebExceptionStatus.RequestCanceled);
				}

				// we could already have an exception waiting for us
				if (async_result.HasException)
					throw async_result.Exception;

				if (!async_result.IsCompleted)
					async_result.AsyncWaitHandle.WaitOne ();

				// (again) exception could occur during the wait
				if (async_result.HasException)
					throw async_result.Exception;

				response = async_result.Response;
			}
			finally {
				async_result.Dispose ();
			}

			return response;
		}
Пример #43
0
        static void getUrl()
        {
            running = true;

start:

            try
            {
                // Create a request using a URL that can receive a post.
                WebRequest request = HttpWebRequest.Create(URL);
                // Set the Method property of the request to POST.
                request.Method = "GET";

                ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                request.Headers.Add("Accept-Encoding", "gzip,deflate");

                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                log.Debug(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();

                BinaryReader br = new BinaryReader(dataStream);

                // get boundary header

                string mpheader = response.Headers["Content-Type"];
                if (mpheader.IndexOf("boundary=") == -1)
                {
                    ReadLine(br); // this is a blank line
                    string line = "proxyline";
                    do
                    {
                        line = ReadLine(br);
                        if (line.StartsWith("--"))
                        {
                            mpheader = line;
                            break;
                        }
                    } while (line.Length > 2);
                }
                else
                {
                    int startboundary = mpheader.IndexOf("boundary=") + 9;
                    int endboundary   = mpheader.Length;

                    mpheader = mpheader.Substring(startboundary, endboundary - startboundary);
                }

                dataStream.ReadTimeout    = 10000; // 10 seconds
                br.BaseStream.ReadTimeout = 10000;

                while (running)
                {
                    try
                    {
                        // get the multipart start header
                        int length = int.Parse(getHeader(br)["Content-Length"]);

                        // read boundary header
                        if (length > 0)
                        {
                            byte[] buf1 = new byte[length];

                            dataStream.ReadTimeout = 3000;

                            int offset = 0;
                            int len    = 0;

                            while ((len = br.Read(buf1, offset, length)) > 0)
                            {
                                offset += len;
                                length -= len;
                            }

                            /*
                             * BinaryWriter sw = new BinaryWriter(File.OpenWrite("test.jpg"));
                             *
                             * sw.Write(buf1,0,buf1.Length);
                             *
                             * sw.Close();
                             */
                            try
                            {
                                Bitmap frame = new Bitmap(new MemoryStream(buf1));

                                fps++;

                                if (lastimage.Second != DateTime.Now.Second)
                                {
                                    Console.WriteLine("MJPEG " + fps);
                                    fps       = 0;
                                    lastimage = DateTime.Now;
                                }

                                _onNewImage?.Invoke(null, frame);
                            }
                            catch { }
                        }

                        // blank line at end of data
                        System.Threading.Thread.Sleep(1);
                        ReadLine(br);
                    }
                    catch (Exception ex) { log.Info(ex); break; }
                }

                // clear last image
                _onNewImage?.Invoke(null, null);

                dataStream.Close();
                response.Close();
            }
            catch (Exception ex) { log.Error(ex); }

            // dont stop trying until we are told to stop
            if (running)
            {
                goto start;
            }

            running = false;
        }
Пример #44
0
        private async Task <string> SendGCMNotification(string apiKey, string sender, string postData, string postDataContentType = "application/json")
        {
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

            //
            //  MESSAGE CONTENT
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //
            //  CREATE REQUEST
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");

            Request.Method = "POST";
            //  Request.KeepAlive = false;

            Request.ContentType = postDataContentType;
            Request.Headers.Add(HttpRequestHeader.Authorization, string.Format("key={0}", apiKey));
            //Request.Headers.Add(string.Format(""));
            Request.Headers.Add(string.Format("Sender: id={0}", sender));
            Request.ContentLength = byteArray.Length;

            Stream dataStream = await Request.GetRequestStreamAsync();

            await dataStream.WriteAsync(byteArray, 0, byteArray.Length);

            dataStream.Close();

            //
            //  SEND MESSAGE
            try
            {
                //  Debug.Print(Request.ToString()+"-----"+Request.GetResponse());
                WebResponse Response = await Request.GetResponseAsync();

                HttpWebResponse HttpResponse = ((HttpWebResponse)Response);
                if (HttpResponse.StatusCode.Equals(HttpStatusCode.Unauthorized) || HttpResponse.StatusCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";
                    Debug.Print(text);
                }
                else if (!HttpResponse.StatusCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                    Debug.Print(text);
                }
                else if (HttpResponse.StatusCode.Equals((HttpStatusCode.OK)))
                {
                    var text = "status ok";
                    Debug.Print(HttpResponse.StatusDescription + "-----statusdesc------" + HttpResponse.ResponseUri);
                }

                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = await Reader.ReadToEndAsync();

                Reader.Close();

                return(responseLine);
            }
            catch (WebException e)
            {
                Debug.Print(e.Status + "-----status----" + e.Message + "--------" + e.Response);
            }
            return("error");
        }
Пример #45
0
        // Thread entry point
        public void WorkerThread()
        {
            byte[]         buffer = new byte[bufSize];                          // buffer to read stream
            HttpWebRequest req    = null;
            WebResponse    resp   = null;
            Stream         stream = null;
            Random         rnd    = new Random((int)DateTime.Now.Ticks);
            DateTime       start;
            TimeSpan       span;

            while (true)
            {
                int read, total = 0;

                try
                {
                    start = DateTime.Now;

                    // create request
                    if (!preventCaching)
                    {
                        req = (HttpWebRequest)WebRequest.Create(source);
                    }
                    else
                    {
                        req = (HttpWebRequest)WebRequest.Create(source + ((source.IndexOf('?') == -1) ? '?' : '&') + "fake=" + rnd.Next().ToString());
                    }
                    // set login and password
                    if ((login != null) && (password != null) && (login != ""))
                    {
                        req.Credentials = new NetworkCredential(login, password);
                    }
                    // set connection group name
                    if (useSeparateConnectionGroup)
                    {
                        req.ConnectionGroupName = GetHashCode().ToString();
                    }
                    // get response
                    resp = req.GetResponse();

                    // get response stream
                    stream = resp.GetResponseStream();

                    // loop
                    while (!stopEvent.WaitOne(0, true))
                    {
                        // check total read
                        if (total > bufSize - readSize)
                        {
                            System.Diagnostics.Debug.WriteLine("flushing");
                            total = 0;
                        }

                        // read next portion from stream
                        if ((read = stream.Read(buffer, total, readSize)) == 0)
                        {
                            break;
                        }

                        total += read;

                        // increment received bytes counter
                        bytesReceived += read;
                    }

                    if (!stopEvent.WaitOne(0, true))
                    {
                        // increment frames counter
                        framesReceived++;

                        // image at stop
                        if (NewFrame != null)
                        {
                            Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));
                            // notify client
                            NewFrame(this, new CameraEventArgs(bmp));
                            // release the image
                            bmp.Dispose();
                            bmp = null;
                        }
                    }

                    // wait for a while ?
                    if (frameInterval > 0)
                    {
                        // times span
                        span = DateTime.Now.Subtract(start);
                        // miliseconds to sleep
                        int msec = frameInterval - (int)span.TotalMilliseconds;

                        while ((msec > 0) && (stopEvent.WaitOne(0, true) == false))
                        {
                            // sleeping ...
                            Thread.Sleep((msec < 100) ? msec : 100);
                            msec -= 100;
                        }
                    }
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                }
                finally
                {
                    // abort request
                    if (req != null)
                    {
                        req.Abort();
                        req = null;
                    }
                    // close response stream
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    // close response
                    if (resp != null)
                    {
                        resp.Close();
                        resp = null;
                    }
                }

                // need to stop ?
                if (stopEvent.WaitOne(0, true))
                {
                    break;
                }
            }
        }
Пример #46
0
        /// <summary>
        /// HTTP POST方式请求数据(带图片)
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="param">POST的数据</param>
        /// <param name="fileByte">图片Byte</param>
        /// <returns></returns>
        public static string Post(string url, IDictionary <object, object> param, byte[] fileByte)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

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

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

            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.UserAgent   = "RK_C# 1.2";
            wr.Method      = "POST";

            //wr.Timeout = 150000;
            //wr.KeepAlive = true;

            //wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Stream rs = null;

            try
            {
                rs = wr.GetRequestStream();
            }
            catch { return("无法连接.请检查网络."); }
            string responseStr = null;

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

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

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header         = string.Format(headerTemplate, "image", "i.gif", "image/gif");//image/jpeg

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            rs.Write(fileByte, 0, fileByte.Length);

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;

            try
            {
                wresp = wr.GetResponse();

                Stream       stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                responseStr = reader2.ReadToEnd();
            }
            catch
            {
                //throw;
            }
            finally
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                wr.Abort();
                wr = null;
            }
            return(responseStr);
        }
Пример #47
0
        //Cuando le das al botón 'Conectar' oculta 'FormLogin' y te redirecciona a 'FormPrincipal'
        private void btn_conectar_Click(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://webaliza.net/webservice_jesvy_pda/auth.php");

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            string parameters = "p_clave=@450J391x%_&p_user="******"&p_pass="******"0") || result.ToString().Contains("-1") || result.ToString().Contains("-2"))
                {
                    MessageBox.Show("El usuario o la contraseña no son correctos");
                    return;
                }
            }

            //Con estas dos líneas se borran los datos del fichero actual.
            // Comentado por Ximo
            //string[] contenidoActual = File.ReadAllLines(@"C:\Users\Alberto\Desktop\gsJesvy.txt");
            //File.Delete(@"C:\Users\Alberto\Desktop\gsJesvy.txt");
            Boolean vf_pass = false;

            //Dependiendo de si 'Recordar contraseña' está marcado o no, guarda la contraseña en el archivo de texto o no.
            if (vf_pass)
            {
                if (chk_pass.Checked == true)
                {
                    string[] lines     = { tb_usuario.Text, tb_contraseña.Text, serv, pto, emp, app, ejer };
                    string   mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
                    //using (StreamWriter outputFile = new StreamWriter(@"C:\Users\Alberto\Desktop\gsJesvy.txt", true))
                    using (StreamWriter outputFile = File.CreateText(@"C:\Users\Alberto\Desktop\gsJesvy.txt"))
                    {
                        foreach (string line in lines)
                        {
                            outputFile.WriteLine(line);
                        }
                    }
                }
                else
                {
                    string[] lines     = { tb_usuario.Text, "", serv, pto, emp, app, ejer };
                    string   mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
                    using (StreamWriter outputFile = File.CreateText(@"C:\Users\Alberto\Desktop\gsJesvy.txt"))
                    {
                        foreach (string line in lines)
                        {
                            outputFile.WriteLine(line);
                        }
                    }
                }
            }

            /*
             * Para construir un JSON sería de esta form:
             * @"{""tabla"":""clientes"",""campos"":""*"",""preguntas"":""[]""}";
             */
            string usuario = tb_usuario.Text;

            FormLogin.myUser = usuario;
            this.Hide();
            FormPrincipal frm = new FormPrincipal(usuario);

            frm.Show();
        }
Пример #48
0
        public async Task GetIMBDInfo()
        {
            try
            {
                if (Json.entries.ContainsKey(filename))
                {
                    jsonInfo = Json.entries[filename];
                }
                else
                {
                    string parameters  = "q=" + name + "&" + "year=" + year;
                    byte[] paramStream = Encoding.UTF8.GetBytes(parameters);

                    WebRequest movieRequest = WebRequest.CreateHttp("http://mymovieapi.com/" + "?" + parameters);
                    movieRequest.Credentials = CredentialCache.DefaultCredentials;
                    movieRequest.Method      = "GET";

                    /*
                     * Stream requestStream = await movieRequest.GetRequestStreamAsync();
                     * requestStream.Write(paramStream, 0, paramStream.Length);
                     * requestStream.Flush();
                     * //requestStream.Dispose();
                     */
                    WebResponse movieResponse = await movieRequest.GetResponseAsync();

                    Stream      responseStream = movieResponse.GetResponseStream();
                    List <byte> jsonArr        = new List <byte>();
                    while (true)
                    {
                        byte[] buffer    = new byte[1024];
                        int    bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                        jsonArr.AddRange(buffer.Take(bytesRead));
                        if (bytesRead < buffer.Length)
                        {
                            break;
                        }
                    }
                    responseStream.Dispose();
                    movieResponse.Dispose();

                    jsonInfo = Json.ParseJson(System.Text.Encoding.UTF8.GetString(jsonArr.ToArray(), 0, jsonArr.ToArray().Length));
                    jsonInfo.Add("filename", (JToken)filename);
                    Json.newEntries.Add(filename, jsonInfo);
                }
            }
            catch (WebException e)
            {
                WebExceptionStatus error = e.Status;

                throw e;
            }


            runtime     = Json.GetFieldArr("runtime", jsonInfo)[0];
            rating      = Double.Parse(Json.GetField("rating", jsonInfo));
            description = Json.GetField("plot_simple", jsonInfo);
            actors      = Json.GetFieldArr("actors", jsonInfo);
            directors   = Json.GetFieldArr("directors", jsonInfo);
            genres      = Json.GetFieldArr("genres", jsonInfo);
            writers     = Json.GetFieldArr("writers", jsonInfo);

            //update(this);
            return;
        }
Пример #49
0
        private async Task DownloadAndUpload(string baseurl)
        {
            var tempfile = Path.GetTempFileName();

            try
            {
                // update to use mirror url
                log.Info("Using " + baseurl);

                SetLoading(true);

                var starttime = DateTime.Now;

                // Create a request using a URL that can receive a post.
                WebRequest request = WebRequest.Create(baseurl);
                request.Timeout = 10000;
                // Set the Method property of the request to POST.
                request.Method = "GET";
                // Get the request stream.
                Stream dataStream; //= request.GetRequestStream();
                // Get the response (using statement is exception safe)
                using (WebResponse response = request.GetResponse())
                {
                    // Display the status.
                    log.Info(((HttpWebResponse)response).StatusDescription);
                    // Get the stream containing content returned by the server.
                    using (dataStream = response.GetResponseStream())
                    {
                        long bytes   = response.ContentLength;
                        long contlen = bytes;

                        byte[] buf1 = new byte[1024];

                        using (FileStream fs = new FileStream(tempfile, FileMode.Create))
                        {
                            //fw_Progress1(0, Strings.DownloadingFromInternet);

                            long length   = response.ContentLength;
                            long progress = 0;
                            dataStream.ReadTimeout = 30000;

                            while (dataStream.CanRead)
                            {
                                try
                                {
                                    //fw_Progress1(length == 0 ? 50 : (int)((progress * 100) / length), Strings.DownloadingFromInternet);
                                }
                                catch
                                {
                                }

                                int len = dataStream.Read(buf1, 0, 1024);
                                if (len == 0)
                                {
                                    break;
                                }
                                progress += len;
                                bytes    -= len;
                                fs.Write(buf1, 0, len);
                            }

                            fs.Close();
                        }

                        dataStream.Close();
                    }

                    response.Close();
                }

                var timetook = (DateTime.Now - starttime).TotalMilliseconds;

                //Tracking.AddTiming("Firmware Download", deviceInfo.board, timetook, deviceInfo.description);

                //fw_Progress1(100, Strings.DownloadedFromInternet);
                log.Info("Downloaded");
            }
            catch
            {
                CustomMessageBox.Show(Strings.FailedDownload, Strings.ERROR);
                return;
            }
            finally
            {
                SetLoading(false);
            }

            //MissionPlanner.Utilities.Tracking.AddFW(mavtype.ToString(), deviceInfo.board);

            //var fw = new Firmware();
            //fw.Progress += fw_Progress1;

            var uploadstarttime = DateTime.Now;

            await UploadPX4(tempfile).ConfigureAwait(false);

            //fw.UploadFlash(deviceInfo.name, tempfile, BoardDetect.boards.pass);

            var uploadtime = (DateTime.Now - uploadstarttime).TotalMilliseconds;

            //Tracking.AddTiming("Firmware Upload", deviceInfo.board, uploadtime, deviceInfo.description);

            return;
        }
Пример #50
0
        /// <summary>
        /// Can be called syncronized to get a Http Web ResponseStream.
        /// </summary>
        /// <param name="method">The HTTP request method</param>
        /// <param name="address">Url to request</param>
        /// <param name="newAddress">out string. return a new url, if the original requested is permanent moved</param>
        /// <param name="credentials">Url credentials</param>
        /// <param name="userAgent"></param>
        /// <param name="proxy">Proxy to use</param>
        /// <param name="ifModifiedSince">Header date</param>
        /// <param name="eTag">Header tag</param>
        /// <param name="timeout">Request timeout. E.g. 60 * 1000, means one minute timeout.
        /// If zero or less than zero, the default timeout of one minute will be used</param>
        /// <param name="responseResult">out. Result of the request</param>
        /// <param name="cookie">The cookie associated with the request</param>
        /// <param name="body">The body of the HTTP request (if it is a POST)</param>
        /// <param name="additonalHeaders">These are additional headers that are being specified to the Web request</param>
        /// <returns>Stream</returns>
        public static Stream GetResponseStream(HttpMethod method, string address, out string newAddress,
                                               ICredentials credentials,
                                               string userAgent,
                                               IWebProxy proxy, ref DateTime ifModifiedSince, ref string eTag,
                                               int timeout, out RequestResult responseResult, Cookie cookie, string body,
                                               WebHeaderCollection additonalHeaders)
        {
            bool      useDefaultCred    = false;
            int       requestRetryCount = 0;
            const int MaxRetries        = 25;

            newAddress = null;

send_request:

            string requestUri = address;

            if (useDefaultCred)
            {
                credentials = CredentialCache.DefaultCredentials;
            }

            WebResponse wr =
                GetResponse(method, address, credentials, userAgent, proxy, ifModifiedSince, eTag, timeout, cookie, body,
                            additonalHeaders);

            HttpWebResponse response     = wr as HttpWebResponse;
            FileWebResponse fileresponse = wr as FileWebResponse;

            if (response != null)
            {
                if (HttpStatusCode.OK == response.StatusCode ||
                    HttpExtendedStatusCode.IMUsed == (HttpExtendedStatusCode)response.StatusCode)
                {
                    responseResult = RequestResult.OK;
                    // stream will be disposed on response.Close():
                    Stream ret = MakeSeekableStream(response.GetResponseStream()); //GetDeflatedResponse(response);
                    response.Close();
                    return(ret);
                }
                if ((response.StatusCode == HttpStatusCode.MovedPermanently) ||
                    (response.StatusCode == HttpStatusCode.Moved))
                {
                    newAddress = HtmlHelper.ConvertToAbsoluteUrl(response.Headers["Location"], address, false);
                    address    = newAddress;
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsUnauthorized(response.StatusCode))
                {
                    //try with default credentials

                    useDefaultCred = true;
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsRedirect(response.StatusCode))
                {
                    address = HtmlHelper.ConvertToAbsoluteUrl(response.Headers["Location"], address, false);
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsAccessForbidden(response.StatusCode) &&
                         requestUri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ClientCertificateRequiredException();
                }
                else if (response.StatusCode == HttpStatusCode.Gone)
                {
                    throw new ResourceGoneException();
                }
                else
                {
                    string statusCode = response.StatusDescription;
                    if (String.IsNullOrEmpty(statusCode))
                    {
                        statusCode = response.StatusCode.ToString();
                    }
                    response.Close();
                    throw new WebException(String.Format("Request of '{0}' gets unexpected HTTP response: {1}",
                                                         requestUri, statusCode));
                }

                // unauthorized more than MaxRetries
                if (IsUnauthorized(response.StatusCode))
                {
                    response.Close();
                    throw new ResourceAuthorizationException();
                }

                //we got a moved, redirect more than MaxRetries
                string returnCode = response.StatusDescription;
                if (String.IsNullOrEmpty(returnCode))
                {
                    returnCode = response.StatusCode.ToString();
                }
                response.Close();
                throw new WebException(String.Format("Request of '{0}' gets repeated HTTP response: {1}", requestUri,
                                                     returnCode));
            }

            if (fileresponse != null)
            {
                responseResult = RequestResult.OK;
                // stream will be disposed on response.Close():
                Stream ret = MakeSeekableStream(fileresponse.GetResponseStream()); //GetDeflatedResponse(fileresponse);
                fileresponse.Close();
                return(ret);
            }
            throw new ApplicationException("no handler for WebResponse. Address: " + requestUri);
        }
        public StagingTicket invoke(Outlook.MailItem mail)
        {
            StagingTicket ticket = new StagingTicket();

            //Calling CreateSOAPWebRequest method
            HttpWebRequest request = CreateSOAPWebRequest();
            XmlDocument SOAPReqBody = new XmlDocument();

            //declare SOAP message builder
            StringBuilder soap = new StringBuilder();
            //create envelope
            soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:Outlook2Remedy\">\n");
            //create auth header
            soap.Append("\t<soapenv:Header>\n" +
            "\t\t<urn:AuthenticationInfo>\n" +
            "\t\t\t<urn:userName>" + Properties.Settings.Default.RemedyUsername + "</urn:userName>\n" +
            "\t\t\t<urn:password>" + Properties.Settings.Default.RemedyPassword + "</urn:password>\n" +
            "\t\t</urn:AuthenticationInfo>\n" +
            "\t</soapenv:Header>\n");
            //open Body and start creating event
            soap.Append("\t<soapenv:Body>\n" +
            "\t\t<urn:Create>\n");
            //add workflow variables
            soap.Append("\t\t\t<urn:Submitter>" + Environment.UserName.ToLower() + "</urn:Submitter>\n" +
            "\t\t\t<urn:EventCode>" + Properties.Settings.Default.EventCode + "</urn:EventCode>\n");
            //add email content (subject and body)
            soap.Append("\t\t\t<urn:EmailSubject>" + (mail.Subject != null ? WebUtility.HtmlEncode(mail.Subject) : "(no subject)") + "</urn:EmailSubject>\n" +
            "\t\t\t<urn:EmailBody>" + WebUtility.HtmlEncode(mail.Body) + "</urn:EmailBody>\n");
            //add attachment details
            if(Properties.Settings.Default.EmailAttachment)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + @"\temp";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                if (mail.Subject.Length > 50) path += @"\"+ HandleSpecialChars(mail.Subject.Substring(0, 49), "_") + ".msg";
                    else path += @"\" + HandleSpecialChars(mail.Subject, "_") + ".msg";
                mail.SaveAs(path, Outlook.OlSaveAsType.olMSG);
                soap.Append("<urn:EML_attachmentName>" + path + "</urn:EML_attachmentName>");
                soap.Append("<urn:EML_attachmentData>" + Convert.ToBase64String(GetEmailContent(path)) + "</urn:EML_attachmentData>");
                soap.Append("<urn:EML_attachmentOrigSize>" + GetEmailLength(path) + "</urn:EML_attachmentOrigSize>");
                File.Delete(path);
            }
            //add releated ticket - if is found
            soap.Append("\t\t\t<urn:RelatedTicketID>" + GetTicketReference(mail.Subject) + "</urn:RelatedTicketID>\n");
            //add recepients
            soap.Append("\t\t\t<urn:EmailFrom>" + WebUtility.HtmlEncode(mail.SenderEmailAddress) + "</urn:EmailFrom>\n" +
            "\t\t\t<urn:EmailTO>" + WebUtility.HtmlEncode(mail.To) + "</urn:EmailTO>\n" +
            "\t\t\t<urn:EmailCC>" + WebUtility.HtmlEncode(mail.CC) + "</urn:EmailCC>\n");
            //closing event, Body and envelope
            soap.Append("\t\t</urn:Create>\n" +
            "\t</soapenv:Body>\n" +
            "</soapenv:Envelope>");

            //prepare XML SOAP request
            SOAPReqBody.LoadXml(soap.ToString());

            //send XML SOAP request to server
            using (Stream stream = request.GetRequestStream())
            {
                SOAPReqBody.Save(stream);
            }

            //Geting response from request
            using (WebResponse Serviceres = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))
                {
                    //reading stream
                    var strResponse = rd.ReadToEnd();

                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.LoadXml(strResponse);
                    XmlNamespaceManager nsm = new XmlNamespaceManager(xmldoc.NameTable);
                    nsm.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
                    nsm.AddNamespace("ns0", "urn:Outlook2Remedy");

                    XmlNode node1 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:RID", nsm);
                    if (node1 != null && node1.InnerText != null) ticket.rid = node1.InnerText;
                        else ticket.rid = null;

                    XmlNode node2 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:WID", nsm);
                    if (node2 != null && node2.InnerText != null) ticket.wid = node2.InnerText;
                        else ticket.wid = null;

                    XmlNode node3 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:STS", nsm);
                    if (node3 != null && node3.InnerText != null) ticket.sts = node3.InnerText;
                        else ticket.sts = "open";

                    XmlNode node4 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:LOG", nsm);
                    if (node4 != null && node4.InnerText != null) ticket.log = node4.InnerText;
                        else ticket.log = null;
                }
            }

            return ticket;
        }
 internal void FetchResponse(WebResponse fetchResponse)
 {
     ++_ResponseCount;
     _Response = fetchResponse;
 }
        /// <summary>
        /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
        /// </summary>
        /// <param name="address">文件上传到的服务器</param>
        /// <param name="fileNamePath">要上传的本地文件(全路径)</param>
        /// <param name="saveName">文件上传后的名称</param>
        /// <returns>成功返回1,失败返回0</returns>
        public static string UploadFilesByPost(string address, string fileNamePath)
        {
            try
            {
                int u = ServicePointManager.DefaultConnectionLimit;
                ServicePointManager.DefaultConnectionLimit = 200;

                string      returnValue = "0"; // 要上传的文件
                WebResponse webRespon   = null;

                FileStream   fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                BinaryReader r  = new BinaryReader(fs);    //时间戳

                string sguidSplit = Guid.NewGuid().ToString();
                string filename   = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);

                StringBuilder sb = new StringBuilder(300);

                string         strPostHeader = sb.ToString();
                HttpWebRequest httpReq       = (HttpWebRequest)WebRequest.Create(new Uri(address));

                httpReq.ServicePoint.Expect100Continue = false;
                httpReq.Method = "POST";                                             //对发送的数据不使用缓存
                httpReq.AllowWriteStreamBuffering = false;                           //设置获得响应的超时时间(300秒)
                httpReq.Timeout     = 60000;
                httpReq.ContentType = "multipart/form-data; boundary=" + sguidSplit; //"text/xml";
                httpReq.Accept      = "text/plain, */*";
                httpReq.UserAgent   = "WinHttpClient";

                httpReq.Headers["Accept-Language"] = "zh-cn";

                sb.Append("--" + sguidSplit + "\r\n");
                sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n");
                sb.Append("Content-Type: application/octet-stream;Charset=UTF-8\r\n");
                sb.Append("\r\n");

                byte[] boundaryBytes = Encoding.ASCII.GetBytes(sb.ToString());     //请求头部信息
                byte[] bEndBytes     = Encoding.ASCII.GetBytes("\r\n--" + sguidSplit + "--\r\n");
                long   length        = fs.Length + boundaryBytes.Length + bEndBytes.Length;
                long   fileLength    = fs.Length;
                httpReq.ContentLength = length;

                try
                {
                    int      bufferLength = 4096;                   //每次上传4k
                    byte[]   buffer       = new byte[bufferLength]; //已上传的字节数
                    long     offset       = 0;                      //开始上传时间
                    DateTime startTime    = DateTime.Now;

                    int    size       = r.Read(buffer, 0, bufferLength);
                    Stream postStream = httpReq.GetRequestStream();         //发送请求头部消息
                    postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    while (size > 0)
                    {
                        postStream.Write(buffer, 0, size);
                        offset += size;
                        TimeSpan span   = DateTime.Now - startTime;
                        double   second = span.TotalSeconds;
                        Application.DoEvents();
                        size = r.Read(buffer, 0, bufferLength);
                    }
                    //添加尾部的时间戳
                    postStream.Write(bEndBytes, 0, bEndBytes.Length);
                    postStream.Close();
                    //获取服务器端的响应
                    webRespon = httpReq.GetResponse();   //提示操作超时  20180105
                    Stream s = webRespon.GetResponseStream();
                    //读取服务器端返回的消息
                    StreamReader sr            = new StreamReader(s);
                    String       sReturnString = sr.ReadLine();
                    s.Close();
                    sr.Close();
                    returnValue = "1";
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    returnValue = "0";
                }
                finally
                {
                    fs.Close();
                    r.Close();
                    if (httpReq != null)
                    {
                        httpReq.Abort();
                    }
                    if (webRespon != null)
                    {
                        webRespon.Close();
                    }
                    GC.Collect();
                }
                return(returnValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Thread.Sleep(500);
            }
            return("0");
        }
Пример #54
0
		private Exception NotFound (string scheme, WebResponse wres)
		{
			if (scheme == "https")
				return new SecurityException ();

			return new WebException ("NotFound", null, 
				wres == null ? WebExceptionStatus.UnknownError : WebExceptionStatus.Success, 
				wres);
		}
Пример #55
0
        public static object GetResponse(object webRequest, int opCode, int mdToken, long moduleVersionPtr)
        {
            if (webRequest == null)
            {
                throw new ArgumentNullException(nameof(webRequest));
            }

            const string methodName = nameof(GetResponse);

            Func <object, WebResponse> callGetResponse;

            try
            {
                var instrumentedType = webRequest.GetInstrumentedType("System.Net.WebRequest");
                callGetResponse =
                    MethodBuilder <Func <object, WebResponse> >
                    .Start(moduleVersionPtr, mdToken, opCode, methodName)
                    .WithConcreteType(instrumentedType)
                    .WithNamespaceAndNameFilters("System.Net.WebResponse")
                    .Build();
            }
            catch (Exception ex)
            {
                Log.ErrorRetrievingMethod(
                    exception: ex,
                    moduleVersionPointer: moduleVersionPtr,
                    mdToken: mdToken,
                    opCode: opCode,
                    instrumentedType: WebRequestTypeName,
                    methodName: methodName,
                    instanceType: webRequest.GetType().AssemblyQualifiedName);
                throw;
            }

            var request = (WebRequest)webRequest;

            if (!(request is HttpWebRequest) || !IsTracingEnabled(request))
            {
                return(callGetResponse(webRequest));
            }

            using (var scope = ScopeFactory.CreateOutboundHttpScope(Tracer.Instance, request.Method, request.RequestUri, IntegrationName))
            {
                try
                {
                    if (scope != null)
                    {
                        // add distributed tracing headers to the HTTP request
                        SpanContextPropagator.Instance.Inject(scope.Span.Context, request.Headers.Wrap());
                    }

                    WebResponse response = callGetResponse(webRequest);

                    if (scope != null && response is HttpWebResponse webResponse)
                    {
                        scope.Span.SetTag(Tags.HttpStatusCode, ((int)webResponse.StatusCode).ToString());
                    }

                    return(response);
                }
                catch (Exception ex)
                {
                    scope?.Span.SetException(ex);
                    throw;
                }
            }
        }
Пример #56
0
 public static void Close(this WebResponse response) => response.Dispose();
        /// <summary>
        /// Obtient le nom du compte SMS connecté
        /// </summary>
        /// <returns>sms-XX0000-1</returns>
        public string GetServiceName()
        {
            string method        = "GET";
            string query         = "https://eu.api.ovh.com/1.0/sms/";
            string body          = string.Empty;
            string unixTimestamp = ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString();

            // Création de la signature
            string signature = string.Format("{0}+{1}+{2}+{3}+{4}+{5}", ApplicationSecret, ConsumerKey, method, query, body, unixTimestamp);

            // Création de la requête
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);

            req.Method      = method;
            req.ContentType = "application/json";
            req.Headers.Add("X-Ovh-Application:" + ApplicationKey);
            req.Headers.Add("X-Ovh-Consumer:" + ConsumerKey);
            req.Headers.Add("X-Ovh-Signature:" + string.Concat("$1$", SHA1Helper.Hash(signature)));
            req.Headers.Add("X-Ovh-Timestamp:" + unixTimestamp);

            try
            {
                string result = string.Empty;
                using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            // La chaine est du type ["sms-XX0000-1"], on cherche à récupérer la valeur entre double quote.
                            Regex regex = new Regex(@"(?<=\["")(.*?)(?=""\])");
                            result = regex.Match(reader.ReadToEnd().Trim()).Value;
                            reader.Close();
                        }
                        responseStream.Close();
                    }
                    response.Close();
                }

                return(result);
            }
            catch (WebException e)
            {
                string error = e.Message;
                using (WebResponse response = e.Response)
                {
                    using (Stream data = ((HttpWebResponse)response).GetResponseStream())
                    {
                        using (var reader = new StreamReader(data))
                        {
                            error = reader.ReadToEnd();
                            reader.Close();
                        }
                        data.Close();
                    }
                    response.Close();
                }

                return(error);
            }
        }
        //
        // Returns UpdateResponseInformation if passed response stream has to be replaced (cache is updated in some way)
        // Returns Fail if request is to fail
        // Any other return value should be ignored
        //
        internal CacheValidationStatus GetUpdateStatus (WebResponse response, Stream responseStream)
        {
            if (response == null)
                throw new ArgumentNullException("response");

            if (_ProtocolStatus == CacheValidationStatus.DoNotUseCache)
                return CacheValidationStatus.DoNotUseCache;

            try {
                if(Logging.On) Logging.Enter(Logging.RequestCache, this, "GetUpdateStatus", null);

                if (_Validator.Response == null)
                    _Validator.FetchResponse(response);

                if (_ProtocolStatus == CacheValidationStatus.RemoveFromCache)
                {
                    EnsureCacheRemoval(_Validator.CacheKey);
                    return _ProtocolStatus;
                }

                if (_ProtocolStatus != CacheValidationStatus.DoNotTakeFromCache &&
                    _ProtocolStatus != CacheValidationStatus.ReturnCachedResponse &&
                    _ProtocolStatus != CacheValidationStatus.CombineCachedAndServerResponse)
                {
                    if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_not_updated_based_on_cache_protocol_status, "GetUpdateStatus()", _ProtocolStatus.ToString()));
                    return _ProtocolStatus;
                }

                CheckUpdateOnResponse(responseStream);
            }
            catch (Exception e) {
                _ProtocolException = e;
                _ProtocolStatus = CacheValidationStatus.Fail;
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
                    throw;
                }
                if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_object_and_exception, "CacheProtocol#" + this.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), (e is WebException? e.Message: e.ToString())));
            }
            finally {
                if(Logging.On)Logging.Exit(Logging.RequestCache, this, "GetUpdateStatus", "result = " + _ProtocolStatus.ToString());
            }
            return _ProtocolStatus;
        }
Пример #59
0
        private static void DownloadImage()
        {
            int page = 1;


            const string connection =
                @"Data Source=42.112.28.93;Initial Catalog=QT_2;Persist Security Info=True;User ID=wss_price;Password=HzlRt4$$axzG-*UlpuL2gYDu;";
            string query         = @"
select a.ImagePath, a.id
from product  a
inner join company b on a.company = b.id 
where b.status = 1
and b.DataFeedType = 0 
and a.Valid = 1
and isnull(a.imagepath,'')!=''
and a.ImageId is  null
order by a.id asc 
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
FETCH NEXT @RowspPage ROWS ONLY;
";
            SqlDb  sqlConnection = new SqlDb(connection);

            using (FtpClient ftpClient = new FtpClient())
            {
                ftpClient.Host        = "183.91.14.84";
                ftpClient.Credentials = new NetworkCredential("xuantrang_dev", "123456!@#$%^");
                ftpClient.Connect();
                DataTable tbl = sqlConnection.GetTblData(query, CommandType.Text, new SqlParameter[]
                {
                    SqlDb.CreateParamteterSQL("PageNumber", page++, SqlDbType.Int),
                    SqlDb.CreateParamteterSQL("RowspPage", itemInPage, SqlDbType.Int),
                });
                string path = "";
                while (tbl.Rows.Count > 0)
                {
                    foreach (DataRow variable in tbl.Rows)
                    {
                        try
                        {
                            long productId = Convert.ToInt64(variable["id"])
                            ;
                            path = variable["ImagePath"].ToString();
                            string readyPath = path.Replace("Store/", "");
                            if (ftpClient.FileExists(readyPath))
                            {
                                using (var ftpStream = ftpClient.OpenRead(readyPath))
                                {
                                    var request =
                                        (HttpWebRequest)WebRequest.Create("http://192.168.100.34/users/xtpu/images");
                                    request.Headers.Add("X-Imbo-PublicKey", "xtpu");
                                    // request.Headers.Add("Content-Type", "application/json");
                                    request.ContentType = "application/json";
                                    request.Method      = "POST";
                                    using (Stream stream = request.GetRequestStream())
                                    {
                                        ftpStream.CopyTo(stream);
                                    }
                                    using (WebResponse response = request.GetResponse())
                                    {
                                        using (Stream stream = response.GetResponseStream())
                                        {
                                            using (StreamReader sr99 = new StreamReader(stream))
                                            {
                                                var     responseContent = sr99.ReadToEnd();
                                                dynamic d          = JObject.Parse(responseContent);
                                                string  idImageNew = d.imageIdentifier;
                                                string  query1     =
                                                    string.Format("update product set ImageId = '{0}' where Id = {1}",
                                                                  idImageNew, productId
                                                                  );
                                                sqlConnection.RunQuery(query1
                                                                       , CommandType.Text, null);
                                                Log.Info(responseContent);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }
                    }
                    ftpClient.Disconnect();
                    Log.InfoFormat("SUccess page : {0}", page);
                    tbl = sqlConnection.GetTblData(query, CommandType.Text, new SqlParameter[]
                    {
                        SqlDb.CreateParamteterSQL("PageNumber", page++, SqlDbType.Int),
                        SqlDb.CreateParamteterSQL("RowspPage", itemInPage, SqlDbType.Int),
                    });
                }
            }
        }