GetResponseStream() public method

public GetResponseStream ( ) : Stream
return System.IO.Stream
示例#1
1
文件: Program.cs 项目: Aren97/MISIS
 public Stream Creat()
 {
     WebRequest inquiry = WebRequest.Create("http://api.lod-misis.ru/testassignment");
     Answer = inquiry.GetResponse();
     Stream stream = Answer.GetResponseStream();
     return stream;
 }
        /// <summary>
        /// Determines whether response is gzipped and invokes platform specific decompression if necessary
        /// </summary>
        /// <param name="response">The web response</param>
        /// <returns>The response stream</returns>
        public Stream GetResponseStream(WebResponse response)
        {
            bool gzipped = false;
            if (response.Headers != null && response.Headers.Count > 0)
            {
                var headerEncoding = response.Headers["Content-Encoding"];
                gzipped = headerEncoding != null && headerEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) > -1;
            }

            return gzipped ?
                new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)
                : response.GetResponseStream();
        }
示例#3
0
        public static byte[] ConvertWebResponseToByteArray(WebResponse res)
        {
            BinaryReader br = new BinaryReader(res.GetResponseStream());

            // Download and buffer the binary stream into a memory stream
            MemoryStream stm = new MemoryStream();
            int pos = 0;
            int maxread = BufferSize;
            while (true)
            {
                byte[] content = br.ReadBytes(maxread);
                if (content.Length <= 0)
                    break;

                if (content.Length < maxread)
                    maxread = maxread - content.Length;

                stm.Write(content, 0, content.Length);
                pos += content.Length;
            }

            br.Close();
            stm.Position = 0;
            byte[] final = new byte[(int)stm.Length];
            stm.Read(final, 0, final.Length);
            stm.Close();
            return final;
        }
		private static string ReadResponse(WebResponse response) {
			using(var readStream = new StreamReader(response.GetResponseStream(),System.Text.Encoding.UTF8)) {
				var output = readStream.ReadToEnd();

				return output;
			}
		}
 public virtual ParsedCSVFile ParseToRows(WebResponse response)
 {
     using (var reader = new CsvReader(new StreamReader(response.GetResponseStream()), true))
     {
         return new ParsedCSVFile(GetRows(reader).ToArray(), reader.GetFieldHeaders().Select(StringExtensions.RemoveWhitespace).ToArray());
     }
 }
 internal GravatarProfile(WebResponse webResponse)
 {
     using (var responseStream = webResponse.GetResponseStream())
         if (responseStream != null)
             using (var reader = new StreamReader(responseStream))
                 LoadFromXml(reader.ReadToEnd());
 }
示例#7
0
 /// <summary>
 /// 下载Response的文件流数据
 /// </summary>
 /// <param name="response">response</param>
 private void DownloadFile(WebResponse response)
 {
     if (response == null) return;
     try
     {
         var context = HttpContext.Current;
         using (var iStream = response.GetResponseStream())
         {
             byte[] buffer = new byte[AppConst.ChunkSize];
             int readDataLen = 0;
             context.Response.ContentType = response.ContentType;
             context.Response.AddHeader("Content-Disposition", response.Headers["Content-Disposition"]);
             readDataLen = iStream.Read(buffer, 0, AppConst.ChunkSize);
             while (readDataLen > 0 && context.Response.IsClientConnected)
             {
                 context.Response.OutputStream.Write(buffer, 0, readDataLen);
                 context.Response.Flush();
                 try
                 {
                     readDataLen = iStream.Read(buffer, 0, AppConst.ChunkSize);
                 }
                 catch
                 {
                     break;
                 }
             }
             context.Response.Close();
         }
     }
     finally
     {
         response.Close();
     }
 }
 /// <summary>
 /// Create a new Gravatar response for the method that was called.
 /// Throws a <see cref="GravatarInvalidResponseXmlException">GravatarInvalidResponseXmlException</see>
 /// if the XML returned from Gravatar is in an unexpected format
 /// </summary>		
 internal GravatarServiceResponse(WebResponse webResponse, string methodName)
 {
     using (var responseStream = webResponse.GetResponseStream())
         if (responseStream != null)
             using (var reader = new StreamReader(responseStream))
                 InitializeGravatarResponse(reader.ReadToEnd(), methodName);
 }
示例#9
0
 private static Stream Post(string url, string postData, out WebResponse response)
 {
     // Create a request using a URL that can receive a post.
     WebRequest request = WebRequest.Create(url);
     // Set the Method property of the request to POST.
     request.Method = "POST";
     // Create POST data and convert it to a byte array.
     byte[] byteArray = Encoding.UTF8.GetBytes(postData);
     // Set the ContentType property of the WebRequest.
     request.ContentType = "application/json";
     // Set the ContentLength property of the WebRequest.
     request.ContentLength = byteArray.Length;
     // Get the request stream.
     Stream dataStream = request.GetRequestStream();
     // Write the data to the request stream.
     dataStream.Write(byteArray, 0, byteArray.Length);
     // Close the Stream object.
     dataStream.Close();
     // Get the response.
     response = request.GetResponse();
     // Display the status.
     //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
     // Get the stream containing content returned by the server.
     dataStream = response.GetResponseStream();
     return dataStream;
 }
        public OAuthTokenResponse(WebResponse httpWebResponse)
        {
            using (var stream = httpWebResponse.GetResponseStream())
            {
                var reader = new StreamReader(stream);
                ResponseBody = reader.ReadToEnd();
                reader.Close();
            }

            if (string.IsNullOrEmpty(ResponseBody))
            {
                return;
            }

            Items = new NameValueCollection();

            foreach (string item in ResponseBody.Split('&'))
            {
                if (item.IndexOf('=') > -1)
                {
                    string[] temp = item.Split('=');
                    Items.Add(temp[0], temp[1]);
                }
                else
                {
                    Items.Add(item, string.Empty);
                }
            }

            Token = new OAuthToken() { Token = Items["oauth_token"], TokenSecret = Items["oauth_token_secret"] };
        }
示例#11
0
        private static string ReadData(WebResponse response)
        {
            Stream resStream = response.GetResponseStream();

            var buf = new byte[8192];
            var sb = new StringBuilder();
            string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            } while (count > 0); // any more data to read?
            return sb.ToString();
        }
示例#12
0
 public Stream Get()
 {
     WebRequest request = WebRequest.Create("http://api.lod-misis.ru/testassignment");
     response = request.GetResponse();
     Stream stream = response.GetResponseStream();
     return stream;
 }
        public ListAllMyBucketsResponse( WebResponse response )
            : base(response)
        {
            buckets = new ArrayList();
            string rawBucketXML = Utils.slurpInputStreamAsString( response.GetResponseStream() );

            XmlDocument doc = new XmlDocument();
            doc.LoadXml( rawBucketXML );
            foreach (XmlNode node in doc.ChildNodes)
            {
                if (node.Name.Equals("ListAllMyBucketsResult"))
                {
                    foreach (XmlNode child in node.ChildNodes)
                    {
                        if (child.Name.Equals("Owner"))
                        {
                            owner = new Owner(child);
                        }
                        else if (child.Name.Equals("Buckets"))
                        {
                            foreach (XmlNode bucket in child.ChildNodes)
                            {
                                if (bucket.Name.Equals("Bucket"))
                                {
                                    buckets.Add(new Bucket(bucket));
                                }
                            }
                        }
                    }
                }
            }
        }
 private static bool saveBinaryFile(WebResponse response, string savePath)
 {
     bool value = false;
     byte[] buffer = new byte[1024];
     Stream outStream = null;
     Stream inStream = null;
     try
     {
         if (File.Exists(savePath)) File.Delete(savePath);
         outStream = System.IO.File.Create(savePath);
         inStream = response.GetResponseStream();
         int l;
         do
         {
             l = inStream.Read(buffer, 0, buffer.Length);
             if (l > 0) outStream.Write(buffer, 0, l);
         } while (l > 0);
         value = true;
     }
     finally
     {
         if (outStream != null) outStream.Close();
         if (inStream != null) inStream.Close();
     }
     return value;
 }
		private static byte[] GetDeliveryKey(WebResponse response)
		{
			var stream = response.GetResponseStream();
			if (stream == null)
			{
				throw new NullReferenceException("Response stream is null");
			}

			var buffer = new byte[256];
			var length = 0;
			while (stream.CanRead && length <= buffer.Length)
			{
				var nexByte = stream.ReadByte();
				if (nexByte == -1)
				{
					break;
				}
				buffer[length] = (byte)nexByte;
				length++;
			}
			//response.Close();

			var key = new byte[length];
			Array.Copy(buffer, key, length);
			return key;
		}
示例#16
0
 public GetResponse(WebResponse response)
     : base(response)
 {
     SortedList metadata = extractMetadata( response );
     byte [] data = Utils.slurpInputStream( response.GetResponseStream() );
     this.obj = new S3Object( data, metadata );
 }
示例#17
0
 private void staticBtn_Click(object sender, EventArgs e)
 {
     requestPicStatic = WebRequest.Create("http://maps.googleapis.com/maps/api/staticmap?center=" + address + "&zoom=" + zoom + "&size=353x267&sensor=false");
     repsonsePicStatic = requestPicStatic.GetResponse();
     mapStatic = Image.FromStream(repsonsePicStatic.GetResponseStream());
     pictureBox1.Image = mapStatic;
 }
示例#18
0
		private string GetResponseAsString(WebResponse response)
		{
			using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
			{
				return sr.ReadToEnd();
			}
		}
示例#19
0
 private void strtBtn_Click(object sender, EventArgs e)
 {
     requestPicStreet = WebRequest.Create("http://maps.googleapis.com/maps/api/streetview?location=" + address + "&heading=" + heading.ToString() + "&zoom=12&size=453x267&sensor=false");
     repsonsePicStreet = requestPicStreet.GetResponse();
     mapStreet = Image.FromStream(repsonsePicStreet.GetResponseStream());
     pictureBox2.Image = mapStreet;
 }
示例#20
0
    public void BeginStreaming()
    {
      try
      {
        request = new CampfireRequest(this.site)
            .CreateRequest(this.site.ApiUrlBuilder.Stream(this.room.ID), HttpMethod.GET);
        request.Timeout = -1;

        // yes, this is needed. regular authentication using the Credentials property does not work for streaming
        string token = string.Format("{0}:X", this.site.ApiToken);
        string encoding = Convert.ToBase64String(Encoding.UTF8.GetBytes(token));
        request.Headers.Add("Authorization", "Basic " + encoding);

        response = request.GetResponse();
        responseStream = response.GetResponseStream();
        reader = new StreamReader(responseStream, Encoding.UTF8);

        del = new Action(() =>
        {
          ReadNextMessage(reader);
        });

        del.BeginInvoke(LineRead, null);
      }
      catch
      {
        Thread.Sleep(2500);
        BeginStreaming();
      }
    }
示例#21
0
        public void ProcessReponse(List<SearchResultItem> list, WebResponse resp)
        {
            var response = new StreamReader(resp.GetResponseStream()).ReadToEnd();

            var info = JsonConvert.DeserializeObject<BergGetStockResponse>(response, new JsonSerializerSettings()
            {
                Culture = CultureInfo.GetCultureInfo("ru-RU")
            });

            if (info != null && info.Resources.Length > 0)
            {
                foreach (var resource in info.Resources.Where(r => r.Offers != null))
                {
                    foreach (var offer in resource.Offers)
                    {
                        list.Add(new SearchResultItem()
                        {
                            Article = resource.Article,
                            Name = resource.Name,
                            Vendor = PartVendor.BERG,
                            VendorPrice = offer.Price,
                            Quantity = offer.Quantity,
                            VendorId = resource.Id,
                            Brand = resource.Brand.Name,
                            Warehouse = offer.Warehouse.Name,
                            DeliveryPeriod = offer.AveragePeriod,
                            WarehouseId = offer.Warehouse.Id.ToString()
                        });
                    }

                }
            }
        }
示例#22
0
        public static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }
        /// <summary>Print the error message as it came from the server.</summary>
        private void PrintErrorResponse(WebResponse response)
        {
            if (response == null)
            {
                return;
            }

            Stream responseStream = response.GetResponseStream();
            try
            {
                Stream errorStream = Console.OpenStandardError();
                try
                {
                    Copy(responseStream, errorStream);
                }
                finally
                {
                    errorStream.Close();
                }
            }
            finally
            {
                responseStream.Close();
            }
        }
示例#24
0
文件: JSON.cs 项目: Rezura/LiveSplit
 public static dynamic FromResponse(WebResponse response)
 {
     using (var stream = response.GetResponseStream())
     {
         return FromStream(stream);
     }
 }
        /// <summary>
        /// 从Response获取错误信息
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static WfServiceInvokeException FromWebResponse(WebResponse response)
        {
            StringBuilder strB = new StringBuilder();

            string content = string.Empty;

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
                content = streamReader.ReadToEnd();
            }

            if (response is HttpWebResponse)
            {
                HttpWebResponse hwr = (HttpWebResponse)response;

                strB.AppendFormat("Status Code: {0}, Description: {1}\n", hwr.StatusCode, hwr.StatusDescription);
            }

            strB.AppendLine(content);

            WfServiceInvokeException result = new WfServiceInvokeException(strB.ToString());

            if (response is HttpWebResponse)
            {
                HttpWebResponse hwr = (HttpWebResponse)response;

                result.StatusCode = hwr.StatusCode;
                result.StatusDescription = hwr.StatusDescription;
            }

            return result;
        }
示例#26
0
        private static string ExtractJsonResponse(WebResponse response)
        {
            GetRateLimits(response);

            var responseStream = response.GetResponseStream();
            if (responseStream == null)
            {
                throw new StackExchangeException("Response stream is empty, unable to continue");
            }

            string json;
            using (var outStream = new MemoryStream())
            {
                using (var zipStream = new GZipStream(responseStream, CompressionMode.Decompress))
                {
                    zipStream.CopyTo(outStream);
                    outStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(outStream, Encoding.UTF8))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }

            return json;
        }
示例#27
0
 private string ReadAll(WebResponse webResponse)
 {
     using (var reader = new StreamReader(webResponse.GetResponseStream()))
     {
         return reader.ReadToEnd();
     }
 }
示例#28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebResponseDetails"/> class.
        /// </summary>
        /// <param name="webResponse">The web response.</param>
        public WebResponseDetails(WebResponse webResponse)
        {
            if (webResponse == null)
            {
                throw new ArgumentNullException("webResponse", "Server response could not be null");
            }

            //
            // Copy headers
            this.Headers = new Dictionary<string,string>();
            if ((webResponse.Headers != null) && (webResponse.Headers.Count > 0))
            {
                foreach (string key in webResponse.Headers.AllKeys)
                    this.Headers.Add(key, webResponse.Headers[key]);
            }

            //
            // Copy body (raw)
            try
            {
                StreamReader reader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.Default);
                this.Body = reader.ReadToEnd();
            }
            catch (ArgumentNullException exp_null)
            {
                //
                // No response stream ?
                System.Diagnostics.Trace.WriteLine("WebResponse does not have any response stream");
                this.Body = string.Empty;
            }
        }
示例#29
0
 private string GetResponseContent(WebResponse response)
 {
     Encoding enc = Encoding.GetEncoding(65001);
     var stream = new StreamReader(response.GetResponseStream(), enc);
     string output = stream.ReadToEnd();
     stream.Close();
     return output;
 }
 public IEnumerable<string> ParseToLines(WebResponse response)
 {
     using (var response_stream = new StreamReader(response.GetResponseStream()))
     {
         while (!response_stream.EndOfStream)
             yield return response_stream.ReadLine();
     }
 }
示例#31
0
 private string reqGet(string url)
 {
     System.Net.WebRequest reqGET = System.Net.WebRequest.Create(@url);
     //reqGET.Credentials = System.Net.CredentialCache.DefaultCredentials;/WebAPIClient:VvqrUM29
     //reqGET.Credentials = new System.Net.NetworkCredential("n.sadovin@ws", "Sad0vin2014");
     reqGET.Credentials = new System.Net.NetworkCredential(_AuthUser, _AuthPassword);
     try
     {
         System.Net.WebResponse resp   = reqGET.GetResponse();
         System.IO.Stream       stream = resp.GetResponseStream();
         System.IO.StreamReader sr     = new System.IO.StreamReader(stream);
         string s = sr.ReadToEnd();
         return(s);
     }
     catch (System.Net.WebException WE)
     {
         //Сообщение об ошибке
         //   Console.WriteLine(WE.Message);
         //  Console.ReadLine();
         return(WE.Message);
     }
 }
示例#32
0
    /// <summary>
    /// 传入URL返回网页的html代码
    /// </summary>
    /// <param name="Url">URL</param>
    /// <returns></returns>
    public string getUrltoHtml(string Url)
    {
        string errorMsg = "";

        try
        {
            System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);

            System.Net.WebResponse wResp = wReq.GetResponse();

            System.IO.Stream respStream = wResp.GetResponseStream();

            System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));

            return(reader.ReadToEnd());
        }
        catch (System.Exception ex)
        {
            errorMsg = ex.Message;
        }
        return("");
    }
示例#33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string username         = "******";
        string password         = "******";
        string usernamePassword = username + ":" + password;

        string url        = "http://api.t.sina.com.cn/statuses/update.json";
        string news_title = "VS2010网剧合集:讲述程序员的爱情故事";
        int    news_id    = 62747;
        string t_news     = string.Format("{0},http://news.cnblogs.com/n/{1}/", news_title, news_id);
        string data       = "source=3854961754&status=" + System.Web.HttpUtility.UrlEncode(t_news);

        System.Net.WebRequest     webRequest  = System.Net.WebRequest.Create(url);
        System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest;

        System.Net.CredentialCache myCache = new System.Net.CredentialCache();
        myCache.Add(new Uri(url), "Basic", new System.Net.NetworkCredential(username, password));
        httpRequest.Credentials = myCache;
        httpRequest.Headers.Add("Authorization", "Basic " +
                                Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(usernamePassword)));


        httpRequest.Method      = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        System.Text.Encoding encoding = System.Text.Encoding.ASCII;
        byte[] bytesToPost            = encoding.GetBytes(data);
        httpRequest.ContentLength = bytesToPost.Length;
        System.IO.Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytesToPost, 0, bytesToPost.Length);
        requestStream.Close();

        System.Net.WebResponse wr            = httpRequest.GetResponse();
        System.IO.Stream       receiveStream = wr.GetResponseStream();
        using (System.IO.StreamReader reader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8))
        {
            string responseContent = reader.ReadToEnd();
            Response.Write(responseContent);
        }
    }
示例#34
0
    public static string Save(string user, string data)
    {
        string sendData = "user="******"&" + "data=" + data;           //发送的数据
        string url      = "http://192.168.199.185:8080/save/?" + sendData; //请求路径
                                                                           //string url = "http://192.168.199.107:8080/save/?" + sendData;//请求路径
        string backMsg = "";                                               //接收服务端返回数据

        try
        {
            System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
            httpRquest.Method = "GET";

            /*byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
             * System.IO.Stream requestStream = null;
             * if (string.IsNullOrWhiteSpace(sendData) == false)
             * {
             *  requestStream = httpRquest.GetRequestStream();
             *  requestStream.Write(dataArray, 0, dataArray.Length);
             *  requestStream.Close();
             * }*/
            System.Net.WebResponse response       = httpRquest.GetResponse();
            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
            backMsg = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            //requestStream.Dispose();
            responseStream.Close();
            responseStream.Dispose();
        }
        catch (System.Exception e1)
        {
            //Console.WriteLine(e1.ToString());
            Debug.Log(e1.ToString());
        }
        return(backMsg);
    }
示例#35
0
    /// <summary>
    /// a sub-function of saveQuestionImage
    /// </summary>
    /// <param name="imageURL"></param>
    /// <returns></returns>
    private System.Drawing.Image storeImage(string imageURL)
    {
        System.Drawing.Image img = null;

        try
        {
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageURL);
            //webRequest.AllowReadStreamBuffering = true;
            webRequest.Timeout = 30000;

            System.Net.WebResponse webResponse = webRequest.GetResponse();

            System.IO.Stream stream = webResponse.GetResponseStream();

            img = System.Drawing.Image.FromStream(stream);

            webResponse.Close();
        }
        catch (Exception ex)
        {
            return(null);
        }
        return(img);
    }
示例#36
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                //create a new myjsonrequest object from which data will be serialized
                JsonRequest myRequest = new JsonRequest();
                myRequest.InputObj = new CrmAzureMlDemo.Input1();
                Input input = new Input();

                string[] columns = { "address1_stateorprovince", "annualincome",            "lpa_age",
                                     "numberofchildren",         "educationcodename",       "familystatuscodename",
                                     "gendercodename",           "lpa_commutedistancename", "lpa_homeownername",
                                     "lpa_occupationname",       "lpa_numberofcarsowned",   "lpa_numberofchildrenathome" };

                object[] values = { StateOrProvince.Get(executionContext), AnnualIncome.Get(executionContext),    Age.Get(executionContext),
                                    NumChildren.Get(executionContext),     Education.Get(executionContext),       MaritalStatus.Get(executionContext),
                                    Gender.Get(executionContext),          CommuteDistance.Get(executionContext), Homeowner.Get(executionContext),
                                    Occupation.Get(executionContext),      NumCars.Get(executionContext),         NumChildrenAtHome.Get(executionContext) };

                input.Columns = columns;
                input.Values  = new object[][] { values };

                myRequest.InputObj.Inputs = new Input();
                myRequest.InputObj.Inputs = input;

                //serialize the myjsonrequest to json
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myRequest.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, myRequest);
                string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                //create the webrequest object and execute it (and post jsonmsg to it)
                System.Net.WebRequest req = System.Net.WebRequest.Create(Endpoint.Get(executionContext));

                //must set the content type for json
                req.ContentType = "application/json";

                //must set method to post
                req.Method = "POST";

                //add authorization header
                req.Headers.Add(string.Format("Authorization:Bearer {0}", ApiKey.Get(executionContext)));

                tracingService.Trace("json request: {0}", jsonMsg);

                //create a stream
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonMsg.ToString());
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                //get the response
                System.Net.WebResponse resp = req.GetResponse();

                Stream responseStream = CopyAndClose(resp.GetResponseStream());
                // Do something with the stream
                StreamReader reader         = new StreamReader(responseStream, Encoding.UTF8);
                String       responseString = reader.ReadToEnd();
                tracingService.Trace("json response: {0}", responseString);

                responseStream.Position = 0;
                //deserialize the response to a myjsonresponse object
                JsonResponse myResponse = new JsonResponse();
                System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                myResponse = deserializer.ReadObject(responseStream) as JsonResponse;

                //set output values from the fields of the deserialzed myjsonresponse object
                BikeBuyer.Set(executionContext, myResponse.Results.Output1.Value.Values[0][0]);
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
        private Image FetchCardImage(ScryfallCard card, bool frontFace)
        {
            Image  retval = null;
            string cardID = card.id;
            string imageURL;
            string imagePath;

            SqlCeCommand     cmd    = new SqlCeCommand("SELECT * FROM CardImage WHERE Card_ID = \'" + cardID + "\'", db.connection);
            SqlCeDataAdapter da     = new SqlCeDataAdapter(cmd);
            DataTable        result = new DataTable();

            da.Fill(result);


            switch (result.Rows.Count)
            {
            case 0:     // no rows returned
                // we want the front face
                if (frontFace)
                {
                    // if the card is single faced and the normal image url isn't misssing
                    if (card.image_uris != null && card.image_uris.normal != null)
                    {
                        imageURL = card.image_uris.normal;

                        System.Net.WebRequest  request        = System.Net.WebRequest.Create(imageURL);
                        System.Net.WebResponse response       = request.GetResponse();
                        System.IO.Stream       responseStream =
                            response.GetResponseStream();
                        retval = new Bitmap(responseStream);

                        string filePath = cardID + ".jpg";
                        retval.Save(".\\images\\" + filePath);
                        cmd = new SqlCeCommand("INSERT INTO CardImage (Card_ID, Image_URL, Local_Filepath)" +
                                               "VALUES (@Card_ID, @Image_URL, @Local_Filepath)", db.connection);
                        cmd.Parameters.AddWithValue("@Card_ID", cardID);
                        cmd.Parameters.AddWithValue("@Image_URL", imageURL);
                        cmd.Parameters.AddWithValue("@Local_Filepath", filePath);
                        cmd.ExecuteNonQuery();
                    }
                    // if the card is multifaced
                    else if (card.card_faces != null)
                    {
                        // if the front face image url is present
                        if (card.card_faces[0].image_uris != null && card.card_faces[0].image_uris.normal != null)
                        {
                            imageURL = card.card_faces[0].image_uris.normal;

                            System.Net.WebRequest  request        = System.Net.WebRequest.Create(imageURL);
                            System.Net.WebResponse response       = request.GetResponse();
                            System.IO.Stream       responseStream =
                                response.GetResponseStream();
                            retval = new Bitmap(responseStream);

                            string filePath = cardID + "_0" + ".jpg";

                            retval.Save(".\\images\\" + filePath);
                            cmd = new SqlCeCommand("INSERT INTO CardImage (Card_ID, Image_URL, Local_Filepath)" +
                                                   "VALUES (@Card_ID, @Image_URL, @Local_Filepath)", db.connection);
                            cmd.Parameters.AddWithValue("@Card_ID", cardID);
                            cmd.Parameters.AddWithValue("@Image_URL", imageURL);
                            cmd.Parameters.AddWithValue("@Local_Filepath", filePath);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    else
                    {
                        throw new Exception("wtf?");
                    }
                }
                else     // we want the back face (it must be multifaced)
                {
                    // if the back face url is present
                    if (card.card_faces[1].image_uris != null && card.card_faces[1].image_uris.normal != null)
                    {
                        imageURL = card.card_faces[1].image_uris.normal;

                        System.Net.WebRequest  request        = System.Net.WebRequest.Create(imageURL);
                        System.Net.WebResponse response       = request.GetResponse();
                        System.IO.Stream       responseStream =
                            response.GetResponseStream();
                        retval = new Bitmap(responseStream);

                        string filePath = cardID + "_1" + ".jpg";

                        retval.Save(".\\images\\" + filePath);
                        cmd = new SqlCeCommand("INSERT INTO CardImage (Card_ID, Image_URL, Local_Filepath)" +
                                               "VALUES (@Card_ID, @Image_URL, @Local_Filepath)", db.connection);
                        cmd.Parameters.AddWithValue("@Card_ID", cardID);
                        cmd.Parameters.AddWithValue("@Image_URL", imageURL);
                        cmd.Parameters.AddWithValue("@Local_Filepath", filePath);
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        throw new NotImplementedException("Image url missing!");
                    }
                }
                break;


            case 1:     // only one row returned
                if (frontFace)
                {
                    // if the card is NOT multifaced or the card is multifaced but one-sided
                    if (card.card_faces == null || card.card_faces[1].image_uris == null)
                    {
                        imagePath = result.Rows[0]["Local_Filepath"].ToString();
                        retval    = Bitmap.FromFile(".\\images\\" + imagePath);
                    }
                    else
                    {
                        throw new Exception("wtf");
                    }
                }
                else                                                                    // the card is multifaced and we want the back face
                {
                    if (result.Rows[0]["Local_Filepath"].ToString().EndsWith("_1.jpg")) // if somehow the only row returned is the back face image
                    {
                        imagePath = result.Rows[0]["Local_Filepath"].ToString();
                        retval    = Bitmap.FromFile(".\\images\\" + imagePath);
                    }
                    else if (card.card_faces[1].image_uris != null && card.card_faces[1].image_uris.normal != null)     // if the back face image url is present
                    {
                        imageURL = card.card_faces[1].image_uris.normal;

                        System.Net.WebRequest  request        = System.Net.WebRequest.Create(imageURL);
                        System.Net.WebResponse response       = request.GetResponse();
                        System.IO.Stream       responseStream =
                            response.GetResponseStream();
                        retval = new Bitmap(responseStream);

                        string filePath = cardID + "_1" + ".jpg";

                        retval.Save(".\\images\\" + filePath);
                        cmd = new SqlCeCommand("INSERT INTO CardImage (Card_ID, Image_URL, Local_Filepath)" +
                                               "VALUES (@Card_ID, @Image_URL, @Local_Filepath)", db.connection);
                        cmd.Parameters.AddWithValue("@Card_ID", cardID);
                        cmd.Parameters.AddWithValue("@Image_URL", imageURL);
                        cmd.Parameters.AddWithValue("@Local_Filepath", filePath);
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        throw new NotImplementedException("Second face image url missing!");
                    }
                }
                break;


            default:                                                                    // more than 1 row returned
                if (frontFace)                                                          // we want the front face
                {
                    if (result.Rows[0]["Local_Filepath"].ToString().EndsWith("_0.jpg")) // if row 1 is the front face
                    {
                        imagePath = result.Rows[0]["Local_Filepath"].ToString();
                        retval    = Bitmap.FromFile(".\\images\\" + imagePath);
                    }
                    else if (result.Rows[1]["Local_Filepath"].ToString().EndsWith("_0.jpg"))     // if row 2 is the front face
                    {
                        imagePath = result.Rows[1]["Local_Filepath"].ToString();
                        retval    = Bitmap.FromFile(".\\images\\" + imagePath);
                    }
                    else
                    {
                        throw new Exception("wtf");
                    }
                }
                else                                                                    // we want the back face
                {
                    if (result.Rows[0]["Local_Filepath"].ToString().EndsWith("_1.jpg")) // if row 1 is the back face
                    {
                        imagePath = result.Rows[0]["Local_Filepath"].ToString();
                        retval    = Bitmap.FromFile(".\\images\\" + imagePath);
                    }
                    else if (result.Rows[1]["Local_Filepath"].ToString().EndsWith("_1.jpg"))     // if row 2 is the back face
                    {
                        imagePath = result.Rows[1]["Local_Filepath"].ToString();
                        retval    = Bitmap.FromFile(".\\images\\" + imagePath);
                    }
                    else
                    {
                        throw new Exception("wtf");
                    }
                }
                break;
            }


            // OLD VERSION
            //if (frontFace && result.Rows.Count == 1)
            //{
            //    imageURL = result.Rows[0]["Local_Filepath"].ToString();
            //    retval = Bitmap.FromFile(".\\images\\" + imageURL);
            //} else
            //{
            //    if (frontFace && card.image_uris != null && card.image_uris.normal != null)
            //    {
            //        imageURL = card.image_uris.normal;

            //        System.Net.WebRequest request = System.Net.WebRequest.Create(imageURL);
            //        System.Net.WebResponse response = request.GetResponse();
            //        System.IO.Stream responseStream =
            //            response.GetResponseStream();
            //        retval = new Bitmap(responseStream);

            //        //string filePath = (".\\images\\" + cardID + ".jpg");
            //        string filePath = cardID + ".jpg";
            //        retval.Save(".\\images\\" + filePath);
            //        cmd = new SqlCeCommand("INSERT INTO CardImage (Card_ID, Image_URL, Local_Filepath)" +
            //                                "VALUES (@Card_ID, @Image_URL, @Local_Filepath)", db.connection);
            //        cmd.Parameters.AddWithValue("@Card_ID", cardID);
            //        cmd.Parameters.AddWithValue("@Image_URL", imageURL);
            //        cmd.Parameters.AddWithValue("@Local_Filepath", filePath);
            //        cmd.ExecuteNonQuery();
            //    }
            //    else if (card.card_faces != null && card.card_faces[0].image_uris != null && card.card_faces[0].image_uris.normal != null)
            //    {
            //        if (frontFace)
            //        {
            //            imageURL = card.card_faces[0].image_uris.normal;
            //        }
            //        else
            //        {
            //            if (card.card_faces[1] != null
            //                && card.card_faces[1].image_uris != null
            //                && card.card_faces[1].image_uris.normal != null)
            //                {
            //                    imageURL = card.card_faces[1].image_uris.normal;
            //                }
            //            else
            //            {
            //                throw new NotImplementedException("Second face has no image!");
            //            }
            //        }

            //        System.Net.WebRequest request = System.Net.WebRequest.Create(imageURL);
            //        System.Net.WebResponse response = request.GetResponse();
            //        System.IO.Stream responseStream =
            //            response.GetResponseStream();
            //        retval = new Bitmap(responseStream);

            //        //string filePath = (".\\images\\" + cardID + ".jpg");
            //        string filePath = cardID + ".jpg";
            //        retval.Save(".\\images\\" + filePath);
            //        cmd = new SqlCeCommand("INSERT INTO CardImage (Card_ID, Image_URL, Local_Filepath)" +
            //                                "VALUES (@Card_ID, @Image_URL, @Local_Filepath)", db.connection);
            //        cmd.Parameters.AddWithValue("@Card_ID", cardID);
            //        cmd.Parameters.AddWithValue("@Image_URL", imageURL);
            //        cmd.Parameters.AddWithValue("@Local_Filepath", filePath);
            //        cmd.ExecuteNonQuery();
            //    }

            //}

            return(retval);
        }
示例#38
0
        private void HTTP_PUT(string Url, string Data, JsonResultModel model, StreamWriter sw)
        {
            string Out   = String.Empty;
            string Error = String.Empty;
            String Log   = String.Empty;

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

            try
            {
                req.Method      = "PUT";
                req.Timeout     = 100000;
                req.ContentType = "application/json";

                byte[] sentData = Encoding.UTF8.GetBytes(Data);
                req.ContentLength = sentData.Length;

                Log = DateTime.Now + " :: Sent Request :: " + Data + Environment.NewLine;


                using (Stream sendStream = req.GetRequestStream())
                {
                    sendStream.Write(sentData, 0, sentData.Length);
                    sendStream.Close();
                }

                System.Net.WebResponse res = req.GetResponse();
                Stream ReceiveStream       = res.GetResponseStream();
                using (StreamReader sr = new
                                         StreamReader(ReceiveStream, Encoding.UTF8))
                {
                    Char[] read  = new Char[256];
                    int    count = sr.Read(read, 0, 256);

                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        Out  += str;
                        count = sr.Read(read, 0, 256);
                    }
                }
                Log               += DateTime.Now + " :: Received Request :: " + Out + Environment.NewLine;
                model.Results      = Out;
                model.ErrorMessage = Error;
                Log               += DateTime.Now + " :: ERRORS :: " + model.ErrorMessage + Environment.NewLine;
                model.Log          = Log;

                //File.AppendAllText(logFile1, model.Log);
                sw.WriteLine(model.Log);

                if (!string.IsNullOrWhiteSpace(Out))
                {
                    model.IsSuccess = true;
                }
                else
                {
                    model.IsSuccess = false;
                }
            }
            catch (ArgumentException ex)
            {
                Error = string.Format("ArgumentException raiesed trying to stream data to DOJ :: {0}", ex.Message);
                throw ex;
            }
            catch (WebException ex)
            {
                Error = string.Format("WebException raised! :: {0}", ex.Message);
                throw ex;
            }
            catch (Exception ex)
            {
                Error = string.Format("Exception raised! :: {0}", ex.Message);
                throw ex;
            }
        }
示例#39
0
        virtual public string HttpPost(string xmlRequest, Dictionary <String, String> config)
        {
            string logFile = null;

            if (config.ContainsKey("logFile"))
            {
                logFile = config["logFile"];
            }

            string uri = config["url"];

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);

            bool neuter = false;

            if (config.ContainsKey("neuterAccountNums"))
            {
                neuter = ("true".Equals(config["neuterAccountNums"]));
            }

            bool printxml = false;

            if (config.ContainsKey("printxml"))
            {
                if ("true".Equals(config["printxml"]))
                {
                    printxml = true;
                }
            }
            if (printxml)
            {
                Console.WriteLine(xmlRequest);
                Console.WriteLine(logFile);
            }

            //log request
            if (logFile != null)
            {
                log(xmlRequest, logFile, neuter);
            }

            req.ContentType = "text/xml";
            req.Method      = "POST";
            req.ServicePoint.MaxIdleTime       = 10000;
            req.ServicePoint.Expect100Continue = false;
            if (isProxyOn(config))
            {
                WebProxy myproxy = new WebProxy(config["proxyHost"], int.Parse(config["proxyPort"]));
                myproxy.BypassProxyOnLocal = true;
                req.Proxy = myproxy;
            }

            // submit http request
            using (var writer = new StreamWriter(req.GetRequestStream()))
            {
                writer.Write(xmlRequest);
            }



            // read response
            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null)
            {
                return(null);
            }
            string xmlResponse;

            using (var reader = new System.IO.StreamReader(resp.GetResponseStream()))
            {
                xmlResponse = reader.ReadToEnd().Trim();
            }
            if (printxml)
            {
                Console.WriteLine(xmlResponse);
            }

            //log response
            if (logFile != null)
            {
                log(xmlResponse, logFile, neuter);
            }

            return(xmlResponse);
        }
示例#40
0
        private void toolSendAll_Click(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    //Ping ping = new Ping();
                    //PingReply pingStatus = ping.Send("google.com");
                    var sign = context.Setting.FirstOrDefault();
                    if (sign.Signature == null || sign.Signature == "" || sign.NumberSms == null || sign.NumberSms == "")
                    {
                        MessageBox.Show("از قسمت تنظیمات امضا دیجیتال و شماره پیامک را ثبت کنید", "امضا دیجیتال ", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        return;
                    }
                    //***********baraye check kardane ertebat
                    HttpWebRequest         reqCheack  = (HttpWebRequest)WebRequest.Create("http://login.parsgreen.com/UrlService/sendSMS.ashx?from=");
                    System.Net.WebResponse respCheack = reqCheack.GetResponse();
                    //***********
                    //if (resp2 == encode2.)
                    //{
                    for (int i = 0; i < dgSearch.RowCount; i++)
                    {
                        string pattern = "http://login.parsgreen.com/UrlService/sendSMS.ashx?from=" + sign.NumberSms + "&to=" + dgSearch.CurrentRow.Cells[1].Value.ToString() + "&text=" + dgSearch.CurrentRow.Cells[2].Value.ToString() + "&signature=" + sign.Signature;

                        //MessageBox.Show(pattern);
                        System.IO.Stream       st = null;
                        System.IO.StreamReader sr = null;

                        HttpWebRequest req    = (HttpWebRequest)WebRequest.Create(pattern);
                        Encoding       encode = System.Text.Encoding.UTF8;

                        System.Net.WebResponse resp = req.GetResponse();

                        st = resp.GetResponseStream();
                        sr = new System.IO.StreamReader(st, Encoding.UTF8);
                        string result = sr.ReadToEnd().Substring(12, 1);
                        if (result == "0")
                        {
                            string id  = dgSearch.CurrentRow.Cells[6].Value.ToString();
                            var    del = context.ErsalNashode.Where(c => c.Id.ToString() == id).FirstOrDefault();
                            context.ErsalNashode.Remove(del);
                            context.SaveChanges();
                            Refresh_dgSearch();
                        }
                        sr.Close();
                        resp.Close();
                    }
                    //}
                }
                catch (Exception)
                {
                    MessageBox.Show("اینترنت وصل نیست", "اینترنت", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception)
            {
                //MessageBox.Show("اینترنت وصل نیست 2" + "\n" + ex.Message, "اینترنت", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //MessageBox.Show("ارسال نشده2" + "\n" + ex.Message);
            }
        }
示例#41
0
    public static DataTable GetCadastralInfoFromPKK_REST(string cadastral)
    {
        //System.Net.WebClient obj = new System.Net.WebClient();
        string rosreestr_id = "";
        string str_text     = "";
        //UTF8Encoding utf8 = new UTF8Encoding();
        //byte[] qqq;
        DataSet   dsCadastral;
        DataTable dtCadastral;
        DataRow   d_row;

        PKK_Property_Info pty = new PKK_Property_Info();

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


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

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

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

        //        str_text = utf8.GetString(qqq)

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


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

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

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

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

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

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

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

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

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

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

            default:
                break;
            }
            d_row["p_status_str"] = status_text;
        }
        dtCadastral.Rows.Add(d_row);
        return(dtCadastral);
    }
示例#42
0
 /// <summary>
 /// Запрос информации
 /// </summary>
 /// <param name="message"></param>
 /// <param name="metod"></param>
 /// <param name="accept"></param>
 /// <returns></returns>
 private string Select(string message, string metod, string accept)
 {
     try
     {
         HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(message);
         request.Method          = metod;
         request.PreAuthenticate = true;
         request.Credentials     = CredentialCache.DefaultCredentials;
         request.Accept          = accept;
         try
         {
             using (System.Net.WebResponse response = request.GetResponse())
             {
                 try
                 {
                     using (System.IO.StreamReader rd = new System.IO.StreamReader(response.GetResponseStream()))
                     {
                         return(rd.ReadToEnd());
                     }
                 }
                 catch (Exception e)
                 {
                     String.Format("Ошибка создания StreamReader ответа, метод {0}, accept {1}, e {2}", metod, accept, e).SaveError(e);
                     return(null);
                 }
             }
         }
         catch (Exception e)
         {
             String.Format("Ошибка получения ответа WebResponse, метод {0}, accept {1}, e {2}", metod, accept, e).SaveError(e);
             return(null);
         }
     }
     catch (Exception e)
     {
         String.Format("Ошибка выполнения метода Select(metod={0}, accept={1}, e {2}", metod, accept, e).SaveError(e);
         return(null);
     }
 }
示例#43
0
        /// <summary>
        /// 通讯函数
        /// </summary>
        /// <param name="url">请求Url</param>
        /// <param name="para">请求参数</param>
        /// <param name="method">请求方式GET/POST</param>
        /// <returns></returns>
        public static string SendRequest(string url, string para, string method = "GET")
        {
            string strResult = "";

            if (url == null || url == "")
            {
                return(null);
            }
            if (method == null || method == "")
            {
                method = "GET";
            }
            // GET方式
            if (method.ToUpper() == "GET")
            {
                try
                {
                    System.Net.WebRequest wrq = System.Net.WebRequest.Create(url + para);
                    wrq.Method = "GET";
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                    System.Net.WebResponse wrp = wrq.GetResponse();
                    System.IO.StreamReader sr  = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
                    strResult = sr.ReadToEnd();
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }
            // POST方式
            else if (method.ToUpper() == "POST")
            {
                if (para.Length > 0 && para.IndexOf('?') == 0)
                {
                    para = para.Substring(1);
                }
                WebRequest req = WebRequest.Create(url);
                req.Method      = "POST";
                req.ContentType = "application/x-www-form-urlencoded";

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                StringBuilder UrlEncoded = new StringBuilder();
                Char[]        reserved   = { '?', '=', '&' };
                byte[]        SomeBytes  = null;
                if (para != null)
                {
                    int i = 0, j;
                    while (i < para.Length)
                    {
                        j = para.IndexOfAny(reserved, i);
                        if (j == -1)
                        {
                            UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, para.Length - i), System.Text.Encoding.GetEncoding("gb2312")));
                            break;
                        }
                        UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, j - i), System.Text.Encoding.GetEncoding("gb2312")));
                        UrlEncoded.Append(para.Substring(j, 1));
                        i = j + 1;
                    }
                    SomeBytes         = Encoding.Default.GetBytes(UrlEncoded.ToString());
                    req.ContentLength = SomeBytes.Length;
                    Stream newStream = req.GetRequestStream();
                    newStream.Write(SomeBytes, 0, SomeBytes.Length);
                    newStream.Close();
                }
                else
                {
                    req.ContentLength = 0;
                }
                try
                {
                    WebResponse result        = req.GetResponse();
                    Stream      ReceiveStream = result.GetResponseStream();
                    Byte[]      read          = new Byte[512];
                    int         bytes         = ReceiveStream.Read(read, 0, 512);
                    while (bytes > 0)
                    {
                        // 注意:
                        // 下面假定响应使用 UTF-8 作为编码方式。
                        // 如果内容以 ANSI 代码页形式(例如,932)发送,则使用类似下面的语句:
                        // Encoding encode = System.Text.Encoding.GetEncoding("shift-jis");
                        Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
                        strResult += encode.GetString(read, 0, bytes);
                        bytes      = ReceiveStream.Read(read, 0, 512);
                    }
                    return(strResult);
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }
            return(strResult);
        }
示例#44
0
        ///// <summary>
        ///// Response from POST
        ///// </summary>
        ///// <returns></returns>
        //public string PostReturnResponse()
        //{
        //    return PostReturnResponse(false, false, false);
        //}


        /// <summary>
        /// POSTs to a URL and returns the response string
        /// </summary>
        /// <param name="UseFullPostingUrl">Use the full url, which includes the encoded POST data. default is to use the base URL</param>
        /// <param name="EncodeSpacesAs20">Fixes space-encoding to use %20 rather than %2b</param>
        /// <returns>Response from POSTed-to server</returns>
        public string PostReturnResponse(bool UseFullPostingUrl = false, bool EncodeSpacesAs20 = false, bool DontEncodeFormData = false)
        {
            //if (FixError417)
            //{
            //    System.Net.ServicePointManager.Expect100Continue = false;
            //}
            string ResponseString = "";
            string PostingUrl     = this.Url;

            if (UseFullPostingUrl)
            {
                PostingUrl = this.FullPostingUrl(EncodeSpacesAs20);
            }

            this.LogPostInfo("RemotePost.PostReturnResponse PARAMS : "
                             + "[UseFullPostingUrl=" + UseFullPostingUrl
                             + "] [EncodeSpacesAs20=" + EncodeSpacesAs20
                             + "] [DontEncodeFormData" + DontEncodeFormData
                             + "]");



            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PostingUrl);

            if (this.PreventFailedExpectationError == true)
            {
                req.ServicePoint.Expect100Continue = false;
            }

            //Add these, as we're doing a POST
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = "POST";
            this.LogPostInfo("RemotePost.PostReturnResponse : request.RequestUri=" + req.RequestUri);


            try
            {
                if (this.CookieContainer != null)
                {
                    this.LogPostInfo("RemotePost.PostReturnResponse : CookieContainer.Count=" + this.CookieContainer.Count);
                    req.CookieContainer = this.CookieContainer;
                    this.LogPostInfo("RemotePost.PostReturnResponse : req-num of Cookies = " + req.CookieContainer.Count);
                }
                else
                {
                    this.LogPostInfo("RemotePost.PostReturnResponse : CookieContainer IS NULL");
                }
            }
            catch (Exception ex)
            {
                this.LogPostInfo("RemotePost.PostReturnResponse : Error w. Cookie Container: " + ex.Message, true);
            }

            //We need to count how many bytes we're sending.
            //Post'ed Faked Forms should be name=value&
            string AllData = this.GetQueryStringFormattedData(EncodeSpacesAs20, DontEncodeFormData);

            this.LogPostInfo("RemotePost.PostReturnResponse : QueryStringFormattedData=" + AllData);

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(AllData);
            this.LogPostInfo("RemotePost.PostReturnResponse : bytes=" + bytes.ToString());
            req.ContentLength = bytes.Length;
            this.LogPostInfo("RemotePost.PostReturnResponse : req.ContentLength=" + req.ContentLength);
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();

            try
            {
                System.Net.WebResponse resp = req.GetResponse();
                if (resp == null)
                {
                    return(null);
                }
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                ResponseString = sr.ReadToEnd().Trim();
            }
            catch (Exception RespEx)
            {
                //TODO: Update using new code pattern:
                //var functionName = string.Format("{0}.GetMySQLDataSet", ThisClassName);
                //var msg = string.Format("");

                this.LogPostInfo("RemotePost.PostReturnResponse : Error during GetResponse:", true);
                //Info.LogException("RemotePost.PostReturnResponse", RespEx);
                ResponseString = "Error - " + RespEx.Message;
            }

            this.LogPostInfo("RemotePost.PostReturnResponse : ResponseString=" + ResponseString);

            return(ResponseString);
        }
示例#45
0
        ///////////////////////////////////////////////////////////////////////////////////////
        public static bool HttpGet(String strUrl, int timeout, out String outResponse)
        {
            //*****parameters: timout in ms
            outResponse = "";

            //-----Request
            // Initialize the WebRequest.
            System.Net.WebRequest myRequest;
            try {
                myRequest         = System.Net.WebRequest.Create(strUrl);
                myRequest.Timeout = timeout;
            }
            catch (Exception ex) {
                String msg = ex.Message;
                return(false);
            }


            //-----Response
            // return the response.
            System.Net.WebResponse myResponse = null;


            //[rev]
            if (CString.StartWith(strUrl, "https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            }

            try {
                myResponse = myRequest.GetResponse();
                String strResponse = StreamToUTF8String(myResponse.GetResponseStream());

                outResponse = strResponse;

                // Code to use the WebResponse goes here.
                // Close the response to free resources.
                myResponse.Close();

                //OK
                return(true);
            }
            //catch (Exception ex) {
            //    String msg = ex.Message;
            //    if (myResponse !=null) {
            //        myResponse.Close();
            //    }

            //    return false;
            //}
            catch (WebException ex) {
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        outResponse = "NotFound";
                    }
                    else if (resp.StatusCode == HttpStatusCode.BadRequest)
                    {
                        outResponse = "BadRequest";
                    }
                    else
                    {
                        outResponse = "";
                    }
                }
                else
                {
                    outResponse = "";
                }

                //String msg = ex.Message;
                if (myResponse != null)
                {
                    myResponse.Close();
                }

                return(false);
            }
        }
        public ActionResult MZ()
        {
            #region 组装数据
            string _other      = "868232000894311";
            string _productid  = "Chip_12";
            int    _identityid = 88;
            int    _othertype  = 2;
            string _customsign = "";
            string _transtime  = "1460182643";
            _customsign = Utils.MD5(string.Concat(_transtime, _identityid, _othertype, _other, _productid, _key));
            #endregion

            #region 生成订单
            string url = payUrl + "/Pay/YYHPay?" + @"
other=" + _other + @"&
productid=" + _productid + @"&
identityid=" + _identityid + @"&
othertype=" + _othertype + @"&
customsign=" + _customsign + @"&
transtime=" + _transtime + @"
";
            url = url.Replace("\r", "").Replace("\n", "");

            System.Net.WebRequest wReq = System.Net.WebRequest.Create(url);

            System.Net.WebResponse wResp      = wReq.GetResponse();
            System.IO.Stream       respStream = wResp.GetResponseStream();
            // Dim reader As StreamReader = New StreamReader(respStream)
            string s = "";
            using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream))
            {
                s = reader.ReadToEnd();
            }
            string order = "";
            #endregion

            #region 发货


            string json = "transdata={\"exorderno\":\"YYHPay20160411114633262\",\"transid\":\"Simulated00000000000\",\"waresid\":1,\"appid\":\"5000805433\",\"feetype\":0,\"money\":100,\"count\":1,\"result\":0,\"transtype\":0,\"transtime\":\"2016-04-09 14:30:11\",\"cpprivate\":\"515游戏-1元首冲大礼包\",\"paytype\":401}&sign=7ee830b175e9de8d24f199a718daa9fd 6c6def0ccada85dab58e0ae796283fa6 2a01126a488b125dbcdbb714f2db6466 ";

            string callbackurl = payUrl + "/Callback/YYHPay";

            callbackurl = callbackurl.Replace("\r", "").Replace("\n", "");
            System.Net.WebRequest cwReq = System.Net.WebRequest.Create(callbackurl);
            byte[] requestBytes         = System.Text.Encoding.UTF8.GetBytes(json);
            cwReq.Method        = "POST";
            cwReq.ContentType   = "text/xml";
            cwReq.ContentLength = requestBytes.Length;
            Stream requestStream = cwReq.GetRequestStream();
            requestStream.Write(requestBytes, 0, requestBytes.Length);
            requestStream.Close();
            System.Net.WebResponse cResp       = cwReq.GetResponse();
            System.IO.Stream       crespStream = cResp.GetResponseStream();
            // Dim reader As StreamReader = New StreamReader(respStream)
            string cs = "";
            using (System.IO.StreamReader creader = new System.IO.StreamReader(crespStream))
            {
                cs = creader.ReadToEnd();
            }
            return(Content("1"));

            #endregion
        }
        public static T SendRequest <T>(string url, List <KeyValuePair <string, string> > paraList, string method, ref string cookie)
        {
            T result = default(T);

            if (url == null || url == "")
            {
                return(result);
            }
            if (string.IsNullOrWhiteSpace(method))
            {
                method = "GET";
            }

            if (url.StartsWith("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }


            // GET方式
            if (method.ToUpper() == "GET")
            {
                string fullUrl = url.TrimEnd('?') + "?";
                if (paraList != null)
                {
                    foreach (KeyValuePair <string, string> kv in paraList)
                    {
                        //Jin:Uri.EscapeDataString是最完美URLENCODE方案
                        fullUrl += kv.Key + "=" + Uri.EscapeDataString(kv.Value) + "&";
                    }
                    fullUrl = fullUrl.TrimEnd('&');
                }

                var wrq = System.Net.WebRequest.Create(fullUrl) as HttpWebRequest;

                if (url.StartsWith("https://"))
                {
                    wrq.ProtocolVersion = HttpVersion.Version10;
                }

                wrq.Method = "GET";
                if (!string.IsNullOrEmpty(cookie))
                {
                    wrq.Headers.Add("Cookie", cookie);
                }

                System.Net.WebResponse response = wrq.GetResponse();
                var header = response.Headers;
                cookie = header["Set-Cookie"];

                System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));

                string strResult = sr.ReadToEnd();
                sr.Close();
                response.Close();

                result = ServiceStack.Text.JsonSerializer.DeserializeFromString <T>(strResult);
            }

            // POST方式
            if (method.ToUpper() == "POST")
            {
                url = url.TrimEnd('?');
                var wrq = WebRequest.Create(url) as HttpWebRequest;

                if (url.StartsWith("https://"))
                {
                    wrq.ProtocolVersion = HttpVersion.Version10;
                }

                wrq.Method      = "POST";
                wrq.ContentType = "application/x-www-form-urlencoded";
                wrq.Headers.Add("X-OSVersion", "6.0.1");
                wrq.Headers.Add("x-kjt-app-id", "47ac0aa15d54");

                StringBuilder sbPara     = new StringBuilder();
                string        paraString = string.Empty;
                if (paraList != null)
                {
                    foreach (KeyValuePair <string, string> kv in paraList)
                    {
                        sbPara.Append(kv.Key + "=" + kv.Value + "&");
                    }
                    paraString = sbPara.ToString().TrimEnd('&');

                    byte[]           buf           = System.Text.Encoding.GetEncoding("utf-8").GetBytes(paraString);
                    System.IO.Stream requestStream = wrq.GetRequestStream();
                    requestStream.Write(buf, 0, buf.Length);
                    requestStream.Close();
                }
                else
                {
                    wrq.ContentLength = 0;
                }

                HttpWebResponse response  = null;
                StreamReader    reader    = null;
                string          strResult = string.Empty;

                try
                {
                    response = wrq.GetResponse() as HttpWebResponse;
                    var header = response.Headers;
                    cookie = header["Set-Cookie"];
                    Encoding htmlEncoding = Encoding.UTF8;
                    reader    = new StreamReader(response.GetResponseStream(), htmlEncoding);
                    strResult = reader.ReadToEnd();
                    reader.Close();
                    response.Close();
                }
                catch (WebException e)
                {
                    throw new Exception(string.Format("调用接口有问题: {0}", e.Message));
                }
                catch (Exception e)
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }

                    if (response != null)
                    {
                        response.Close();
                    }
                }
                if (!string.IsNullOrWhiteSpace(strResult))
                {
                    result = ServiceStack.Text.JsonSerializer.DeserializeFromString <T>(strResult);
                }
            }
            return(result);
        }
示例#48
0
        /// <summary>
        /// Realiza la petición utilizando el método POST y devuelve la respuesta del servidor
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <author>Findemor http://findemor.porExpertos.es</author>
        /// <history>Creado 17/02/2012</history>
        private static string GetResponse_POST(string url, Dictionary <string, string> parameters)
        {
            try{
                //Concatenamos los parametros, OJO: NO se añade el caracter "?"
                string parametrosConcatenados = ConcatParams(parameters);

                System.Net.WebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                wr.Method = "POST";

                wr.ContentType = "application/x-www-form-urlencoded";

                System.IO.Stream newStream;
                //Codificación del mensaje
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] byte1 = encoding.GetBytes(parametrosConcatenados);
                wr.ContentLength = byte1.Length;
                //Envio de parametros
                newStream = wr.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);

                // Obtiene la respuesta
                System.Net.WebResponse response = wr.GetResponse();
                // Stream con el contenido recibido del servidor
                newStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
                // Leemos el contenido
                string responseFromServer = reader.ReadToEnd();

                // Cerramos los streams
                reader.Close();
                newStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (System.Web.HttpException ex) {
                if (ex.ErrorCode == 404)
                {
                    throw new Exception("Not found remote service " + url);
                }
                else
                {
                    throw new Exception("Error: " + ex.GetHtmlErrorMessage());
                }
            }catch (System.Net.WebException ex) {
                using (WebResponse response = ex.Response){
                    if (response != null)
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)response;
                        if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
                        {
                            using (System.IO.Stream data = response.GetResponseStream())
                                using (var reader = new System.IO.StreamReader(data)) {
                                    string text = reader.ReadToEnd();
                                    return(text);
                                }
                        }
                    }
                    throw ex;
                }
            }
        }
示例#49
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack && !Page.IsPostBack)
        {
            if (this.UserSettings == null || this.TabId == null)
            {
                throw new Exception("Find Invite Control missing parameters");
            }
            if (this.IsInviteOnly)
            {
                panelManualSearch.Visible = false;
                atiFoundPanel.Visible     = true;
                //   ScriptManager.RegisterStartupScript(this, Page.GetType(), "ContactInviteList", "$(function(){ Aqufit.Page.atiContactInviteScript.generateStreamDom('{}'); });", true);
            }
            if (this.IsInviteOnly && this.GroupSettings != null)
            {
                atiContactInviteScript.UserSettings  = this.GroupSettings;
                atiFoundFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.GROUP_INVITE;
            }
            else
            {
                atiContactInviteScript.UserSettings  = this.UserSettings;
                atiFoundFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_REQUEST;
            }
            if (Request[Parameters.OAuth_Token] != null && Request[Parameters.OAuth_Verifier] != null && Context.Items["s"] != null)
            {
                this.IsOAuthPostback = true;
                string serviceType = ((string)Context.Items["s"]).ToLower();

                string returnUri = string.Empty;
                if (this.IsInviteOnly && this.GroupSettings != null)
                {
                    atiContactInviteScript.UserSettings = this.GroupSettings;
                    returnUri = "http://" + Request.Url.Host + ResolveUrl("~/") + TabId + "/" + GroupSettings.UserName + "/" + serviceType + "/contacts";
                }
                else
                {
                    atiContactInviteScript.UserSettings = this.UserSettings;
                    returnUri = "http://" + Request.Url.Host + ResolveUrl("~/") + TabId + "/" + UserSettings.UserName + "/" + serviceType + "/contacts";
                }
                IOAuthSession oauthSession = OAuthSessionFactory.createSession(serviceType, returnUri);

                string requestTokenString = Request[Parameters.OAuth_Token];
                string verifier           = Request[Parameters.OAuth_Verifier];
                IToken requestToken       = (IToken)Session[requestTokenString];

                IToken accessToken;

                try
                {
                    accessToken = oauthSession.ExchangeRequestTokenForAccessToken(requestToken, verifier);
                    oauthSession.AccessToken    = accessToken;
                    Session[requestTokenString] = null;
                    Session[accessToken.Token]  = accessToken;
                    //Response.Write(test);
                    ContactSearchResults(oauthSession.GetContactsEmails());
                }
                catch (OAuthException authEx)
                {
                    Session["problem"] = authEx.Report;
                    Response.Write(authEx.Message + "<br/><br/>" + authEx.StackTrace);
                    return;
                }
            }
            else if (Request["ConsentToken"] != null)      // We have a windows live login ( OMFG I wish they had OAuth sorted out like the rest of the world )
            {
                string ConsentToken = Request["ConsentToken"];
                System.Collections.Specialized.NameValueCollection consent = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(ConsentToken));
                string uri = "https://livecontacts.services.live.com/@L@" + consent["lid"] + "/rest/LiveContacts/Contacts/";
                //string uri2 = "https://livecontacts.services.live.com/users/@L@" + consent["lid"] + "/rest/livecontacts";
                System.Net.WebRequest request = System.Net.HttpWebRequest.Create(uri);
                request.Method = "GET";
                request.Headers.Add("UserAgent", "Windows Live Data Interactive SDK");
                request.ContentType = "application/xml; charset=utf-8";
                request.Headers.Add("Authorization", "DelegatedToken dt=\"" + consent["delt"] + "\"");
                request.Headers["Cookie"] = Response.Headers["Set-Cookie"];
                System.Net.WebResponse response       = request.GetResponse();
                System.IO.Stream       responseStream = response.GetResponseStream();
                System.IO.StreamReader streamReader   = new System.IO.StreamReader(responseStream);
                string resString = streamReader.ReadToEnd();
                System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Parse(resString);
                //<Contacts>
                //  <Contact><ID>b41c2cec-e5c7-426c-b8e6-0043e7cdaeb0</ID>
                //  <Profiles><Personal><FirstName>Krista</FirstName><LastName>Greeves</LastName><UniqueName>bluegirl</UniqueName><SortName>Greeves,Krista</SortName><DisplayName>bluegirl</DisplayName></Personal></Profiles>
                //  <Emails>
                //      <Email><ID>1</ID><EmailType>Personal</EmailType><Address>[email protected]</Address><IsIMEnabled>false</IsIMEnabled><IsDefault>true</IsDefault></Email>
                //  </Emails></Contact>

                //  Affine.Data.json.Contact[] contactList = doc.Element("Contacts").Descendants("Email").Select(c => new Affine.Data.json.Contact() { Email = c.Element("Address").Value }).OrderBy(c => c.Email).ToArray();
                // We need to find all the contacts that are in the system now.
                //ContactSearchResults(contactList);
                ContactSearchResults(doc.Element("Contacts").Descendants("Email").Select(c => c.Element("Address").Value).ToArray());
            }

            SetupOauth();
        }
    }
示例#50
0
        public static string GetExternalIPAddress()
        {
            string result = string.Empty;

            try {
                using (var client = new WebClient()) {
                    client.Headers["User-Agent"] =
                        "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                        "(compatible; MSIE 6.0; Windows NT 5.1; " +
                        ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                    try {
                        byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");

                        string response = System.Text.Encoding.UTF8.GetString(arr);

                        result = response.Trim();
                    }
                    catch (WebException) {
                    }
                }
            }
            catch {
            }

            if (string.IsNullOrEmpty(result))
            {
                try {
                    result = new WebClient().DownloadString("https://ipinfo.io/ip").Replace("\n", "");
                }
                catch {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try {
                    result = new WebClient().DownloadString("https://api.ipify.org").Replace("\n", "");
                }
                catch {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try {
                    result = new WebClient().DownloadString("https://icanhazip.com").Replace("\n", "");
                }
                catch {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try {
                    result = new WebClient().DownloadString("https://wtfismyip.com/text").Replace("\n", "");
                }
                catch {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try {
                    result = new WebClient().DownloadString("http://bot.whatismyipaddress.com/").Replace("\n", "");
                }
                catch {
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                try {
                    string url = "http://checkip.dyndns.org";
                    System.Net.WebRequest  req  = System.Net.WebRequest.Create(url);
                    System.Net.WebResponse resp = req.GetResponse();
                    System.IO.StreamReader sr   = new System.IO.StreamReader(resp.GetResponseStream());
                    string   response           = sr.ReadToEnd().Trim();
                    string[] a  = response.Split(':');
                    string   a2 = a[1].Substring(1);
                    string[] a3 = a2.Split('<');
                    result = a3[0];
                }
                catch (Exception) {
                }
            }

            return(result);
        }
示例#51
0
        //public connectionStatus HTTP_Connection()
        //{
        //    connectionStatus connectStat = new connectionStatus();
        //    connectStat.error = String.Empty;
        //    System.Net.WebRequest req = System.Net.WebRequest.Create(TestDOJUrl);
        //    try
        //    {
        //        connectStat.connected = false;

        //        var response = (HttpWebResponse)req.GetResponse();
        //        if (response.StatusCode == HttpStatusCode.OK)
        //        {
        //            //  it is responsive
        //            connectStat.error = string.Format("{0} Available", TestDOJUrl);
        //            connectStat.connected = true;
        //        }
        //        else
        //        {
        //            connectStat.error = string.Format("{0} Returned, but with status: {1}",
        //                TestDOJUrl, response.StatusDescription);
        //        }
        //        return connectStat;
        //    }
        //    catch (Exception ex)
        //    {
        //        //  not available at all, for some reason
        //        connectStat.error = string.Format("{0} unavailable: {1}", TestDOJUrl, ex.Message);
        //        connectStat.connected = false;
        //        return connectStat;
        //    }
        //}

        public connectionStatus HTTP_Connection()
        {
            try
            {
                string       Out   = String.Empty;
                string       Error = String.Empty;
                string       Log   = String.Empty;
                ExtractJNode eJson;

                connectionStatus connectStat = new connectionStatus();
                connectStat.error     = String.Empty;
                connectStat.connected = true;
                DOJWebApiUrl          = ConfigurationManager.AppSettings["DOJWebApiUrl"];

                System.Net.WebRequest req = System.Net.WebRequest.Create(DOJWebApiUrl);

                req.Method      = "PUT";
                req.Timeout     = 100000;
                req.ContentType = "application/json";

                byte[] sentData = Encoding.UTF8.GetBytes(connectionTestData);
                req.ContentLength = sentData.Length;

                using (Stream sendStream = req.GetRequestStream())
                {
                    sendStream.Write(sentData, 0, sentData.Length);
                    sendStream.Close();
                }

                System.Net.WebResponse res = req.GetResponse();
                Stream ReceiveStream       = res.GetResponseStream();
                using (StreamReader sr = new
                                         StreamReader(ReceiveStream, Encoding.UTF8))
                {
                    Char[] read  = new Char[256];
                    int    count = sr.Read(read, 0, 256);

                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        Out  += str;
                        count = sr.Read(read, 0, 256);
                    }
                }
                JObject o = JObject.Parse(Out);
                eJson = new ExtractJNode("Messages.Code", o);
                string code = eJson.traverseNode();
                if (code == "SYSERR")
                {
                    eJson = new ExtractJNode("Messages.Message", o);
                    string message = eJson.traverseNode();
                    connectStat.error     = code + " : " + message;
                    connectStat.connected = false;
                }
                return(connectStat);
            }
            catch (Exception error)
            {
                string err = error.Message;
                throw error;
            }
        }
        public void ResizeFromUrl(string url, decimal?width, decimal?height)
        {
            ImageFormat _format = ImageFormat.Jpeg;

            Response.ContentType = "image/jpeg";
            Color _backgroundColor = Color.White;
            bool  isImage          = true;

            string extension = url.Substring(url.LastIndexOf('.') + 1);

            switch (extension.ToLower())
            {
            case "jpg":
            case "jpeg":
                _format = ImageFormat.Jpeg;
                Response.ContentType = "image/jpeg";
                break;

            case "png":
                _format = ImageFormat.Png;
                Response.ContentType = "image/png";
                _backgroundColor     = Color.Transparent;
                break;

            case "gif":
                _format = ImageFormat.Gif;
                Response.ContentType = "image/gif";
                _backgroundColor     = Color.Transparent;
                break;

            // for unknown types
            default:
                isImage = false;
                _format = ImageFormat.Png;
                Response.ContentType = "image/png";
                _backgroundColor     = Color.Transparent;
                break;
            }

            Image img = null;

            if (isImage)
            {
                try
                {
                    // Open a connection
                    System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

                    //_HttpWebRequest.AllowWriteStreamBuffering = true;

                    //_HttpWebRequest.Referer = "http://www.google.com/";

                    // set timeout for 20 seconds (Optional)
                    //_HttpWebRequest.Timeout = 20000;

                    // Request response:
                    using (System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse())
                    {
                        // Open data stream:
                        using (System.IO.Stream _WebStream = _WebResponse.GetResponseStream())
                        {
                            // convert webstream to image
                            img = Image.FromStream(_WebStream);
                        }
                    }
                }
                catch (Exception _Exception)
                {
                    // Error
                    Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
                }
            }

            if (img != null)
            {
                int _width  = width.HasValue ? (int)width : img.Width;
                int _height = height.HasValue ? (int)height : img.Height;
                var im      = ImageUtility.GetFixedSizeImage(img, _width, _height, true, _backgroundColor);

                EncoderParameters eps = new EncoderParameters(1);
                eps.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);

                im.Save(Response.OutputStream, _format);
            }
        }
示例#53
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the context
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService             tracingService = executionContext.GetExtension <ITracingService>();

            try
            {
                JSONRequestResponse request = new JSONRequestResponse();
                request.InputObj = new TitanicPlugins.Input1();
                //request.inputObj2 = new Dictionary<string, string>() { };
                Input    input   = new Input();
                string[] columns = { "PassengerId", "Age", "Cabin", "Embarked", "Fare", "Name", "Parch", "Pclass", "SibSp", "Sex", "Ticket", "Survived" };
                object[] values  = { PassengerId.Get(executionContext), Age.Get(executionContext),    Cabin.Get(executionContext), Embarked.Get(executionContext), Fare.Get(executionContext),   Name.Get(executionContext),
                                     Parch.Get(executionContext),        Pclass.Get(executionContext), SibSp.Get(executionContext), Sex.Get(executionContext),      Ticket.Get(executionContext), Survived.Get(executionContext) };
                input.Columns           = columns;
                input.Values            = new object[][] { values };
                request.InputObj.Inputs = new Input();
                request.InputObj.Inputs = input;

                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(request.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, request);
                string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                const string endpoint = "https://ussouthcentral.services.azureml.net/workspaces/92e7c840c83f4673ac594e767da8b538/services/e8b5c75d168345189225fcb5eab964d5/execute?api-version=2.0";
                const string apiKey   = "PjAGXQN7aI8FhJ+bVPi7wFEt6QeUzLMTkx7FTkOcjxakVv2Fq4r8VNdnirlK2tBSIqp58sF4UiJ1tXT+l2eiTQ==";

                System.Net.WebRequest req = System.Net.WebRequest.Create(endpoint);
                req.ContentType = "application/json";
                req.Method      = "POST";
                req.Headers.Add(string.Format("Authorization:Bearer {0}", apiKey));


                //create a stream
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonMsg.ToString());
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                //get the response
                System.Net.WebResponse resp = req.GetResponse();

                Stream responseStream = CopyAndClose(resp.GetResponseStream());
                // Do something with the stream
                StreamReader reader         = new StreamReader(responseStream, Encoding.UTF8);
                String       responseString = reader.ReadToEnd();
                tracingService.Trace("json response: {0}", responseString);

                responseStream.Position = 0;
                //deserialize the response to a myjsonresponse object
                JsonResponse myResponse = new JsonResponse();
                System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                myResponse = deserializer.ReadObject(responseStream) as JsonResponse;

                tracingService.Trace("Scored Label- " + myResponse.Results.Output1.Value.Values[0][9]);
                tracingService.Trace("Scored Probablility- " + myResponse.Results.Output1.Value.Values[0][10]);

                ScoredLabel.Set(executionContext, myResponse.Results.Output1.Value.Values[0][9]);
                ScoredProbability.Set(executionContext, myResponse.Results.Output1.Value.Values[0][10]);
            }
            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }
        }
示例#54
0
文件: JZLog.cs 项目: RoOoOom/Assets
    private static void CaptureLog(string condition, string stacktrace, LogType type)
    {
        if (type == LogType.Error)
        {
            errorDict.Clear();

            string url = ServerInfoConfig.GetErrorURL();
            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            errorDict.Add("msg", condition + "\n" + stacktrace);
            errorDict.Add("game", ServerInfoConfig.GetGame());
            errorDict.Add("environment", "android");
            string deviceID = "";
            //string deviceID = SystemInfo.deviceUniqueIdentifier;
            if (!string.IsNullOrEmpty(deviceID))
            {
                errorDict.Add("deviceId", deviceID);
            }
            string deviceName = "";
            if (!string.IsNullOrEmpty(deviceName))
            {
                errorDict.Add("deviceName", deviceName);
            }
            string platform = "jzwl";
            if (!string.IsNullOrEmpty(platform))
            {
                errorDict.Add("platform", platform);
            }
            string accountName = "";
            if (!string.IsNullOrEmpty(accountName))
            {
                errorDict.Add("account", accountName);
            }
            string accountTicket = "";
            if (!string.IsNullOrEmpty(accountName))
            {
                errorDict.Add("ticket", accountTicket);
            }
            long playerId = 0;
            if (playerId != 0)
            {
                errorDict.Add("playerId", playerId.ToString());
            }

            if (errorDict != null && errorDict.Count > 0)
            {
                string reqUrl = url + "?";
                foreach (KeyValuePair <string, string> post_arg in errorDict)
                {
                    reqUrl += post_arg.Key + "=" + WWW.EscapeURL(post_arg.Value, System.Text.Encoding.UTF8) + "&";
                }
                reqUrl = reqUrl.Remove(reqUrl.Length - 1);

                try
                {
                    System.Net.WebRequest  wReq  = System.Net.WebRequest.Create(reqUrl);
                    System.Net.WebResponse wResp = wReq.GetResponse();
                    wResp.GetResponseStream();
                }
                catch (System.Exception)
                {
                    //errorMsg = ex.Message;
                }
            }
        }
    }
        // Credits Cristian Romanescu @ http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
        static void HttpUploadFile(string url, byte[] fileContents, string fileParam, string fileName, string contentType, System.Collections.Specialized.NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

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

            System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            //HACK: add proxy
            IWebProxy proxy = WebRequest.GetSystemWebProxy();

            proxy.Credentials  = System.Net.CredentialCache.DefaultCredentials;
            wr.Proxy           = proxy;
            wr.PreAuthenticate = true;
            //HACK: end add proxy
            wr.Accept      = "text/html,application/xml";
            wr.UserAgent   = "Mozilla/5.0"; // Fix HTTP Error 406 Not acceptable - Security incident detected
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method      = "POST";

            System.IO.Stream rs = wr.GetRequestStream();

            {
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n";
                foreach (string key in nvc.Keys)
                {
                    // Parameter Header (+ boundary)
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                    string header      = string.Format(formdataTemplate, key);
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    rs.Write(headerbytes, 0, headerbytes.Length);

                    // Parameter Content
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(nvc[key].ToString());
                    rs.Write(buffer, 0, buffer.Length);
                }
            }
            {
                // File Header (+ boundary)
                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, fileParam, fileName, contentType);
                byte[] headerbytes    = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                // File Content
                rs.Write(fileContents, 0, fileContents.Length);
            }
            {
                // WebRequest Trailer
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
            }
            rs.Close();

            try
            {
                using (System.Net.WebResponse wresp = wr.GetResponse())
                {
                    System.IO.StreamReader respReader = new System.IO.StreamReader(wresp.GetResponseStream());
                    //MessageBox.Show(respReader.ReadToEnd());
                }
            }
            catch (System.Net.WebException ex)
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(ex.Response.GetResponseStream());
                MessageBox.Show(ex.Message + " " + reader.ReadToEnd());
            }
        }
示例#56
0
        /// 访问URL地址

        public string CallWebPage(string url, int httpTimeout, Encoding postEncoding)

        {
            string rStr = "";

            System.Net.WebRequest req = null;

            System.Net.WebResponse resp = null;

            System.IO.Stream os = null;

            System.IO.StreamReader sr = null;

            try

            {
                //创建连接

                req = System.Net.WebRequest.Create(url);

                req.ContentType = "application/x-www-form-urlencoded";

                req.Method = "GET";

                //时间

                if (httpTimeout > 0)

                {
                    req.Timeout = httpTimeout;
                }

                //读取返回结果

                resp = req.GetResponse();

                sr = new System.IO.StreamReader(resp.GetResponseStream(), postEncoding);

                rStr = sr.ReadToEnd();
            }

            catch (Exception ex)

            {
                throw (ex);
            }

            finally

            {
                try

                {
                    //关闭资源

                    if (os != null)

                    {
                        os.Dispose();

                        os.Close();
                    }

                    if (sr != null)

                    {
                        sr.Dispose();

                        sr.Close();
                    }

                    if (resp != null)

                    {
                        resp.Close();
                    }

                    if (req != null)

                    {
                        req.Abort();

                        req = null;
                    }
                }

                catch (Exception ex2)
                {
                    throw (ex2);
                }
            }

            return(rStr);
        }
示例#57
0
        async Task <string> ReadRSS(string url, DateTime LastGet, int SubNesourceID, string TagContent, string ImageTag)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.DtdProcessing = DtdProcessing.Ignore;
            try
            {
                using (XmlReader reader = XmlReader.Create(url, settings))
                {
                    SyndicationFeed feed = SyndicationFeed.Load(reader);
                    string          link;
                    string          summary        = "";
                    string          SummaryContent = "";
                    foreach (SyndicationItem item in feed.Items.Reverse())
                    {
                        try
                        {
                            string dateStr = item.PublishDate.ToString("ddd MMM dd HH:mm:ss zzzz yyyy");
                            // // DateTime PostDate = DateTime.ParseExact(dateStr, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                            DateTime PostDate = DateTime.ParseExact(dateStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);
                            // DateTime PostDate = Convert.ToDateTime(item.PublishDate.ToString());
                            if ((PostDate > LastGet))
                            {
                                link = item.Links[0].Uri.ToString();
                                string ImageURL = "";
                                try
                                { summary = item.Summary.Text;
                                  if (item.Links.Count > 1)
                                  {
                                      string value = item.Links[item.Links.Count - 1].Uri.ToString().ToLower();
                                      if (value.StartsWith("http://") && (value.EndsWith(".jpg") || value.EndsWith(".jpeg") || value.EndsWith(".png") || value.EndsWith(".gif")))
                                      {
                                          ImageURL = item.Links[item.Links.Count - 1].Uri.ToString();
                                      }
                                  }
                                  // read the attach images
                                  foreach (SyndicationElementExtension extension in item.ElementExtensions)
                                  {
                                      XElement element = extension.GetObject <XElement>();
                                      if (element.HasAttributes)
                                      {
                                          foreach (var attribute in element.Attributes())
                                          {
                                              string value = attribute.Value.ToLower();
                                              if (value.StartsWith("http://") && (value.EndsWith(".jpg") || value.EndsWith(".png") || value.EndsWith(".gif")))
                                              {
                                                  ImageURL = value; // Add here the image link to some array
                                                  break;            //get ne filesonly
                                              }
                                          }
                                      }
                                  }
                                }
                                catch (Exception ex) { summary = ""; }

                                try // get news details
                                {
                                    if (link.Length > 0)
                                    {
                                        //  SummaryContent = await ReadTextFromUrl(link, TagContent);
                                        // if (SummaryContent.Length > 0)
                                        //   summary = SummaryContent;
                                        try
                                        {
                                            string  PageContain = "";
                                            String  PageFull    = "";
                                            HtmlWeb web         = new HtmlWeb();
                                            HtmlAgilityPack.HtmlDocument doc = web.Load(link);
                                            //doc.LoadHtml(PageContainhtml);
                                            string host = web.ResponseUri.Host.ToString();
                                            if (host.IndexOf("http") < 0)
                                            {
                                                host = "http://" + host;
                                            }
                                            if (TagContent.Length > 0)
                                            { /// get one node data
                                                try
                                                {
                                                    HtmlNode rateNode = doc.DocumentNode.SelectSingleNode(TagContent);
                                                    PageContain = rateNode.InnerHtml;

                                                    //get all div content
                                                    //   var  query = doc.DocumentNode.SelectNodes(TagContent);
                                                    //   PageContain = query.ToString();
                                                    // get all nodes tags data
                                                    PageFull = "";
                                                    foreach (HtmlAgilityPack.HtmlNode node2 in doc.DocumentNode.SelectNodes(TagContent))
                                                    {
                                                        PageFull = PageFull + "<p>" + node2.InnerHtml + "</p>";
                                                    }
                                                    if (PageFull.Length > 0)
                                                    {
                                                        PageContain = PageFull;
                                                    }

                                                    if (PageContain.Length > 0)
                                                    {
                                                        summary = PageContain;
                                                    }
                                                }
                                                catch (Exception ex) { }
                                            }

                                            if (ImageTag.Length > 0)
                                            {
                                                HtmlNode rateNodeimage = doc.DocumentNode.SelectSingleNode(ImageTag);
                                                string   tempimageURL;
                                                foreach (Match m in Regex.Matches(rateNodeimage.InnerHtml, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                                                {
                                                    tempimageURL = m.Groups[1].Value;
                                                    if (tempimageURL.IndexOf("http") < 0)
                                                    {
                                                        tempimageURL = host + m.Groups[1].Value;
                                                    }
                                                    // لget only the picture with  big size
                                                    System.Net.WebRequest  request        = System.Net.WebRequest.Create(tempimageURL);
                                                    System.Net.WebResponse response       = request.GetResponse();
                                                    System.IO.Stream       responseStream = response.GetResponseStream();
                                                    Bitmap bitmap2     = new Bitmap(responseStream);
                                                    var    imageHeight = bitmap2.Height;
                                                    var    imageWidth  = bitmap2.Width;
                                                    // string value = attribute.Value.ToLower();
                                                    if ((bitmap2.Width > 100) && (bitmap2.Height > 100) && (!tempimageURL.EndsWith(".gif")))
                                                    {
                                                        if ((ImageURL.Length == 0))
                                                        {
                                                            ImageURL = tempimageURL;
                                                            break;
                                                        }
                                                    }
                                                }

                                                // get image in cause they cannot get in direct
                                                if (ImageURL.Length == 0)
                                                {
                                                    foreach (HtmlNode img in doc.DocumentNode.SelectNodes(ImageTag))
                                                    {
                                                        ImageURL = img.GetAttributeValue("src", null);
                                                        if (ImageURL.IndexOf("http") < 0)
                                                        {
                                                            ImageURL = host + ImageURL;
                                                        }
                                                        break;
                                                    }
                                                }
                                                if (ImageURL.Length == 0)
                                                {
                                                    // get the viedos url
                                                    List <string>   list     = new List <string>();
                                                    Regex           urlRx    = new Regex(@"(http://youtu|https://youtu|https://www.youtu|http://www.youtu)[A-Za-z0-9\.\-]+(/[A-Za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*", RegexOptions.IgnoreCase);
                                                    string          ViedoURL = "";
                                                    MatchCollection matches  = urlRx.Matches(rateNodeimage.InnerHtml);
                                                    foreach (Match match in matches)
                                                    {
                                                        ViedoURL = match.Value;
                                                        try
                                                        {
                                                            string[] sp = ViedoURL.Split('&');
                                                            if (sp.Length > 1)
                                                            {
                                                                ViedoURL = sp[0];
                                                            }
                                                            string[] spid = ViedoURL.Split('/');
                                                            if (spid.Length > 1)
                                                            {
                                                                ViedoURL = "http://www.youtube.com/embed/" + spid[spid.Length - 1];
                                                            }
                                                            break;
                                                        }
                                                        catch (Exception ex) { }
                                                        list.Add(ViedoURL);
                                                    }
                                                    if (list.Count > 0)
                                                    {
                                                        ImageURL = list[0];
                                                    }


                                                    if (list.Count == 0)
                                                    {// get mp4
                                                        Regex urlRx1 = new Regex(@"(http://|https://)[A-Za-z0-9\.\-]+(/[A-Za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*(.mp4|.MP4)", RegexOptions.IgnoreCase);
                                                        ViedoURL = "";

                                                        MatchCollection matches1 = urlRx1.Matches(rateNodeimage.InnerHtml);
                                                        if (matches1.Count > 0)
                                                        {
                                                            list.Clear();
                                                            foreach (Match match in matches1)
                                                            {
                                                                ViedoURL = match.Value;

                                                                list.Add(ViedoURL);
                                                                break;
                                                            }
                                                            if (list.Count > 0)
                                                            {
                                                                ImageURL = list[0];
                                                            }
                                                        }
                                                    }

                                                    /////in cuase use video tag
                                                    tempimageURL = "";
                                                    if (list.Count == 0)
                                                    {
                                                        foreach (Match m in Regex.Matches(rateNodeimage.InnerHtml, "<iframe.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                                                        {
                                                            tempimageURL = m.Groups[1].Value;
                                                            break;
                                                        }
                                                        if (tempimageURL.Length > 0)
                                                        {
                                                            ImageURL = tempimageURL;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception ex7) { }
                                    }
                                }
                                catch (Exception ex) { }

                                ColoumnParam[] Coloumns = new ColoumnParam[6];
                                Coloumns[0] = new ColoumnParam("NewsTitle", ColoumnType.NVarChar, item.Title.Text);
                                Coloumns[1] = new ColoumnParam("NewsDate", ColoumnType.DateTime, PostDate);
                                Coloumns[2] = new ColoumnParam("ReadFromWebsiteLink", ColoumnType.NVarChar, link);
                                Coloumns[3] = new ColoumnParam("SubNesourceID", ColoumnType.Int, SubNesourceID);
                                Coloumns[4] = new ColoumnParam("NewsDetails", ColoumnType.NVarChar, summary);
                                Coloumns[5] = new ColoumnParam("DateIN", ColoumnType.DateTime, DateTime.Now.ToString());
                                if (DBop.cobject.InsertRow("News", Coloumns))
                                {
                                    DataTable dataTable = new DataTable();
                                    dataTable = DBop.cobject.SelectDataSet("News", "NewsID", "SubNesourceID=" + SubNesourceID + "  and NewsDate ='" + PostDate + "'").Tables[0];
                                    if ((dataTable != null) && (dataTable.Rows.Count > 0))
                                    {
                                        if (ImageURL.Length > 0)// get image from content
                                        {
                                            ColoumnParam[] Coloumns1 = new ColoumnParam[2];
                                            Coloumns1[0] = new ColoumnParam("NewsID", ColoumnType.Int, Convert.ToString(dataTable.Rows[0]["NewsID"]));
                                            Coloumns1[1] = new ColoumnParam("NewsLink", ColoumnType.NVarChar, ImageURL);

                                            DBop.cobject.InsertRow("NewsImages", Coloumns1);
                                        }
                                    }
                                }
                                //Console.Clear();
                                // Console.WriteLine("Last New Readed was at :" + PostDate.ToString());
                            }
                        }
                        catch (Exception xexp)
                        {
                            // fix those datetime nodes with exceptions and read again.
                            try
                            {
                                /// old version of RSS
                                XmlDocument rssXmlDoc = new XmlDocument();

                                // Load the RSS file from the RSS URL
                                rssXmlDoc.Load(url);

                                // Parse the Items in the RSS file
                                XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");

                                StringBuilder rssContent = new StringBuilder();

                                string title;
                                string description;

                                string pubdate;
                                string ImageURL = "";
                                // Iterate through the items in the RSS file
                                foreach (XmlNode rssNode in rssNodes)
                                {
                                    XmlNode rssSubNode = rssNode.SelectSingleNode("title");
                                    title = rssSubNode != null ? rssSubNode.InnerText : "";

                                    rssSubNode = rssNode.SelectSingleNode("link");
                                    link       = rssSubNode != null ? rssSubNode.InnerText : "";

                                    rssSubNode  = rssNode.SelectSingleNode("description");
                                    description = rssSubNode != null ? rssSubNode.InnerText : "";
                                    rssSubNode  = rssNode.SelectSingleNode("pubDate");
                                    pubdate     = rssSubNode != null?rssSubNode.InnerText.ToString() : "";

                                    try
                                    {
                                        // string dateStr = rssSubNode.InnerText.ToString("ddd MMM dd HH:mm:ss zzzz yyyy");
                                        //DateTime PostDate = Convert.ToDateTime(pubdate);// DateTime.ParseExact(pubdate, "ddd MMM dd HH:mm:ss zzzz yyyy", null);
                                        // DateTime date = DateTime.ParseExact(pubdate, "dd/MM/yyyy", null);
                                        // string dateTime = parsedDateTime.ToString("ddd MMM dd HH:mm:ss zzzz yyyy");
                                        // DateTime dateStr = DateTime.ParseExact(pubdate, "ddd MMM dd HH:mm:ss zzzz yyyy", null );
                                        // DateTime PostDate = DateTime.ParseExact(pubdate, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);
                                        // string dateStr = item.PublishDate.ToString("ddd MMM dd HH:mm:ss zzzz yyyy");
                                        // DateTime PostDate = DateTime.ParseExact(dateStr, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                                        DateTime PostDate = DateTime.ParseExact(pubdate, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);

                                        if ((PostDate > LastGet))
                                        {
                                            ImageURL = "";
                                            summary  = description;
                                            if (link.Length > 0)
                                            {
                                                //  SummaryContent = await ReadTextFromUrl(link, TagContent);
                                                // if (SummaryContent.Length > 0)
                                                //   summary = SummaryContent;
                                                try
                                                {
                                                    string  PageContain = "";
                                                    String  PageFull    = "";
                                                    HtmlWeb web         = new HtmlWeb();
                                                    HtmlAgilityPack.HtmlDocument doc = web.Load(link);
                                                    //doc.LoadHtml(PageContainhtml);
                                                    string host = web.ResponseUri.Host.ToString();
                                                    if (host.IndexOf("http") < 0)
                                                    {
                                                        host = "http://" + host;
                                                    }
                                                    if (TagContent.Length > 0)
                                                    { /// get one node data
                                                        try
                                                        {
                                                            HtmlNode rateNode = doc.DocumentNode.SelectSingleNode(TagContent);
                                                            PageContain = rateNode.InnerHtml;

                                                            //get all div content
                                                            //   var  query = doc.DocumentNode.SelectNodes(TagContent);
                                                            //   PageContain = query.ToString();
                                                            // get all nodes tags data
                                                            PageFull = "";
                                                            foreach (HtmlAgilityPack.HtmlNode node2 in doc.DocumentNode.SelectNodes(TagContent))
                                                            {
                                                                PageFull = PageFull + "<p>" + node2.InnerHtml + "</p>";
                                                            }
                                                            ;
                                                            if (PageFull.Length > 0)
                                                            {
                                                                PageContain = PageFull;
                                                            }

                                                            if (PageContain.Length > 0)
                                                            {
                                                                summary = PageContain;
                                                            }
                                                        }
                                                        catch (Exception e34x) { }
                                                    }

                                                    if (ImageTag.Length > 0)
                                                    {
                                                        HtmlNode rateNodeimage = doc.DocumentNode.SelectSingleNode(ImageTag);
                                                        string   tempimageURL;
                                                        foreach (Match m in Regex.Matches(rateNodeimage.InnerHtml, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                                                        {
                                                            tempimageURL = m.Groups[1].Value;
                                                            if (tempimageURL.IndexOf("http") < 0)
                                                            {
                                                                tempimageURL = host + m.Groups[1].Value;
                                                            }
                                                            // لget only the picture with  big size
                                                            System.Net.WebRequest  request        = System.Net.WebRequest.Create(tempimageURL);
                                                            System.Net.WebResponse response       = request.GetResponse();
                                                            System.IO.Stream       responseStream = response.GetResponseStream();
                                                            Bitmap bitmap2     = new Bitmap(responseStream);
                                                            var    imageHeight = bitmap2.Height;
                                                            var    imageWidth  = bitmap2.Width;
                                                            // string value = attribute.Value.ToLower();
                                                            if ((bitmap2.Width > 100) && (bitmap2.Height > 100) && (!tempimageURL.EndsWith(".gif")))
                                                            {
                                                                if ((ImageURL.Length == 0))
                                                                {
                                                                    ImageURL = tempimageURL;
                                                                    break;
                                                                }
                                                            }
                                                        }

                                                        // get image in cause they cannot get in direct
                                                        if (ImageURL.Length == 0)
                                                        {
                                                            foreach (HtmlNode img in doc.DocumentNode.SelectNodes(ImageTag))
                                                            {
                                                                ImageURL = img.GetAttributeValue("src", null);
                                                                if (ImageURL.IndexOf("http") < 0)
                                                                {
                                                                    ImageURL = host + ImageURL;
                                                                }
                                                                break;
                                                            }
                                                        }
                                                        //et viedos
                                                    }

                                                    ColoumnParam[] Coloumns = new ColoumnParam[6];
                                                    Coloumns[0] = new ColoumnParam("NewsTitle", ColoumnType.NVarChar, title);
                                                    Coloumns[1] = new ColoumnParam("NewsDate", ColoumnType.DateTime, PostDate);
                                                    Coloumns[2] = new ColoumnParam("ReadFromWebsiteLink", ColoumnType.NVarChar, link);
                                                    Coloumns[3] = new ColoumnParam("SubNesourceID", ColoumnType.Int, SubNesourceID);
                                                    Coloumns[4] = new ColoumnParam("NewsDetails", ColoumnType.NVarChar, summary);
                                                    Coloumns[5] = new ColoumnParam("DateIN", ColoumnType.DateTime, DateTime.Now.ToString());
                                                    if (DBop.cobject.InsertRow("News", Coloumns))
                                                    {
                                                        DataTable dataTable = new DataTable();
                                                        dataTable = DBop.cobject.SelectDataSet("News", "NewsID", "SubNesourceID=" + SubNesourceID + "  and NewsDate ='" + PostDate + "'").Tables[0];
                                                        if ((dataTable != null) && (dataTable.Rows.Count > 0))
                                                        {
                                                            if (ImageURL.Length > 0)// get image from content
                                                            {
                                                                ColoumnParam[] Coloumns1 = new ColoumnParam[2];
                                                                Coloumns1[0] = new ColoumnParam("NewsID", ColoumnType.Int, Convert.ToString(dataTable.Rows[0]["NewsID"]));
                                                                Coloumns1[1] = new ColoumnParam("NewsLink", ColoumnType.NVarChar, ImageURL);

                                                                DBop.cobject.InsertRow("NewsImages", Coloumns1);
                                                            }
                                                        }
                                                    }
                                                    //Console.Clear();
                                                    // Console.WriteLine("Last New Readed was at :" + PostDate.ToString());
                                                }
                                                catch (Exception xexssp)
                                                {
                                                    // fix those datetime nodes with exceptions and read again.
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception exerror) { }
                                }
                            }

                            catch (Exception exerror) { }
                        }
                    }
                }
            }
            catch (Exception ex) { }
            return(null);
        }
示例#58
0
        public async Task <string> GetTwitts(string userName, int count, DateTime LastGet, int SubNesourceID, string TagContent, string ImageTag)
        {
            //if (accessToken == null)
            //{
            //    accessToken = await GetAccessToken();
            //}
            try
            {
                var requestUserTimeline = new HttpRequestMessage(HttpMethod.Get, string.Format("https://api.twitter.com/1.1/statuses/user_timeline.json?count={0}&screen_name={1}", count, userName));//"https://api.twitter.com/1.1/search/tweets.json?q=%&count=10&geocode=37.781157,-122.398720,1mi"); //
                requestUserTimeline.Headers.Add("Authorization", "Bearer " + accessToken);
                var httpClient = new HttpClient();
                HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);

                var     serializer       = new JavaScriptSerializer();
                dynamic json             = serializer.Deserialize <object>(await responseUserTimeLine.Content.ReadAsStringAsync());
                var     enumerableTwitts = (json as IEnumerable <dynamic>);

                if (enumerableTwitts == null)
                {
                    return(null);
                }
                // List<PostInfo> ls = new List<PostInfo>();
                List <string> listoflinks    = new List <string>();
                string        twitterlink    = "";
                string        Articlelink    = "";
                string        ArticleData    = "";
                string        SummaryContent = "";
                string        summary        = "";


                foreach (dynamic t in enumerableTwitts.Reverse())
                {
                    try
                    {
                        string Post_url       = "";
                        string host           = "";
                        string mytempImageURL = "";
                        try
                        {
                            dynamic media = t["entities"]["urls"];

                            Post_url = media[0]["url"].ToString();
                        }
                        catch (Exception ex) { }
                        ///


                        string dateStr = t["created_at"].ToString();
                        // DateTime PostDate = DateTime.ParseExact(dateStr, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime PostDate = DateTime.ParseExact(dateStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);
                        //  DateTime PostDate = Convert.ToDateTime(dateStr);
                        if ((PostDate > LastGet) && (PostDate <= DateTime.Now))
                        {
                            try // get news details
                            {
                                if (Post_url.Length > 0 && TagContent.Length > 0)
                                {
                                    // SummaryContent = await ReadTextFromUrl(Post_url, TagContent,2);
                                    //if (SummaryContent.Length > 0)
                                    //    summary = SummaryContent;
                                    String LoadURL = Post_url;
                                    if (Post_url.IndexOf("http") < 0)
                                    {
                                        LoadURL = "http://" + Post_url;
                                    }
                                    string PageContain = "";

                                    string PageFull;
                                    try
                                    {
                                        HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(LoadURL);
                                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                                        if (response.StatusCode == HttpStatusCode.OK)
                                        {
                                            LoadURL = response.ResponseUri.ToString();
                                            host    = response.ResponseUri.Host.ToString();

                                            // get page content====================
                                            HtmlWeb web = new HtmlWeb();
                                            HtmlAgilityPack.HtmlDocument doc = web.Load(LoadURL);
                                            //doc.LoadHtml(PageContainhtml);
                                            HtmlNode rateNode = doc.DocumentNode.SelectSingleNode(TagContent);
                                            PageContain = rateNode.InnerHtml;
                                            PageFull    = "";
                                            foreach (HtmlAgilityPack.HtmlNode node2 in doc.DocumentNode.SelectNodes(TagContent))
                                            {
                                                PageFull = PageFull + "<p>" + node2.InnerHtml + "</p>";
                                            }
                                            if (PageFull.Length > 0)
                                            {
                                                PageContain = PageFull;
                                            }
                                            if (PageContain.Length > 0)
                                            {
                                                summary = PageContain;
                                            }

                                            // get image==============================
                                            // get image
                                            if (ImageTag.Length > 0)
                                            {
                                                if (host.IndexOf("http") < 0)
                                                {
                                                    host = "http://" + host;
                                                }
                                                HtmlNode rateNodeimage = doc.DocumentNode.SelectSingleNode(ImageTag);
                                                string   tempimageURL;
                                                foreach (Match m in Regex.Matches(rateNodeimage.InnerHtml, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                                                {
                                                    tempimageURL = m.Groups[1].Value;
                                                    if (tempimageURL.IndexOf("http") < 0)
                                                    {
                                                        tempimageURL = host + m.Groups[1].Value;
                                                    }
                                                    // لget only the picture with  big size
                                                    try
                                                    {
                                                        System.Net.WebRequest  request1       = System.Net.WebRequest.Create(tempimageURL);
                                                        System.Net.WebResponse response1      = request1.GetResponse();
                                                        System.IO.Stream       responseStream = response1.GetResponseStream();
                                                        Bitmap bitmap2     = new Bitmap(responseStream);
                                                        var    imageHeight = bitmap2.Height;
                                                        var    imageWidth  = bitmap2.Width;
                                                        // string value = attribute.Value.ToLower();
                                                        if ((bitmap2.Width > 100) && (bitmap2.Height > 100) && (!tempimageURL.EndsWith(".gif")))
                                                        {
                                                            if ((mytempImageURL.Length == 0))
                                                            {
                                                                mytempImageURL = tempimageURL;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex) { }
                                                }
                                                //et viedos
                                                // get image in cause they cannot get in direct
                                                if (mytempImageURL.Length == 0)
                                                {
                                                    foreach (HtmlNode img in doc.DocumentNode.SelectNodes(ImageTag))
                                                    {
                                                        mytempImageURL = img.GetAttributeValue("src", null);
                                                        if (mytempImageURL.IndexOf("http") < 0)
                                                        {
                                                            mytempImageURL = host + mytempImageURL;
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    { }
                                }
                            }
                            catch (Exception ex) { }

                            // extract the links for text
                            ArticleData = t["text"].ToString();
                            try
                            {
                                Regex urlRx = new Regex(@"((https?|ftp|file)\://|www.)[A-Za-z0-9\.\-]+(/[A-Za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*", RegexOptions.IgnoreCase);

                                MatchCollection matches = urlRx.Matches(ArticleData);
                                foreach (Match match in matches)
                                {
                                    listoflinks.Add(match.Value);
                                    twitterlink = match.Value; // link in twitter will update
                                    if (listoflinks.Count > 1)
                                    {
                                        Articlelink = listoflinks.ElementAt(0);// het article link
                                    }
                                    ArticleData = ArticleData.Remove(ArticleData.IndexOf(twitterlink), twitterlink.Length);
                                }
                            }
                            catch (Exception ex) { }
                            ColoumnParam[] Coloumns = new ColoumnParam[6];
                            Coloumns[0] = new ColoumnParam("NewsTitle", ColoumnType.NVarChar, ArticleData);
                            Coloumns[1] = new ColoumnParam("NewsDate", ColoumnType.DateTime, PostDate);
                            Coloumns[2] = new ColoumnParam("ReadFromWebsiteLink", ColoumnType.NVarChar, Post_url);
                            Coloumns[3] = new ColoumnParam("SubNesourceID", ColoumnType.Int, SubNesourceID);
                            Coloumns[4] = new ColoumnParam("NewsDetails", ColoumnType.NVarChar, summary);
                            Coloumns[5] = new ColoumnParam("DateIN", ColoumnType.DateTime, DateTime.Now.ToString());
                            if (DBop.cobject.InsertRow("News", Coloumns))
                            {
                                DataTable dataTable = new DataTable();
                                dataTable = DBop.cobject.SelectDataSet("News", "NewsID", "SubNesourceID=" + SubNesourceID + "  and NewsDate ='" + PostDate + "'").Tables[0];
                                if ((dataTable != null) && (dataTable.Rows.Count > 0))
                                {
                                    string media_url = "";
                                    try
                                    {
                                        dynamic media = t["entities"]["media"];

                                        media_url = media[0]["media_url_https"].ToString();
                                    }
                                    catch (Exception ex) {
                                        media_url = "";
                                        if (mytempImageURL.Length > 0)// we looked for image
                                        {
                                            media_url = mytempImageURL;
                                        }
                                    }
                                    if (media_url.Length > 0)
                                    {
                                        ColoumnParam[] Coloumns1 = new ColoumnParam[2];
                                        Coloumns1[0] = new ColoumnParam("NewsID", ColoumnType.Int, Convert.ToString(dataTable.Rows[0]["NewsID"]));
                                        Coloumns1[1] = new ColoumnParam("NewsLink", ColoumnType.NVarChar, media_url);
                                        DBop.cobject.InsertRow("NewsImages", Coloumns1);
                                    }
                                    //
                                }
                            }
                            // Console.Clear();
                            twitterlink = "";
                            Articlelink = "";
                            ArticleData = "";
                            listoflinks.Clear();
                            // Console.WriteLine("Last New Readed was at :" + PostDate.ToString());
                        }
                    }
                    catch (Exception ex) { }
                    //ls.Add(new PostInfo(t["text"].ToString(), PostDate));
                }
            }catch (Exception ex8) {}
            return(null);
        }
示例#59
0
    private void getWeatherInfo(GameObject button)
    {
        //inputCityName.value = "桂林";

        cityname = inputCityName.value.Trim();
        string type = "utf-8";

        string Url = "https://free-api.heweather.com/v5/now?city=" + cityname + "&key=29dc35d4b161490cb03639d34935b786";

        System.Net.WebRequest  wReq       = System.Net.WebRequest.Create(Url);
        System.Net.WebResponse wResp      = wReq.GetResponse();
        System.IO.Stream       respStream = wResp.GetResponseStream();
        string data = "";

        using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding(type)))
        {
            data = reader.ReadToEnd();
        }

        data = Regex.Unescape(data);
        //Debug.Log(data);
        try
        {
            rt = Newtonsoft.Json.JavaScriptConvert.DeserializeObject <Root>(data);
            foreach (HeWeather5Item hw in rt.HeWeather5)
            {
                s1 = hw.now.tmp;
                s2 = hw.now.cond.txt.Trim();
                Debug.Log(hw.now.tmp);
                Debug.Log(hw.now.cond.txt);
                if (lastwea != 1 && (s2 == "晴" || s2 == "平静" || s2 == "热" || s2 == "未知"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                 //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                 //移走 雪
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube01_Sunny.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube01_Sunny;                                    //改变当前图片记录
                    lastwea = 1;
                }
                else if (lastwea != 2 && (s2 == "多云" || s2 == "少云" || s2 == "晴间多云"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                  //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                  //移走 雪
                    weather_cube02_Cloudy.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current.transform.position  = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube_current = weather_cube02_Cloudy;                                    //改变当前图片记录
                    lastwea = 2;
                }
                else if (lastwea != 3 && (s2 == "有风" || s2 == "微风" || s2 == "和风" || s2 == "清风"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                 //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                 //移走 雪
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube03_Windy.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube03_Windy;                                    //改变当前图片记录
                    lastwea = 3;
                }
                else if (lastwea != 4 && (s2 == "强风" || s2 == "劲风" || s2 == "疾风" || s2 == "大风" || s2 == "烈风" || s2 == "阴" || s2 == "冷"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                 //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                 //移走 雪
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube04_HWind.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube04_HWind;                                    //改变当前图片记录
                    lastwea = 4;
                }
                else if (lastwea != 5 && (s2 == "风暴" || s2 == "狂爆风" || s2 == "飓风" || s2 == "龙卷风" || s2 == "热带风暴"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                  //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                  //移走 雪
                    weather_cube_current.transform.position  = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube05_HHWind.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube05_HHWind;                                    //改变当前图片记录
                    lastwea = 5;
                }
                else if (lastwea != 6 && (s2 == "小雨" || s2 == "中雨" || s2 == "毛毛雨" || s2 == "细雨" || s2 == "雨夹雪" || s2 == "阵雨夹雪"))
                {
                    rain.transform.position = new Vector3(591.99f, 15.8f, -1153.45f);               //雨 移到窗前
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                 //移走 雪
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube06_LRain.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube06_LRain;                                    //改变当前图片记录
                    lastwea = 6;
                }
                else if (lastwea != 7 && (s2 == "强阵雨" || s2 == "强雷阵雨" || s2 == "雷阵雨" || s2 == "大雨" || s2 == "极端降雨" || s2 == "暴雨" || s2 == "大暴雨" || s2 == "特大暴雨" || s2 == "雷阵雨伴有冰雹" || s2 == "阵雨"))
                {
                    rain.transform.position = new Vector3(591.99f, 15.8f, -1153.45f);               //雨 移到窗前
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                 //移走 雪
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube07_HRain.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube07_HRain;                                    //改变当前图片记录
                    lastwea = 7;
                }
                else if (lastwea != 8 && (s2 == "小雪" || s2 == "中雪" || s2 == "大雪" || s2 == "暴雪" || s2 == "雨雪天气" || s2 == "阵雪" || s2 == "暴雨" || s2 == "雨雪天气" || s2 == "雨雪天气" || s2 == "雨雪天气" || s2 == "阵雪"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                 //移走 雨
                    snow.transform.position = new Vector3(591.9f, 17.4f, -1149.3f);                 //雪 移到窗前
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube08_Snowy.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube08_Snowy;                                    //改变当前图片记录
                    lastwea = 8;
                }
                else if (lastwea != 9 && s2 == "冻雨")
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                   //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                   //移走 雪
                    weather_cube_current.transform.position   = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube09_IceRain.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube09_IceRain;                                    //改变当前图片记录
                    lastwea = 9;
                }
                else if (lastwea != 10 && (s2 == "薄雾" || s2 == "雾" || s2 == "霾"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                 //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                 //移走 雪
                    weather_cube_current.transform.position = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube10_Fog.transform.position   = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube10_Fog;                                      //改变当前图片记录
                    lastwea = 10;
                }
                else if (lastwea != 11 && (s2 == "扬沙" || s2 == "浮尘" || s2 == "沙尘暴" || s2 == "强沙尘暴"))
                {
                    rain.transform.position = new Vector3(596.1f, 15.8f, -1177.7f);                     //移走 雨
                    snow.transform.position = new Vector3(593.6f, 17.4f, -1159.7f);                     //移走 雪
                    weather_cube_current.transform.position     = new Vector3(592.5f, -1.5f, -1158.5f); //将当前图片移走
                    weather_cube11_DustStorm.transform.position = new Vector3(589.9f, -1.5f, -1141.9f); //将天气对应的图片移到窗前
                    weather_cube_current = weather_cube11_DustStorm;                                    //改变当前图片记录
                    lastwea = 11;
                }
            }
        }
        catch (JsonSerializationException ex)
        {
            Debug.Log("wrong!");
        }
        ui.SetActive(false);
    }
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                string inputText = TextInput.Get(executionContext);
                if (inputText != string.Empty)
                {
                    //strip any html characters from the text to analyze
                    inputText = HtmlTools.StripHTML(inputText);
                    tracingService.Trace(string.Format("stripped text: {0}", inputText));

                    //escape any double quote characters (") so they don't cause problems when posting the json later
                    string escapedText = inputText.Replace("\"", "\\\"");
                    tracingService.Trace(string.Format("escaped text: {0}", escapedText));

                    //create the webrequest object
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_webAddress);

                    //set request content type so it is treated as a regular form post
                    req.ContentType = "application/x-www-form-urlencoded";

                    //set method to post
                    req.Method = "POST";

                    //buld the request
                    StringBuilder postData = new StringBuilder();

                    //note the Id value set to 1 - we can hardcode this because we're only sending a batch of one
                    postData.Append("{\"Inputs\":[{\"Id\":\"1\",\"Text\":\"" + escapedText + "\"}]}");

                    //set the authentication using the azure service access key
                    string authInfo = "AccountKey:" + ApiKey.Get(executionContext);
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                    req.Headers["Authorization"] = "Basic " + authInfo;

                    //create a stream
                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
                    req.ContentLength = bytes.Length;
                    System.IO.Stream os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();

                    //post the request and get the response
                    System.Net.WebResponse resp = req.GetResponse();

                    //deserialize the response to a SentimentBatchResult object
                    SentimentBatchResult sentimentResult = new SentimentBatchResult();
                    System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(sentimentResult.GetType());
                    sentimentResult = deserializer.ReadObject(resp.GetResponseStream()) as SentimentBatchResult;

                    //if no errors, return the sentiment
                    if (sentimentResult.Errors.Count == 0)
                    {
                        //set output values from the fields of the deserialzed myjsonresponse object
                        Score.Set(executionContext, sentimentResult.SentimentBatch[0].Score);
                    }
                    else
                    {
                        //otherwise raise an exception with the returned error message
                        throw new InvalidPluginExecutionException(String.Format("Sentiment analyis error: {0)", sentimentResult.Errors[0].Message));
                    }
                }
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }