Esempio n. 1
0
        private async Task <TransmissionResponse> SendRequestAsync(TransmissionRequest request, CancellationToken token)
        {
            var result = new TransmissionResponse();

            request.Tag = ++CurrentTag;
            var counter   = 0;
            var byteArray = Encoding.UTF8.GetBytes(request.ToJson());

            //Prepare http web request
            if (!CheckURLValid(Url))
            {
                throw new WebException("Host error", WebExceptionStatus.NameResolutionFailure);
            }


            while (counter < NumberOfAttempts)
            {
                try
                {
                    var webRequest = (HttpWebRequest)WebRequest.Create(Url);
                    webRequest.ContentType = "application/json-rpc";
                    webRequest.Method      = "POST";
                    if (_needAuthorization)
                    {
                        webRequest.Headers["Authorization"] = _authorization;
                    }

                    webRequest.Headers["X-Transmission-Session-Id"] = SessionId;

                    await using (var dataStream = await webRequest.GetRequestStreamAsync())
                    {
                        await dataStream.WriteAsync(byteArray, 0, byteArray.Length, token);
                    }

                    //Send request and prepare response
                    using var webResponse = await webRequest.GetResponseAsync(token);

                    await using var responseStream = await webResponse.GetResponseStream(token);

                    if (responseStream == null)
                    {
                        result.CustomException = new Exception("Stream resonse is null");
                        Log.Error(result.WebException);
                        return(result);
                    }

                    var reader         = new StreamReader(responseStream, Encoding.UTF8);
                    var responseString = await reader.ReadToEndAsync(token);

                    result = JsonConvert.DeserializeObject <TransmissionResponse>(responseString);

                    if (result.Result != "success")
                    {
                        throw new Exception(result.Result);
                    }
                    break;
                }
                catch (TaskCanceledException)
                {
                    result.Result = "canceled";
                    return(result);
                }
            }
Esempio n. 2
0
        private async Task <Boolean> ReadObjectDataAsync(String bucketName, String keyName, Boolean liveInstance)
        {
            Console.WriteLine(" ");
            try
            {
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = bucketName,
                    Key        = keyName
                };
                using (GetObjectResponse response = await client.GetObjectAsync(request))
                {
                    MimeMessage           message           = MimeMessage.Load(response.ResponseStream);
                    MailAddressCollection mailFromAddresses = (MailAddressCollection)message.From;
                    MailAddressCollection mailToAddresses   = (MailAddressCollection)message.To;

                    try
                    {
                        emailTo   = mailToAddresses[0].Address.ToString().ToLower();
                        emailFrom = mailFromAddresses[0].Address.ToString().ToLower();
                        Console.WriteLine(emailFrom + " - Processing email sent to this address : " + emailTo);
                        if (emailTo.Contains("update"))
                        {
                            Console.WriteLine(emailFrom + " - Update Case");
                            create = false;
                        }
                        else
                        {
                            Console.WriteLine(emailFrom + " - Create Case");
                        }
                        if (emailTo.ToLower().Equals(await GetStringFieldFromDynamoAsync(emailTo.ToLower(), "email", "UnitaryEmailAddresses")))
                        {
                            unitary = true;
                        }
                        if (emailTo.ToLower().Contains("northnorthants"))
                        {
                            west = false;
                        }
                        if (emailFrom.ToLower().Contains("*****@*****.**") && message.Subject.ToLower().Contains("northamptonshire council form has been submitted"))
                        {
                            contactUs = true;
                        }
                    }
                    catch (Exception)
                    {
                    }
                    subject = message.Subject;

                    if (String.IsNullOrWhiteSpace(subject))
                    {
                        subject = " ";
                    }
                    List <String> names = message.From[0].Name.Split(' ').ToList();
                    firstName = names.First();
                    names.RemoveAt(0);
                    lastName  = String.Join(" ", names.ToArray());
                    emailBody = message.HtmlBody;
                    Console.WriteLine(emailFrom + " - Email Contents : " + message.TextBody);
                    if (String.IsNullOrEmpty(message.TextBody))
                    {
                        if (String.IsNullOrEmpty(message.HtmlBody))
                        {
                            emailContents = getBodyFromBase64(message);
                        }
                        else
                        {
                            HtmlDocument emailHTML = new HtmlDocument();
                            emailHTML.LoadHtml(message.HtmlBody);
                            emailContents = emailHTML.DocumentNode.InnerText;
                        }
                    }
                    else
                    {
                        emailContents = message.TextBody;
                    }

                    String  person               = "";
                    Boolean bundlerFound         = false;
                    String  responseFileName     = "";
                    String  parsedEmailEncoded   = "";
                    String  parsedEmailUnencoded = "";

                    String emailFromName = "";

                    if (await GetSecrets())
                    {
                        if (liveInstance)
                        {
                            if (west)
                            {
                                cxmEndPoint           = secrets.cxmEndPointLive;
                                cxmAPIKey             = secrets.cxmAPIKeyLive;
                                cxmAPIName            = secrets.cxmAPINameWest;
                                cxmAPICaseType        = secrets.cxmAPICaseTypeWestLive;
                                tableName             = secrets.wncEMACasesLive;
                                ContactUsTableMapping = secrets.WNCContactUsMappingTable;
                                AutoResponseTable     = secrets.AutoResponseTableLive;
                            }
                            else
                            {
                                cxmEndPoint           = secrets.cxmEndPointLiveNorth;
                                cxmAPIKey             = secrets.cxmAPIKeyLiveNorth;
                                cxmAPIName            = secrets.cxmAPINameNorth;
                                cxmAPICaseType        = secrets.cxmAPICaseTypeNorthLive;
                                tableName             = secrets.nncEMNCasesLive;
                                ContactUsTableMapping = secrets.NNCContactUsMappingTable;
                                AutoResponseTable     = secrets.AutoResponseTableLive;
                            }
                        }
                        else
                        {
                            if (west)
                            {
                                cxmEndPoint           = secrets.cxmEndPointTest;
                                cxmAPIKey             = secrets.cxmAPIKeyTest;
                                cxmAPIName            = secrets.cxmAPINameWest;
                                cxmAPICaseType        = secrets.cxmAPICaseTypeWest;
                                tableName             = secrets.wncEMACasesTest;
                                ContactUsTableMapping = secrets.WNCContactUsMappingTable;
                                AutoResponseTable     = secrets.AutoResponseTableTest;
                            }
                            else
                            {
                                cxmEndPoint           = secrets.cxmEndPointTestNorth;
                                cxmAPIKey             = secrets.cxmAPIKeyTestNorth;
                                cxmAPIName            = secrets.cxmAPINameNorth;
                                cxmAPICaseType        = secrets.cxmAPICaseTypeNorth;
                                tableName             = secrets.nncEMNCasesTest;
                                ContactUsTableMapping = secrets.NNCContactUsMappingTable;
                                AutoResponseTable     = secrets.AutoResponseTableTest;
                            }
                        }

                        Random rand = new Random();
                        if (rand.Next(0, 2) == 0)
                        {
                            emailFromName = secrets.botPersona1;
                        }
                        else
                        {
                            emailFromName = secrets.botPersona2;
                        }
                    }
                    else
                    {
                        Console.WriteLine("ERROR : Unable to retrieve secrets");
                        return(false);
                    }

                    try
                    {
                        if (mailToAddresses[0].Address.ToLower().Contains("document"))
                        {
                            bundlerFound = true;
                        }
                        SigParser.Client sigParserClient    = new SigParser.Client(secrets.sigParseKey);
                        String           corporateSignature = await GetSignatureFromDynamoAsync(secrets.homeDomain, "");

                        int corporateSignatureLocation = emailContents.IndexOf(corporateSignature);
                        if (corporateSignatureLocation > 0)
                        {
                            Console.WriteLine("Home Domain Corporate Signature Found");
                            emailContents = emailContents.Remove(corporateSignatureLocation);
                        }
                        else
                        {
                            Console.WriteLine("Home Domain Corporate Signature Not Found");
                        }
                        for (int currentAddress = 0; currentAddress < mailFromAddresses.Count; currentAddress++)
                        {
                            int domainLocation = mailFromAddresses[currentAddress].Address.IndexOf("@");
                            domainLocation++;
                            if (mailFromAddresses[currentAddress].Address.ToLower().Equals("*****@*****.**"))
                            {
                                corporateSignature = await GetSignatureFromDynamoAsync(mailFromAddresses[currentAddress].Address.ToLower().Substring(domainLocation), "2");
                            }
                            else
                            {
                                corporateSignature = await GetSignatureFromDynamoAsync(mailFromAddresses[currentAddress].Address.ToLower().Substring(domainLocation), "");
                            }
                            if (mailFromAddresses[currentAddress].Address.ToLower().Equals("*****@*****.**"))
                            {
                                int nccSignatureLocation = emailContents.IndexOf("Any views expressed in this email are those of the individual sender");
                                if (nccSignatureLocation > 0)
                                {
                                    emailContents = emailContents.Substring(0, nccSignatureLocation);
                                    emailContents = emailContents.Trim();
                                }
                            }
                            corporateSignatureLocation = emailContents.IndexOf(corporateSignature);
                            if (corporateSignatureLocation > 0)
                            {
                                Console.WriteLine("Corporate Signature Found " + currentAddress);
                                emailContents = emailContents.Remove(corporateSignatureLocation);
                            }
                            else
                            {
                                Console.WriteLine("Corporate Signature Not Found " + currentAddress);
                            }
                        }

                        if (contactUs)
                        {
                            try
                            {
                                int serviceAreaStarts = emailContents.ToLower().IndexOf("service: ") + 9;
                                int serviceAreaEnds   = emailContents.ToLower().IndexOf("enquiry details:");
                                serviceArea = (emailContents.Substring(serviceAreaStarts, serviceAreaEnds - serviceAreaStarts).TrimEnd('\r', '\n')).ToLower();
                            }
                            catch { }
                            try
                            {
                                int emailAddressStarts = emailContents.ToLower().IndexOf("email address:") + 15;
                                int emailAddressEnds   = emailContents.ToLower().IndexOf("telephone number:");
                                emailFrom = emailContents.Substring(emailAddressStarts, emailAddressEnds - emailAddressStarts).TrimEnd('\r', '\n');
                            }
                            catch { }
                            try
                            {
                                int firstNameStarts = emailContents.ToLower().IndexOf("first name: ") + 12;
                                int firstNameEnds   = emailContents.ToLower().IndexOf("last name:");
                                firstName = emailContents.Substring(firstNameStarts, firstNameEnds - firstNameStarts).TrimEnd('\r', '\n');
                            }
                            catch { }
                            try
                            {
                                int lastNameStarts = emailContents.ToLower().IndexOf("last name: ") + 11;
                                int lastNameEnds   = emailContents.ToLower().IndexOf("email address:");
                                lastName = emailContents.Substring(lastNameStarts, lastNameEnds - lastNameStarts).TrimEnd('\r', '\n');
                            }
                            catch { }
                            try
                            {
                                int telNoStarts = emailContents.ToLower().IndexOf("telephone number: ") + 18;
                                int telNoEnds   = emailContents.ToLower().IndexOf("address line 1:");
                                telNo = emailContents.Substring(telNoStarts, telNoEnds - telNoStarts).TrimEnd('\r', '\n');
                            }
                            catch { }
                            try
                            {
                                int address1Starts = emailContents.ToLower().IndexOf("address line 1: ") + 16;
                                int address1Ends   = emailContents.ToLower().IndexOf("address line 2:");
                                address = emailContents.Substring(address1Starts, address1Ends - address1Starts).TrimEnd('\r', '\n') + ", ";
                            }
                            catch { }
                            try
                            {
                                int address2Starts = emailContents.ToLower().IndexOf("address line 2: ") + 16;
                                int address2Ends   = emailContents.ToLower().IndexOf("address line 3:");
                                if (address2Ends < 0)
                                {
                                    address2Ends = emailContents.ToLower().IndexOf("postcode:");
                                }
                                address += emailContents.Substring(address2Starts, address2Ends - address2Starts).TrimEnd('\r', '\n') + ", ";
                            }
                            catch { }
                            try
                            {
                                int address3Starts = emailContents.ToLower().IndexOf("address line 3: ") + 16;
                                int address3Ends   = emailContents.ToLower().IndexOf("postcode:");
                                if (address3Starts > 16)
                                {
                                    address += emailContents.Substring(address3Starts, address3Ends - address3Starts).TrimEnd('\r', '\n');
                                }
                            }
                            catch { }
                            try
                            {
                                int postcodeStarts = emailContents.ToLower().IndexOf("postcode: ") + 10;
                                int postcodeEnds   = emailContents.Length;
                                if (postcodeEnds - postcodeStarts < 10)
                                {
                                    address += ", " + emailContents.Substring(postcodeStarts, postcodeEnds - postcodeStarts).TrimEnd('\r', '\n');
                                }
                            }
                            catch { }
                            try
                            {
                                int startOfContact = emailContents.ToLower().IndexOf("enquiry details: ") + 17;
                                int endOfContact   = emailContents.ToLower().IndexOf("about you");
                                emailContents        = emailContents.Substring(startOfContact, endOfContact - startOfContact).TrimEnd('\r', '\n');
                                parsedEmailUnencoded = emailContents;
                                parsedEmailEncoded   = HttpUtility.UrlEncode(emailContents);
                            }
                            catch { }
                        }
                        else
                        {
                            SigParser.EmailParseRequest sigParserRequest = new SigParser.EmailParseRequest {
                                plainbody = emailContents, from_name = firstName + " " + lastName, from_address = emailFrom
                            };
                            parsedEmailUnencoded = sigParserClient.Parse(sigParserRequest).cleanedemailbody_plain;
                            if ((parsedEmailUnencoded == null || parsedEmailUnencoded.Contains("___")) && !bundlerFound)
                            {
                                Console.WriteLine($"No message found, checking for forwarded message");
                                parsedEmailUnencoded = sigParserClient.Parse(sigParserRequest).emails[1].cleanedBodyPlain;
                                emailFrom            = sigParserClient.Parse(sigParserRequest).emails[1].from_EmailAddress;
                                names     = sigParserClient.Parse(sigParserRequest).emails[1].from_Name.Split(' ').ToList();
                                firstName = names.First();
                                names.RemoveAt(0);
                                lastName = String.Join(" ", names.ToArray());
                            }
                            Console.WriteLine($"Cleaned email body is : {parsedEmailUnencoded}");
                            parsedEmailEncoded = HttpUtility.UrlEncode(parsedEmailUnencoded);
                            Console.WriteLine($"Encoded email body is : {parsedEmailEncoded}");
                        }
                    }
                    catch (Exception error)
                    {
                        parsedEmailUnencoded = emailContents;
                        parsedEmailEncoded   = HttpUtility.UrlEncode(emailContents);
                        Console.WriteLine("ERROR : An Unknown error encountered : {0}' when reading email", error.Message);
                        Console.WriteLine(error.StackTrace);
                    }

                    using (var client = new HttpClient())
                    {
                        try
                        {
                            HttpResponseMessage responseMessage = await client.GetAsync(
                                cxmEndPoint + "/api/service-api/norbert/user/" + emailFrom + "?key=" + cxmAPIKey);

                            responseMessage.EnsureSuccessStatusCode();
                            String responseBody = await responseMessage.Content.ReadAsStringAsync();

                            dynamic jsonResponse = JObject.Parse(responseBody);
                            person = jsonResponse.person.reference;
                            Console.WriteLine("Person found");
                        }
                        catch (Exception error)
                        {
                            Console.WriteLine("Person NOT found : " + error.Message);
                            person = "";
                        }
                    }
                    parsedEmailEncoded = JsonConvert.ToString(parsedEmailUnencoded);

                    if (String.IsNullOrEmpty(parsedEmailUnencoded))
                    {
                        if (bundlerFound)
                        {
                            emailBody            = "PDF Bundler";
                            parsedEmailUnencoded = "PDF Bundler";
                        }
                        else
                        {
                            emailBody            = "Empty message";
                            parsedEmailUnencoded = "Empty message";
                        }
                    }


                    if (emailFrom.Contains(secrets.loopPreventIdentifier) || (emailTo.ToLower().Contains("update") && (emailFrom.ToLower().Contains("westnorthants.gov.uk") || emailFrom.ToLower().Contains("northnorthants.gov.uk"))))
                    {
                        Console.WriteLine(emailFrom + " - Loop identifier found - no case created or updated : " + keyName);
                    }
                    else
                    {
                        if (subject.Contains("EMA") || parsedEmailUnencoded.Contains("EMA") || subject.Contains("EMN") || parsedEmailUnencoded.Contains("EMN"))
                        {
                            HttpClient client     = new HttpClient();
                            String     caseNumber = "";
                            if (west)
                            {
                                if (subject.Contains("EMA"))
                                {
                                    int refLocation = subject.IndexOf("EMA");
                                    caseNumber = subject.Substring(refLocation, 9);
                                }
                                else
                                {
                                    int refLocation = parsedEmailUnencoded.IndexOf("EMA");
                                    caseNumber = parsedEmailUnencoded.Substring(refLocation, 9);
                                }
                            }
                            else
                            {
                                if (subject.Contains("EMN"))
                                {
                                    int refLocation = subject.IndexOf("EMN");
                                    caseNumber = subject.Substring(refLocation, 9);
                                }
                                else
                                {
                                    int refLocation = parsedEmailUnencoded.IndexOf("EMN");
                                    caseNumber = parsedEmailUnencoded.Substring(refLocation, 9);
                                }
                            }

                            caseReference = caseNumber;

                            if (await IsAutoResponse(parsedEmailUnencoded))
                            {
                                Console.WriteLine(caseReference + " : " + emailFrom + " - Autoresponder Text Found : " + keyName);
                            }
                            else
                            {
                                String fieldName = "enquiry-details";

                                String data = "{\"" + fieldName + "\":" + parsedEmailEncoded + "," +
                                              "\"" + "customer-has-updated" + "\":" + "true" +
                                              "}";

                                Console.WriteLine($"PATCH payload : " + data);

                                String         url          = cxmEndPoint + "/api/service-api/" + cxmAPIName + "/case/" + caseNumber + "/edit?key=" + cxmAPIKey;
                                Encoding       encoding     = Encoding.Default;
                                HttpWebRequest patchRequest = (HttpWebRequest)WebRequest.Create(url);
                                patchRequest.Method      = "PATCH";
                                patchRequest.ContentType = "application/json; charset=utf-8";
                                byte[] buffer     = encoding.GetBytes(data);
                                Stream dataStream = patchRequest.GetRequestStream();
                                dataStream.Write(buffer, 0, buffer.Length);
                                dataStream.Close();
                                try
                                {
                                    HttpWebResponse patchResponse = (HttpWebResponse)patchRequest.GetResponse();
                                    String          result        = "";
                                    using (StreamReader reader = new StreamReader(patchResponse.GetResponseStream(), Encoding.Default))
                                    {
                                        result = reader.ReadToEnd();
                                    }
                                }
                                catch (Exception error)
                                {
                                    Console.WriteLine(caseNumber + " : " + error.ToString());
                                    Console.WriteLine(caseNumber + " : Error updating CXM field " + fieldName + " with message : " + message);
                                }

                                String unitary = await GetStringFieldFromDynamoAsync(caseReference, "Unitary", tableName);

                                if (unitary.Equals("true"))
                                {
                                    await TransitionCaseAsync("awaiting-location-confirmation");
                                }
                                else
                                {
                                    await TransitionCaseAsync("awaiting-review");
                                }
                            }
                        }
                        else
                        {
                            if (create)
                            {
                                String cxmSovereignServiceArea = "";
                                if (contactUs)
                                {
                                    cxmSovereignServiceArea = await GetStringFieldFromDynamoAsync(serviceArea, "LexService", ContactUsTableMapping);

                                    if (cxmSovereignServiceArea.ToLower().Contains("county"))
                                    {
                                        district = false;
                                    }
                                    try
                                    {
                                        cxmSovereignServiceArea = cxmSovereignServiceArea.Substring(cxmSovereignServiceArea.IndexOf("_") + 1);
                                    }
                                    catch (Exception) { }
                                }

                                Boolean success = true;

                                if (contactUs)
                                {
                                    Dictionary <String, Object> values = new Dictionary <String, Object>
                                    {
                                        { "first-name", firstName },
                                        { "surname", lastName },
                                        { "email", emailFrom },
                                        { "subject", subject },
                                        { "enquiry-details", await TrimEmailContents(parsedEmailUnencoded) },
                                        { "customer-has-updated", false },
                                        { "unitary", unitary },
                                        { "contact-us", contactUs },
                                        { "district", district },
                                        { "telephone-number", telNo },
                                        { "customer-address", address },
                                        { "email-id", keyName },
                                        { "sovereign-service-area", cxmSovereignServiceArea },
                                        { "original-email", await TrimEmailContents(parsedEmailUnencoded) }
                                    };
                                    success = await CreateCase(values, parsedEmailUnencoded, message, person, bundlerFound);

                                    if (!success)
                                    {
                                        Console.WriteLine("ERROR - Retrying case without cxmSovereignServiceArea of : " + cxmSovereignServiceArea);
                                    }
                                }
                                if (!contactUs || (contactUs && !success))
                                {
                                    Dictionary <String, Object> values = new Dictionary <String, Object>
                                    {
                                        { "first-name", firstName },
                                        { "surname", lastName },
                                        { "email", emailFrom },
                                        { "subject", subject },
                                        { "enquiry-details", await TrimEmailContents(parsedEmailUnencoded) },
                                        { "customer-has-updated", false },
                                        { "unitary", unitary },
                                        { "contact-us", contactUs },
                                        { "district", district },
                                        { "telephone-number", telNo },
                                        { "customer-address", address },
                                        { "email-id", keyName },
                                        { "original-email", await TrimEmailContents(message.TextBody) }
                                    };
                                    await CreateCase(values, parsedEmailUnencoded, message, person, bundlerFound);
                                }

                                responseFileName = "email-no-faq.txt";

                                await StoreContactToDynamoAsync(caseReference, parsedEmailUnencoded, unitary);

                                if (bundlerFound)
                                {
                                    await TransitionCaseAsync("awaiting-bundling");
                                }
                            }

                            String attachmentBucketName = "";
                            if (west)
                            {
                                if (liveInstance)
                                {
                                    attachmentBucketName = secrets.wncAttachmentBucketLive;
                                }
                                else
                                {
                                    attachmentBucketName = secrets.wncAttachmentBucketTest;
                                }
                            }
                            else
                            {
                                if (liveInstance)
                                {
                                    attachmentBucketName = secrets.nncAttachmentBucketLive;
                                }
                                else
                                {
                                    attachmentBucketName = secrets.nncAttachmentBucketTest;
                                }
                            }

                            Console.WriteLine($"responseFileName {responseFileName}");
                            ProcessAttachments attachmentProcessor = new ProcessAttachments();
                            attachmentProcessor.Process(caseReference, message, client, attachmentBucketName);
                            await StoreAttachmentCountToDynamoAsync(caseReference, attachmentProcessor.numOfAttachments);
                        }
                    }
                }
            }
            catch (AmazonS3Exception error)
            {
                Console.WriteLine("ERROR : Reading Email : '{0}' when reading email", error.Message);
                Console.WriteLine(error.StackTrace);
            }
            catch (Exception error)
            {
                Console.WriteLine("ERROR : An Unknown error encountered : {0}' when reading email", error.Message);
                Console.WriteLine(error.StackTrace);
            }
            return(true);
        }
Esempio n. 3
0
        /// <summary>
        /// 获得http请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="method">请求方式</param>
        /// <param name="postData">发送数据</param>
        /// <param name="encoding">编码</param>
        /// <param name="timeout">超时值</param>
        /// <returns></returns>
        public static string GetRequestData(string url, string method, string postData, Encoding encoding, int timeout)
        {
            if (!(url.Contains("http://") || url.Contains("https://")))
            {
                url = "http://" + url;
            }

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

            request.Method            = method.Trim().ToLower();
            request.Timeout           = timeout;
            request.AllowAutoRedirect = true;
            request.ContentType       = "text/html";
            request.Accept            = "text/html, application/xhtml+xml, */*,zh-CN";
            request.UserAgent         = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
            request.CachePolicy       = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

            try
            {
                if (!string.IsNullOrEmpty(postData) && request.Method == "post")
                {
                    byte[] buffer = encoding.GetBytes(postData);
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (encoding == null)
                    {
                        MemoryStream stream = new MemoryStream();
                        if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(stream, 10240);
                        }
                        else
                        {
                            response.GetResponseStream().CopyTo(stream, 10240);
                        }

                        byte[] RawResponse = stream.ToArray();
                        string temp        = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
                        Match  meta        = _metaregex.Match(temp);
                        string charter     = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
                        charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty);
                        if (charter.Length > 0)
                        {
                            charter  = charter.ToLower().Replace("iso-8859-1", "gbk");
                            encoding = Encoding.GetEncoding(charter);
                        }
                        else
                        {
                            if (response.CharacterSet.ToLower().Trim() == "iso-8859-1")
                            {
                                encoding = Encoding.GetEncoding("gbk");
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(response.CharacterSet.Trim()))
                                {
                                    encoding = Encoding.UTF8;
                                }
                                else
                                {
                                    encoding = Encoding.GetEncoding(response.CharacterSet);
                                }
                            }
                        }
                        return(encoding.GetString(RawResponse));
                    }
                    else
                    {
                        StreamReader reader = null;
                        if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
                            {
                                return(reader.ReadToEnd());
                            }
                        }
                        else
                        {
                            using (reader = new StreamReader(response.GetResponseStream(), encoding))
                            {
                                try
                                {
                                    return(reader.ReadToEnd());
                                }
                                catch (Exception ex)
                                {
                                    LogExt.WriteLogFile("GetRequestData方法,读取异常。地址:" + url + "。提示:" + ex.Message + "");
                                    return("close");
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                LogExt.WriteLogFile("GetRequestData方法,请求异常。地址:" + url + "。提示:" + ex.Message + "");
                return("error");
            }
        }
Esempio n. 4
0
        private void update(software temp)
        {
            string board = "";

            MainV2.comPort.BaseStream.DtrEnable = false;
            MainV2.comPort.Close();
            System.Threading.Thread.Sleep(100);
            MainV2.comPort.giveComport = true;

            try
            {
                if (softwares.Count == 0)
                {
                    CustomMessageBox.Show("No valid options");
                    return;
                }

                lbl_status.Text = "Detecting APM Version";

                this.Refresh();
                Application.DoEvents();

                /*
                 * ArdupilotMega.Controls.Firmware_Board fwb = new ArdupilotMega.Controls.Firmware_Board();
                 * fwb.ShowDialog();
                 *
                 * var boardname = ArdupilotMega.Controls.Firmware_Board.fw;
                 *
                 * switch (boardname)
                 * {
                 *  case ArdupilotMega.Controls.Firmware_Board.Firmware.apm1:
                 *      board = "2560";
                 *      break;
                 *  case ArdupilotMega.Controls.Firmware_Board.Firmware.apm2:
                 *      board = "2560-2";
                 *      break;
                 *  case ArdupilotMega.Controls.Firmware_Board.Firmware.apm2_5:
                 *      board = "2560-2";
                 *      break;
                 *  case ArdupilotMega.Controls.Firmware_Board.Firmware.px4:
                 *      board = "px4";
                 *      break;
                 * }
                 */
                board = ArduinoDetect.DetectBoard(MainV2.comPortName);

                if (board == "")
                {
                    CustomMessageBox.Show("Cant detect your APM version. Please check your cabling");
                    return;
                }

                int apmformat_version = -1; // fail continue

                if (board != "px4")
                {
                    try
                    {
                        apmformat_version = ArduinoDetect.decodeApVar(MainV2.comPortName, board);
                    }
                    catch { }

                    if (apmformat_version != -1 && apmformat_version != temp.k_format_version)
                    {
                        if (DialogResult.No == CustomMessageBox.Show("Epprom changed, all your setting will be lost during the update,\nDo you wish to continue?", "Epprom format changed (" + apmformat_version + " vs " + temp.k_format_version + ")", MessageBoxButtons.YesNo))
                        {
                            CustomMessageBox.Show("Please connect and backup your config in the configuration tab.");
                            return;
                        }
                    }
                }


                log.Info("Detected a " + board);

                string baseurl = "";
                if (board == "2560")
                {
                    baseurl = temp.url2560.ToString();
                }
                else if (board == "1280")
                {
                    baseurl = temp.url.ToString();
                }
                else if (board == "2560-2")
                {
                    baseurl = temp.url2560_2.ToString();
                }
                else if (board == "px4")
                {
                    baseurl = temp.urlpx4.ToString();
                }
                else
                {
                    CustomMessageBox.Show("Invalid Board Type");
                    return;
                }

                // use the git-history url
                if (CMB_history.Visible == true)
                {
                    baseurl = getUrl(CMB_history.Text, baseurl);
                }

                log.Info("Using " + baseurl);

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

                long bytes   = response.ContentLength;
                long contlen = bytes;

                byte[] buf1 = new byte[1024];

                FileStream fs = new FileStream(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", FileMode.Create);

                lbl_status.Text = "Downloading from Internet";

                this.Refresh();
                Application.DoEvents();

                dataStream.ReadTimeout = 30000;

                while (dataStream.CanRead)
                {
                    try
                    {
                        progress.Value = 50;// (int)(((float)(response.ContentLength - bytes) / (float)response.ContentLength) * 100);
                        this.progress.Refresh();
                    }
                    catch { }
                    int len = dataStream.Read(buf1, 0, 1024);
                    if (len == 0)
                    {
                        break;
                    }
                    bytes -= len;
                    fs.Write(buf1, 0, len);
                }

                fs.Close();
                dataStream.Close();
                response.Close();

                progress.Value = 100;
                this.Refresh();
                Application.DoEvents();
                log.Info("Downloaded");
            }
            catch (Exception ex) { lbl_status.Text = "Failed download"; CustomMessageBox.Show("Failed to download new firmware : " + ex.ToString()); return; }

            System.Threading.ThreadPool.QueueUserWorkItem(apmtype, temp.name + "!" + board);

            UploadFlash(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", board);
        }
Esempio n. 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileContent"></param>
        /// <param name="formName"></param>
        /// <param name="fileName"></param>
        /// <param name="contentType">如:image/jpeg</param>
        /// <param name="formDict"></param>
        /// <returns></returns>
        public static string HttpUploadFile(string url, byte[] fileContent, string formName, string fileName, string contentType, SortedDictionary <string, object> formDict)
        {
            try
            {
                string result        = string.Empty;
                string boundary      = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
                wr.ContentType = "multipart/form-data; boundary=" + boundary;
                wr.Method      = "POST";
                wr.KeepAlive   = false;
                wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

                Stream rs = wr.GetRequestStream();

                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                foreach (string key in formDict.Keys)
                {
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem      = string.Format(formdataTemplate, key, formDict[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    rs.Write(formitembytes, 0, formitembytes.Length);
                }
                rs.Write(boundarybytes, 0, boundarybytes.Length);

                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header         = string.Format(headerTemplate, formName, fileName, contentType);
                byte[] headerbytes    = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

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

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

                WebResponse wresp = null;
                try
                {
                    wresp = wr.GetResponse();
                    Stream       stream2 = wresp.GetResponseStream();
                    StreamReader reader2 = new StreamReader(stream2);

                    result = reader2.ReadToEnd();
                }
                catch (Exception ex)
                {
                    if (wresp != null)
                    {
                        wresp.Close();
                        wresp = null;
                    }
                }
                finally
                {
                    wr = null;
                }

                return(result);
            }
            catch (Exception ex)
            {
                handleWebException(ex);
                return(null);
            }
        }
Esempio n. 6
0
        public string getStrText(string para_API_id, string para_API_access_token, string para_API_language, string para_API_record, string para_format, string para_Hz)
        {
            //方法参数说明:
            //para_API_id:API_id(你的ID)
            //para_API_access_token(getStrAccess(...)方法得到的access_token口令)
            //para_API_language(你要识别的语言, zh, en, ct)
            //para_API_record(语音文件的路径)
            //para_format(语音文件的格式)
            //para_Hz(语音文件的采样率 16000或者8000)

            //该方法返回值:
            //该方法执行正确返回值是语音翻译的文本,错误是错误号,可以去看百度语音文档,查看对应错误

            string     strText = null;
            string     error   = null;
            FileInfo   fi      = new FileInfo(para_API_record);
            FileStream fs      = new FileStream(para_API_record, FileMode.Open);

            byte[] voice = new byte[fs.Length];
            fs.Read(voice, 0, voice.Length);
            fs.Close();

            string         getTextUrl    = "http://vop.baidu.com/server_api?lan=" + "zh" + "&cuid=" + para_API_id + "&token=" + para_API_access_token;
            HttpWebRequest getTextRequst = WebRequest.Create(getTextUrl) as HttpWebRequest;

            /* getTextRequst.Proxy = null;
             * getTextRequst.ServicePoint.Expect100Continue = false;
             * getTextRequst.ServicePoint.UseNagleAlgorithm = false;
             * getTextRequst.ServicePoint.ConnectionLimit = 65500;
             * getTextRequst.AllowWriteStreamBuffering = false;*/

            getTextRequst.ContentType   = "audio/wav;rate=8000";
            getTextRequst.ContentLength = fi.Length;
            getTextRequst.Method        = "post";
            getTextRequst.Accept        = "*/*";
            getTextRequst.KeepAlive     = true;
            getTextRequst.UserAgent     = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            getTextRequst.Timeout       = 30000;//30秒连接不成功就中断
            using (Stream writeStream = getTextRequst.GetRequestStream())
            {
                writeStream.Write(voice, 0, voice.Length);
            }

            HttpWebResponse getTextResponse = getTextRequst.GetResponse() as HttpWebResponse;

            using (StreamReader strHttpText = new StreamReader(getTextResponse.GetResponseStream(), Encoding.UTF8))
            {
                strJSON = strHttpText.ReadToEnd();
            }
            JObject jsons = JObject.Parse(strJSON);//解析JSON

            if (jsons["err_msg"].Value <string>() == "success.")
            {
                strText = jsons["result"][0].ToString();
                return(strText);
            }
            else
            {
                error = jsons["err_no"].Value <string>() + jsons["err_msg"].Value <string>();
                return(error);
            }
        }
Esempio n. 7
0
        static void GetNewFile(IProgressReporterDialogue frmProgressReporter, string baseurl, string subdir, string file)
        {
            // create dest dir
            string dir = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + subdir;

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

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

            Exception fail    = null;
            int       attempt = 0;

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

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

                        // from head
                        long bytes = response.ContentLength;

                        long contlen = bytes;

                        byte[] buf1 = new byte[4096];

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

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

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

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

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

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

                // break if we have no exception
                break;
            }

            if (attempt == 2)
            {
                throw fail;
            }
        }
Esempio n. 8
0
        public List <S_CandleItemData> Query(
            string itemCode
            , string gubun = "D" //M : 15Min, H : Hour, D : Day, W : Week, M : Month
            )
        {
            this.ItemCode = itemCode;
            int round = ItemCodeUtil.GetItemCodeRoundNum(ItemCode);

            Task.Factory.StartNew(() => {
                try
                {
                    string symbol = "169";
                    if (itemCode == "DJI@DJI")
                    {
                        symbol = "169";
                    }
                    else if (itemCode == "NAS@IXIC")
                    {
                        symbol = "14958";
                    }
                    else if (itemCode == "SPI@SPX")
                    {
                        symbol = "166";
                    }

                    else if (itemCode == "HSI@HSI")
                    {
                        symbol = "179";
                    }
                    else if (itemCode == "SHS@000002")
                    {
                        symbol = "40820";
                    }
                    else if (itemCode == "NII@NI225")
                    {
                        symbol = "178";
                    }


                    string resolution = gubun;
                    if (gubun == "H" || gubun == "1H")
                    {
                        resolution = "60";
                    }
                    else if (gubun == "2H")
                    {
                        resolution = "120";
                    }
                    else if (gubun == "4H")
                    {
                        resolution = "240";
                    }
                    else if (gubun == "5H")
                    {
                        resolution = "300";
                    }
                    else if (gubun == "M" || gubun == "1M")
                    {
                        resolution = "1";
                    }
                    else if (gubun == "5M")
                    {
                        resolution = "5";
                    }
                    else if (gubun == "15M")
                    {
                        resolution = "15";
                    }
                    else if (gubun == "30M")
                    {
                        resolution = "30";
                    }

                    Int32 from = (Int32)(DateTime.UtcNow.AddYears(-2).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    Int32 to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                    if (gubun == "M" || gubun == "1M")
                    {
                        from = (Int32)(DateTime.UtcNow.AddDays(-1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "5M")
                    {
                        from = (Int32)(DateTime.UtcNow.AddDays(-5).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "15M")
                    {
                        from = (Int32)(DateTime.UtcNow.AddDays(-15).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "30M")
                    {
                        from = (Int32)(DateTime.UtcNow.AddMonths(-1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "H" || gubun == "1H")
                    {
                        from = (Int32)(DateTime.UtcNow.AddMonths(-2).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "2H")
                    {
                        from = (Int32)(DateTime.UtcNow.AddMonths(-4).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "4H")
                    {
                        from = (Int32)(DateTime.UtcNow.AddMonths(-8).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "5H")
                    {
                        from = (Int32)(DateTime.UtcNow.AddMonths(-10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "W")
                    {
                        from = (Int32)(DateTime.UtcNow.AddYears(-5).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }
                    else if (gubun == "M")
                    {
                        from = (Int32)(DateTime.UtcNow.AddYears(-10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                        to   = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    }

                    string urlPath         = $"https://tvc4.forexpros.com/1cc1f0b6f392b9fad2b50b7aebef1f7c/1601866558/18/18/88/history?symbol={symbol}&resolution={resolution}&from={from}&to={to}";
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPath);
                    request.MaximumAutomaticRedirections = 4;
                    request.MaximumResponseHeadersLength = 4;
                    request.Credentials      = CredentialCache.DefaultCredentials;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    Stream receiveStream    = response.GetResponseStream();
                    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

                    string content = readStream.ReadToEnd();

                    var dyObj = JsonConverter.JsonToDynamicObject(content);
                    int cnt   = dyObj.t.Count;
                    for (int i = 0; i < cnt; i++)
                    {
                        Int64 t        = dyObj.t[i];
                        double o       = dyObj.o[i];
                        double c       = dyObj.c[i];
                        double h       = dyObj.h[i];
                        double l       = dyObj.l[i];
                        DateTime cTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(t);
                        //Console.WriteLine($"DT : {cTime.ToLongDateString()} O : {Math.Round(o, 2)}, H : {Math.Round(h, 2)}, L : {Math.Round(l, 2)}, C : {Math.Round(c, 2)}");

                        S_CandleItemData data = new S_CandleItemData();
                        data.DTime            = cTime;
                        data.ItemCode         = ItemCode;
                        data.OpenPrice        = (Single)Math.Round(o, round);
                        data.HighPrice        = (Single)Math.Round(h, round);
                        data.LowPrice         = (Single)Math.Round(l, round);
                        data.ClosePrice       = (Single)Math.Round(c, round);
                        data.Volume           = 0;

                        returnList.Add(data);
                    }
                }
                catch (Exception ex)
                {
                    string err = ex.Message;
                }
                finally
                {
                    manualEvent.Set();
                }
            });
            manualEvent.WaitOne();

            return(returnList);
        }
 public virtual HttpWebRequest CreateWebRequest(string requestUri, bool?emulateHttpViaPost = null)
 {
     return((HttpWebRequest)WebRequest.Create(requestUri));
 }
Esempio n. 10
0
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体

            //从事件参数中取得当前业务实体
            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
            {
                return;
            }
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
            {
                return;
            }
            PurchaseOrder po = key.GetEntity() as PurchaseOrder;
            if (po == null)
            {
                return;
            }

            if (po.Status == PODOCStatusEnum.Approving && po.OriginalData.Status == PODOCStatusEnum.Opened)
            {
                //是否走OA接口
                string profileValue = Common.GetProfileValue(Common.iProfileCode, Context.LoginOrg.ID);
                if (profileValue.ToLower() == "true")
                {
                    #region 根据描述是否推送到OA

                    string docTypeDesc = po.DocumentType.Description;
                    if (string.IsNullOrEmpty(docTypeDesc))
                    {
                        return;
                    }
                    string returnMsg    = string.Empty;
                    string businessType = "OA流程创建";
                    string requestName  = "采购订单" + po.DocNo + "审批";
                    User   user         = User.Finder.FindByID(Context.LoginUserID);
                    string userID       = user.Code;
                    string workflowId   = po.DocumentType.DescFlexField.PrivateDescSeg1;
                    bool   isPO         = true;
                    if (po.TC.Code.ToUpper() != "C001")
                    {
                        workflowId = po.DocumentType.DescFlexField.PrivateDescSeg2;
                    }
                    string            oaRquestID = po.DescFlexField.PrivateDescSeg30;
                    POLine.EntityList polines    = po.POLines;



                    if (string.IsNullOrEmpty(oaRquestID))
                    {
                        string url = Common.GetProfileValue(Common.csProfileCode, Context.LoginOrg.ID);
                        string workflowRequestInfo = Common.CreateXmlString(requestName, userID, workflowId, isPO, polines, null);
                        WeaverOAService.WorkflowServiceXml client = new WeaverOAService.WorkflowServiceXml();
                        client.Url = url;
                        returnMsg  = client.doCreateWorkflowRequest(workflowRequestInfo, userID);
                    }
                    else
                    {
                        businessType = "OA流程更新";
                        string url = Common.GetProfileValue(Common.msProfileCode, Context.LoginOrg.ID);
                        string workflowRequestInfo = Common.CreateXmlStringForUpdate(oaRquestID, userID, workflowId, isPO, polines, null);
                        WeaverOAForUpadteService.WorkflowServiceforUpadte client = new WeaverOAForUpadteService.WorkflowServiceforUpadte();
                        client.Url = url;
                        bool flag = client.RequestUpdate(workflowRequestInfo);
                        if (flag == false)
                        {
                            returnMsg = "-1";
                        }
                        else
                        {
                            returnMsg = oaRquestID;
                        }
                    }
                    if (string.IsNullOrEmpty(returnMsg) || returnMsg.StartsWith("-"))
                    {
                        string msg = businessType + "失败,请联系系统管理员!OA返回值:" + returnMsg;
                        throw new Exception(msg);
                    }
                    if (string.IsNullOrEmpty(oaRquestID))
                    {
                        po.DescFlexField.PrivateDescSeg30 = returnMsg;
                    }

                    #endregion
                }
                //是否走易派客接口
                string eprcProfileValue = Common.GetProfileValue("ZS006", Context.LoginOrg.ID);
                if (eprcProfileValue.ToLower() == "true")
                {
                    #region 回写易派客订单状态

                    //根据来源单据号取得请购单数据
                    List <long> list = new List <long>();
                    foreach (POLine line in po.POLines)
                    {
                        if (line.SrcDocInfo != null && line.SrcDocInfo.SrcDoc != null)
                        {
                            long srcDoc = line.SrcDocInfo.SrcDoc.EntityID;
                            if (list.Contains(srcDoc) == false)
                            {
                                list.Add(srcDoc);
                            }
                        }
                    }
                    foreach (long srcDoc in list)
                    {
                        PR     pr                = PR.Finder.FindByID(srcDoc);
                        string orderId           = pr.DescFlexField.PrivateDescSeg25;
                        string purchasecompanyid = pr.DescFlexField.PrivateDescSeg26;
                        string orderStatus       = "13";
                        string returnCheckTime   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        if (string.IsNullOrEmpty(orderId))
                        {
                            continue;
                        }
                        string epecUrl     = Common.GetProfileValue("ZS007", Context.LoginOrg.ID);
                        string corpCode    = Common.GetProfileValue("ZS011", Context.LoginOrg.ID);//公司代码
                        string accessToken = GetAccessToken(epecUrl);

                        StringBuilder urlBuilder = new StringBuilder(epecUrl);
                        urlBuilder.Append("/apigate/v2/order/approve");
                        urlBuilder.Append("?access_token=").Append(accessToken);
                        urlBuilder.Append("&data=");
                        urlBuilder.Append("{\"corpcode\":\"").Append(corpCode).Append("\",");
                        urlBuilder.Append("\"orderId\":\"").Append(orderId).Append("\",");
                        urlBuilder.Append("\"purchaseCompanyId\":\"").Append(purchasecompanyid).Append("\",");
                        urlBuilder.Append("\"orderStatus\":\"").Append(orderStatus).Append("\",");
                        urlBuilder.Append("\"returnCheckTime\":\"").Append(returnCheckTime).Append("\"}");

                        string serviceAddress = urlBuilder.ToString();
                        logger.Error("获取消息请求地址:" + serviceAddress);

                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                        request.Method      = "POST";
                        request.ContentType = "application/json";
                        HttpWebResponse response         = (HttpWebResponse)request.GetResponse();
                        Stream          myResponseStream = response.GetResponseStream();
                        StreamReader    reader           = new StreamReader(myResponseStream, Encoding.UTF8);
                        string          jsonString       = reader.ReadToEnd();

                        logger.Error("请购请求返回值:" + jsonString);
                        //解析josn
                        JObject jo       = JObject.Parse(jsonString);
                        string  epecFlag = jo["success"].ToString();
                        string  rtnData  = jo["data"].ToString();
                        if (epecFlag.ToLower() == "false")
                        {
                            if (string.IsNullOrEmpty(rtnData) || rtnData.ToLower() == "null")
                            {
                                string code  = jo["code"].ToString();
                                string exMsg = jo["msg"].ToString();
                                throw new Exception("请求易派客系统发生错误:Code=" + code + ",Msg=" + exMsg);
                            }
                            jo = JObject.Parse(rtnData);
                            string isMatch = jo["ismatch"].ToString();
                            string remark  = jo["remark"].ToString();
                            if (epecFlag.ToLower() == "false")
                            {
                                string exMsg = jo["msg"].ToString();
                                throw new Exception("请求易派客系统发生错误:" + exMsg);
                            }
                            if (isMatch == "0")
                            {
                                throw new Exception("传递数据到易派客系统发生错误:" + remark);
                            }
                        }
                    }

                    #endregion
                }
            }

            #endregion
        }
Esempio n. 11
0
		private static void CheckForUpdates()
		{
            try
            {
                SplashScreen.MessageStr = "Checking for Razor Updates...";
            }
            catch { }

			int uid = 0;
			try
			{
				string str = Config.GetRegString( Microsoft.Win32.Registry.LocalMachine, "UId" );
				if ( str == null || str.Length <= 0 )
					str = Config.GetRegString( Microsoft.Win32.Registry.CurrentUser, "UId" );

				if ( str != null && str.Length > 0 )
					uid = Convert.ToInt32( str, 16 );
			}
			catch
			{
				uid = 0;
			}
			
			if ( uid == 0 )
			{
				try
				{
					uid = Utility.Random( int.MaxValue - 1 );
					if ( !Config.SetRegString( Microsoft.Win32.Registry.LocalMachine, "UId", String.Format( "{0:x}", uid ) ) )
					{
						if ( !Config.SetRegString( Microsoft.Win32.Registry.CurrentUser, "UId", String.Format( "{0:x}", uid ) ) )
							uid = 0;
					}
				}
				catch
				{
					uid = 0;
				}
			}
			
			try
			{
				//ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

				//WebRequest req = WebRequest.Create( String.Format( "https://zenvera.com/razor/version.php?id={0}", uid ) );

				HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://razor.uo.cx/version.txt");
				req.UserAgent = "Razor Update Check";

				using ( StreamReader reader = new StreamReader( req.GetResponse().GetResponseStream() ) )
				{
					Version newVer = new Version( reader.ReadToEnd().Trim() );
					Version v = Assembly.GetCallingAssembly().GetName().Version;
					if ( v.CompareTo( newVer ) < 0 ) // v < newVer
					{
                        ProcessStartInfo processInfo = new ProcessStartInfo();
                        processInfo.Verb = "runas"; // Administrator Rights
                        processInfo.FileName = Path.Combine(Config.GetInstallDirectory(), "Updater.exe");
						processInfo.Arguments = v.ToString();
                        Process.Start(processInfo);
						Process.GetCurrentProcess().Kill();
					}
				}
			}
			catch
			{
			}

            try
            {
                SplashScreen.Message = LocString.Initializing;
            }
            catch { }
		}
Esempio n. 12
0
        /// <summary>
        /// FTP 文件上传
        /// </summary>
        /// <param name="ftpServerIP">FTP服务器路径(必须如下格式ftp://11.22.11.22 :21)</param>
        /// <param name="ftpUserID">用户名ID</param>
        /// <param name="ftpPassword">用户密码</param>
        /// <param name="filePath">相对路径</param>
        /// <param name="filename">上传保存的文件名</param>
        /// <param name="strUploadLocalFileName">上传文件的全路经</param>
        /// <returns></returns>
        public static bool UploadFtp(string ftpServerIP,
                                     string filePath,
                                     string ftpUserID,
                                     string ftpPassword,
                                     string filename,
                                     string strUploadLocalFileName)
        {
            FileInfo      fileInf = new FileInfo(strUploadLocalFileName);
            string        uri     = ftpServerIP + "/" + filePath + "/" + filename;
            FtpWebRequest reqFTP;
            Stream        strm     = null;
            FileStream    fs       = null;
            bool          bSuccess = false;

            reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
            try
            {
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                // By default KeepAlive is true, where the control connection is not closed
                // after a command is executed.
                reqFTP.KeepAlive = false;
                // Specify the command to be executed.
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // Specify the data transfer type.
                reqFTP.UseBinary = true;
                //reqFTP.UsePassive = false;

                // Notify the server about the size of the uploaded file
                reqFTP.ContentLength    = fileInf.Length;
                reqFTP.ReadWriteTimeout = 1000;
                //reqFTP.Timeout = 1000;


                // The buffer size is set to 2kb
                int    buffLength = 4000;
                byte[] buff       = new byte[buffLength];
                int    contentLen;

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                // Stream to which the file to be upload is written
                strm = reqFTP.GetRequestStream();
                strm.WriteTimeout = 1000;
                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);
                int itotal = contentLen;
                // Till Stream content ends
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                    if (contentLen >= 0)
                    {
                        itotal += contentLen;
                    }
                    else
                    {
                        LogMgr.WriteDebugDefSys("读取数据小于0。。。。。。");
                        return(false);
                    }
                    //strm.Flush();
                }
//                LogMgr.WriteInfoDefSys("strm.Flush()......");
                strm.Flush();

//                 string strMsg = string.Format("第一次读取的长度为:{0}, 累计的文件长度为:{1}",
//                     reqFTP.ContentLength,
//                     itotal);
//                 LogMgr.WriteInfoDefSys(strMsg);
                bSuccess = true;
            }
            catch (Exception ex)
            {
                reqFTP.Abort();
                LogMgr.WriteErrorDefSys("Upload Ftp Ex + " + ex.Message + ex.StackTrace);
                bSuccess = false;
            }
            finally
            {
                if (strm != null)
                {
                    strm.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
                if (reqFTP != null)
                {
                    reqFTP.Abort();
                }
            }


            return(bSuccess);
        }
Esempio n. 13
0
        static string GetMailByFolder(string argtoken, string argFolderQuery, string argOfficerEmail)
        {
            string sret = string.Empty;


            StringBuilder sbXML2 = new StringBuilder();

            sbXML2.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sbXML2.Append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">");
            sbXML2.Append("<soap:Header>");
            sbXML2.Append("<context xmlns=\"urn:zimbra\">");
            sbXML2.Append("<format type=\"xml\"/>");
            sbXML2.Append(string.Format("<authToken>{0}</authToken>", argtoken));
            sbXML2.Append("</context>");
            sbXML2.Append("</soap:Header>");
            sbXML2.Append("<soap:Body>");
            sbXML2.Append("<SearchRequest limit=\"2000\" ");
            sbXML2.Append(string.Format(" xmlns=\"urn:zimbraMail\">"));
            sbXML2.Append(string.Format("<query>{0}</query>", argFolderQuery));
            sbXML2.Append("</SearchRequest>");
            sbXML2.Append("</soap:Body>");
            sbXML2.Append("</soap:Envelope>");
            Console.WriteLine(sbXML2);

            HttpWebRequest httpZimbraRequest2 = (HttpWebRequest)WebRequest.Create("https://accounts.mail.go.th/service/soap");

            httpZimbraRequest2.ContentType = "application/soapxml";

            byte[] byteArray2 = Encoding.UTF8.GetBytes(sbXML2.ToString());

            httpZimbraRequest2.Method        = "POST";
            httpZimbraRequest2.ContentLength = byteArray2.Length;

            using (var stream = httpZimbraRequest2.GetRequestStream())
            {
                stream.Write(byteArray2, 0, byteArray2.Length);
            }
            var response2 = (HttpWebResponse)httpZimbraRequest2.GetResponse();

            var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();

            Console.WriteLine(responseString2);



            //@@ reload to XML
            XmlDocument responseDoc2 = new XmlDocument();

            responseDoc2.LoadXml(responseString2);
            //XmlNodeList docs = responseDoc2.SelectNodes("/SearchResponse");
            XmlNodeList docs = responseDoc2.GetElementsByTagName("c");

            Console.WriteLine("have {0} nodes", docs.Count);
            for (int i = 0; i < docs.Count; i++)
            {
                if (docs[i].InnerXml.Length > 0)
                {
                    string sInnerXml = docs[i].InnerXml;
                    Console.WriteLine("{0}). {1}", i, sInnerXml);
                    string sId = GetIdInnerXml(sInnerXml);
                    Console.WriteLine("id = {0}", sId);
                    string sEmailFrom = GetEmailFromInnerXml(sInnerXml);
                    Console.WriteLine("from = {0}", sEmailFrom);

                    string sPath = string.Format(@".\{0}\{1}{2:yyyyMMddHH}id{3}", argOfficerEmail, sEmailFrom, System.DateTime.Now, sId);  //@@ include file name
                    try
                    {
                        if (!Directory.Exists(sPath))
                        {
                            Directory.CreateDirectory(sPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    //if (sId == "257")
                    //{
                    Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@ next to call Get-Msg @@@@@@@@@@@@@@@@@@@@@");
                    string smsg = GetMsgById(argtoken, sId, sEmailFrom, sPath);

                    //}

                    //XmlNode node = docs[i].SelectNodes("//c");
                    //string val = node.SelectSingleNode("m").Attributes["id"].Value;
                    //Console.WriteLine("id value = {0}", val);
                }
            }


            return(sret);
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            string sFolderQuery      = "in:inbox";
            string sOfficerEmail     = "*****@*****.**";
            string sOfficerEmailPass = "******";

            if (args != null)
            {
                ///Console.WriteLine("argument length = {0}", args.Length);
                if (args.Length < 4)
                {
                    if (args.Length == 1)
                    {
                        sFolderQuery += string.Format("/{0}", args[0]);
                    }
                    else if (args.Length > 1 && args.Length < 4)
                    {
                        sFolderQuery     += string.Format("/{0}", args[0]);
                        sOfficerEmail     = args[1];
                        sOfficerEmailPass = args[2];
                    }
                }
                else if (args.Length >= 4)
                {
                    Console.WriteLine("This version can use only 1 sub level folder (from inbox:) \r\n Usage: ega.Consoles.ZimbraPhotoRama9.exe <<Folder Name>>");
                    Console.WriteLine("For exammple: \r\n ega.Consoles.ZimbraPhotoRama9.exe Bangkok [email protected] Ph@toking91 \r\n (It will get all emails under inbox/Bangkok)");
                    return;
                }
            }

            string stoken = string.Empty;

            ServicePointManager.CertificatePolicy = new Program();
            StringBuilder xml = new StringBuilder();

            xml.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            xml.Append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">");
            xml.Append("<soap:Header>");
            xml.Append("<context xmlns=\"urn:zimbra\">");
            xml.Append("<format type=\"xml\"/>");
            xml.Append("</context>");
            xml.Append("</soap:Header>");
            xml.Append("<soap:Body>");
            xml.Append("<AuthRequest xmlns=\"urn:zimbraAccount\">");
            xml.Append(string.Format("<account by=\"name\">{0}</account>", sOfficerEmail));
            xml.Append(string.Format("<password>{0}</password>", sOfficerEmailPass));
            xml.Append("</AuthRequest>");
            xml.Append("</soap:Body>");
            xml.Append("</soap:Envelope>");
            Console.WriteLine(xml);
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://accounts.mail.go.th/service/soap");

            httpRequest.ContentType = "application/soapxml";

            byte[] byteArray = Encoding.UTF8.GetBytes(xml.ToString());

            httpRequest.Method        = "POST";
            httpRequest.ContentLength = byteArray.Length;
            try
            {
                using (var stream = httpRequest.GetRequestStream())
                {
                    stream.Write(byteArray, 0, byteArray.Length);
                }
                var response = (HttpWebResponse)httpRequest.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Console.WriteLine(responseString);

                //Console.ReadLine();

                XmlDocument responseDoc = new XmlDocument();
                responseDoc.LoadXml(responseString);
                string authtoken = responseDoc.GetElementsByTagName("authToken").Item(0).InnerXml;
                stoken = authtoken;
                Console.WriteLine("\r\nauthToken:{0}\r\n", stoken);

                //CheckAndSendLineNotification(stoken);


                //@@ next call other Zimbra API function here.


                string sMails = string.Empty;                                  //might be use List<string> instead.
                sMails = GetMailByFolder(stoken, sFolderQuery, sOfficerEmail); // if want to sub folder for example "Bangkok" use , "in:inbox/Bangkok"

                //DownloadRemoteImageFile(@"https://accounts.mail.go.th/service/home/~/?auth=co&loc=th&id=262&part=2.4", "testImage001.jpg");
                //byte[] data;
                //using (WebClient client = new WebClient())
                //{
                //    client.UseDefaultCredentials = true;
                //    client.Credentials = new NetworkCredential("*****@*****.**", "Ega@2017");
                //    data = client.DownloadData("https://accounts.mail.go.th/service/home/~/?auth=co&loc=th&id=262&part=2.4");
                //}
                //File.WriteAllBytes("testimage.jpg", data);
            }
            catch (WebException wex)
            {
                var pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
                Console.WriteLine("Web Error: \r\n{0}", pageContent);
                //Console.WriteLine("send notification to LINE..");
                //SendNotification("[MailGoThai]: ไม่สามารถเชื่อมต่อ MailGoThai ได้ โปรดติดต่อผู้ดูแลระบบ");
            }
        }
Esempio n. 15
0
        public void GenerateDB(string location, string Email, string Password)
        {
            // Generate partial shelf items
            PopulatePartial partialCreation = new PopulatePartial();
            List <int>      partialIds      = partialCreation.GenerateList(Email, Password);


            // Query NetSuite
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("https://rest.netsuite.com/app/site/hosting/restlet.nl?script=131&deploy=1&binlocation=" + location);

            objRequest.Method      = "GET";
            objRequest.ContentType = "application/json";
            objRequest.Headers.Add(HttpRequestHeader.Authorization, "NLAuth nlauth_account=" + ConfigurationManager.AppSettings["NetSuiteAccountNumber"].ToString() + ", nlauth_email=" + Email + ", nlauth_signature=" + Password + "");
            objRequest.Timeout = 500000;
            HttpWebResponse objResponse = objRequest.GetResponse() as HttpWebResponse;

            // Pull data off of NetSuite
            using (Stream objResponseStream = objResponse.GetResponseStream())
            {
                StreamReader sr      = new StreamReader(objResponseStream);
                string       rawData = sr.ReadToEnd();
                JArray       rows    = JArray.Parse(rawData);

                // List that will store all of the Count Items
                List <Item> Items = new List <Item>();

                // Parse Json and store values
                foreach (JObject row in rows)
                {
                    // Create new Count Item
                    Item item = new Item();

                    JToken cols                = row["columns"];
                    string Name                = cols["itemid"] == null ? null : cols["itemid"].Value <string>();
                    string BinLocation         = cols["custitem_bin_location"] == null ? null : cols["custitem_bin_location"].Value <string>();
                    string Description         = cols["salesdescription"] == null ? null : cols["salesdescription"].Value <string>();
                    int    OnHand              = cols["locationquantityonhand"] == null ? 0 : cols["locationquantityonhand"].Value <int>();
                    int    ID                  = cols["internalid"]["internalid"] == null ? 0 : cols["internalid"]["internalid"].Value <int>();
                    string VendorCode          = cols["vendorcode"] == null ? null : cols["vendorcode"].Value <string>();
                    string Brand               = cols["custitem_brand"] == null ? null : cols["custitem_brand"]["name"].Value <string>();
                    int    QuantityBackOrdered = cols["quantitybackordered"] == null ? 0 : cols["quantitybackordered"].Value <int>();
                    string Vendor              = cols["othervendor"] == null ? null : cols["othervendor"]["name"].Value <string>();
                    string PreferredVendor     = cols["vendor"] == null ? null : cols["vendor"]["name"].Value <string>();
                    int    WebID               = cols["custitem_web_product_id"] == null ? 0 : cols["custitem_web_product_id"].Value <int>();

                    if (Vendor == PreferredVendor || Vendor == null) // Some items have no vendor, but still need to be counted
                    {
                        // Create the items
                        item.Name                = Name;
                        item.BinLocation         = BinLocation;
                        item.Description         = Description;
                        item.OnHand              = OnHand;
                        item.ID                  = ID;
                        item.NewOnHand           = OnHand;
                        item.NewBinLocation      = BinLocation;
                        item.CounterInitials     = null;
                        item.VendorCode          = VendorCode;
                        item.Brand               = Brand;
                        item.QuantityBackOrdered = QuantityBackOrdered;
                        item.WebProductID        = WebID;
                        if (partialIds.Contains(item.ID))
                        {
                            item.OnPartial = true;
                        }

                        // Add item to the Items list
                        db.Items.Add(item);
                    }
                }
                db.SaveChanges();
            }
        }
Esempio n. 16
0
        public string Get(string oauthToken, string oauthTokenSecret, string oauthConsumerKey, string oauthConsumerSecret)
        {
            try
            {
                // oauth implementation details
                var oauth_version          = "1.0";
                var oauth_signature_method = "HMAC-SHA1";

                // unique request details
                var oauthNonce = Convert.ToBase64String(
                    new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())
                    );

                var timeSpan       = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                var oauthTimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

                var resourceUrl  = "https://api.twitter.com/1.1/account/verify_credentials.json";
                var requestQuery = "include_email=true";

                // create oauth signature
                var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                 "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";

                var baseString = string.Format(baseFormat,
                                               oauthConsumerKey,
                                               oauthNonce,
                                               oauth_signature_method,
                                               oauthTimestamp,
                                               oauthToken,
                                               oauth_version
                                               );

                baseString = string.Concat("GET&", Uri.EscapeDataString(resourceUrl) + "&" + Uri.EscapeDataString(requestQuery), "%26", Uri.EscapeDataString(baseString));

                var compositeKey = string.Concat(Uri.EscapeDataString(oauthConsumerSecret),
                                                 "&", Uri.EscapeDataString(oauthTokenSecret));

                string oauthSignature;
                using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
                {
                    oauthSignature = Convert.ToBase64String(
                        hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString))
                        );
                }

                // create the request header
                var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", oauth_timestamp=\"{4}\", oauth_token=\"{5}\", oauth_version=\"{6}\"";

                var authHeader = string.Format(headerFormat,
                                               Uri.EscapeDataString(oauthConsumerKey),
                                               Uri.EscapeDataString(oauthNonce),
                                               Uri.EscapeDataString(oauthSignature),
                                               Uri.EscapeDataString(oauth_signature_method),
                                               Uri.EscapeDataString(oauthTimestamp),
                                               Uri.EscapeDataString(oauthToken),
                                               Uri.EscapeDataString(oauth_version)
                                               );


                // make the request

                ServicePointManager.Expect100Continue = false;
                resourceUrl += "?include_email=true";
                var request = (HttpWebRequest)WebRequest.Create(resourceUrl);
                request.Headers.Add("Authorization", authHeader);
                request.Method = "GET";

                var response       = request.GetResponse();
                var responseStream = response.GetResponseStream();
                if (responseStream == null)
                {
                    return(string.Empty);
                }

                var result = JsonConvert.DeserializeObject <TwitterVerifyCredentialsDto>(new StreamReader(responseStream).ReadToEnd());
                return(result.Email);
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Esempio n. 17
0
        public static async void CheckForUpdate()
        {
            var logger         = LogManager.GetCurrentClassLogger();
            var currentVersion = Version.Parse(VERSION);

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

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

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

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

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

                                case MessageBoxResult.No:

                                    break;
                                }
                            }
                            else if (ghVersion.CompareTo(currentVersion) == 0)
                            {
                                logger.Warn("Running Latest Version: " + githubVersion);
                            }
                            else
                            {
                                logger.Warn("Running TESTING Version!! : " + VERSION);
                            }
                        }
                        else
                        {
                            logger.Warn("Failed to Parse version: " + githubVersion);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Ignore for now
            }
        }
Esempio n. 18
0
        static DownloadStatus Download(string url, long startPosition, int timeout, string filename)
        {
            DownloadStatus rtn = DownloadStatus.SUCCESS;

            HttpWebRequest request = null;
            WebResponse response = null;
            Stream webStream = null;
            FileStream fileStream = null;

            try
            {
                // setup our file to be written to
                if (!Directory.Exists(Path.GetDirectoryName(filename)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));

                if (startPosition == 0)
                    fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
                else
                    fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None);

                // setup and open our connection
                request = (HttpWebRequest)WebRequest.Create(url);
                request.AddRange((int)startPosition);
                request.Timeout = timeout;
                request.ReadWriteTimeout = 20000;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:10.0) Gecko/20100101 Firefox/26.0";
                request.Proxy = WebRequest.DefaultWebProxy;
                request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                response = request.GetResponse();
                webStream = response.GetResponseStream();

                // setup our tracking variables for progress
                int bytesRead = 0;
                long totalBytesRead = 0;
                long totalBytes = response.ContentLength + startPosition;

                // download the file and progressively write it to disk
                byte[] buffer = new byte[2048];
                bytesRead = webStream.Read(buffer, 0, buffer.Length);
                while (bytesRead > 0)
                {
                    // write to our file
                    fileStream.Write(buffer, 0, bytesRead);
                    totalBytesRead = fileStream.Length;

                    //FileLog.Debug("Download progress: {2:0.0}% ({0:###,###,###} / {1:###,###,###} bytes)", totalBytesRead, totalBytes, 100.0 * totalBytesRead / totalBytes);

                    // read the next stretch of data
                    bytesRead = webStream.Read(buffer, 0, buffer.Length);
                }

                // if the downloaded unexpectedly stopped, but we have more left, close the stream but 
                // save the file for resuming
                if (fileStream.Length != totalBytes && totalBytes != -1)
                {
                    rtn = DownloadStatus.INCOMPLETE;
                    fileStream.Close();
                    fileStream = null;
                }
                // if the download stopped and we don't know the total size
                else if (totalBytes == -1)
                {
                    try
                    {
                        fileStream.Close();
                        // we could a check if a valid mp4 file here and return success if okay
                    }
                    catch
                    {
                        startPosition = 0;
                        FileLog.Warning("Invalid trailer when downloading file from: " + url);
                        rtn = DownloadStatus.FAILED;
                    }
                }
            }
            catch (UriFormatException)
            {
                // url was invalid
                FileLog.Warning("Invalid URL: {0}", url);
                rtn = DownloadStatus.FAILED;
            }
            catch (WebException e)
            {
                // file doesnt exist
                if (e.Message.Contains("404"))
                {
                    FileLog.Warning("File does not exist: {0}", url);
                    rtn = DownloadStatus.FAILED;
                }
                // timed out or other similar error
                else
                    rtn = DownloadStatus.TIMED_OUT;

            }
            catch (ThreadAbortException)
            {
                // user is shutting down the program
                fileStream.Close();
                fileStream = null;
                if (File.Exists(filename)) File.Delete(filename);
                rtn = DownloadStatus.FAILED;
            }
            catch (Exception e)
            {
                FileLog.Error("Unexpected error downloading file from: {0}, {1}", url, e.Message);
                rtn = DownloadStatus.FAILED;
            }

            // if we failed delete the file
            if (rtn == DownloadStatus.FAILED)
            {
                if (fileStream != null) fileStream.Close();
                fileStream = null;
                if (File.Exists(filename)) File.Delete(filename);
            }

            if (webStream != null) webStream.Close();
            if (fileStream != null) fileStream.Close();
            if (response != null) response.Close();
            if (request != null) request.Abort();

            return rtn;
        }
Esempio n. 19
0
        private void ShowPoint()
        {
            #region 네트워크 상태 확인
            var current_network = Connectivity.NetworkAccess; // 현재 네트워크 상태
            if (current_network == NetworkAccess.Internet)    // 네트워크 연결 가능
            {
                if (Global.b_user_login)
                {
                    string str = @"{";
                    str += "USER_ID:'" + Global.ID;  //아이디찾기에선 Name으로
                    str += "'}";

                    //// JSON 문자열을 파싱하여 JObject를 리턴
                    JObject jo = JObject.Parse(str);

                    UTF8Encoding encoder = new UTF8Encoding();
                    byte[]       data    = encoder.GetBytes(jo.ToString()); // a json object, or xml, whatever...

                    //request.Method = "POST";
                    HttpWebRequest request = WebRequest.Create(Global.WCFURL + "SelectUserPoint") as HttpWebRequest;
                    request.Method        = "POST";
                    request.ContentType   = "application/json";
                    request.ContentLength = data.Length;

                    //request.Expect = "application/json";

                    request.GetRequestStream().Write(data, 0, data.Length);

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                        }
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            var    readdata = reader.ReadToEnd();
                            string test     = JsonConvert.DeserializeObject <string>(readdata);

                            if (test != null && test != "null")
                            {
                                MyPointLabel.Text = int.Parse(test).ToString("N0") + " Point";
                            }
                            else
                            {
                                MyPointLabel.Text = "0 Point";
                            }
                        }
                    }
                }
                else
                {
                    MyPointLabel.Text = int.Parse("0").ToString("N0") + " Point";
                }
            }    // 네트워크 연결 가능
            else // 연결 불가 -> 포인트 0으로 처리
            {
                MyPointLabel.Text = "0 Point";
            }
            #endregion
        }
Esempio n. 20
0
        /// <summary>
        ///     스텝
        /// </summary>
        /// <param name="month"></param>
        /// <param name="svsvcid"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public static IEnumerable <string> GetFreeSite(string year, string month, string svsvcid)
        {
            try
            {
                string parameter =
                    string.Format(
                        "year={0}&month={1}&rsvsvcid={2}&waitnum=0&usetimeunitcode=B403&usedaystdrcptday=&usedaystdrcpttime=&rsvdaystdrcptday=1&rsvdaystdrcpttime=24",
                        year, month, svsvcid);

                var httpWRequest =
                    (HttpWebRequest)WebRequest.Create("http://yeyak.seoul.go.kr/reservation/include/schedule.web");
                httpWRequest.UserAgent     = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
                httpWRequest.ContentType   = "application/x-www-form-urlencoded";
                httpWRequest.KeepAlive     = true;
                httpWRequest.Method        = "Post";
                httpWRequest.ContentLength = parameter.Length;


                var sw = new StreamWriter(httpWRequest.GetRequestStream());
                sw.Write(parameter);
                sw.Close();

                var theResponse = (HttpWebResponse)httpWRequest.GetResponse();
                var sr          = new StreamReader(theResponse.GetResponseStream(), Encoding.GetEncoding("euc-kr"));

                string resultHtml = sr.ReadToEnd();


                int    startIndex = 0;
                string startText  = "<usedate>";
                string endText    = "</state>";

                var sites = new List <string>();
                while (true)
                {
                    try
                    {
                        startIndex = resultHtml.IndexOf(startText, startIndex + 1);
                        if (startIndex == -1)
                        {
                            break;
                        }
                        string resultText =
                            resultHtml.Substring(startIndex + startText.Length,
                                                 resultHtml.IndexOf(endText, startIndex) - startIndex - startText.Length)
                            .Trim();

                        if (resultText.Contains("</usedate><state>A"))
                        {
                            resultText = resultText.Replace("</usedate><state>A", "");
                            sites.Add(resultText);
                        }
                    }
                    catch (Exception ex)
                    {
                        Util.ErrorLog(MethodBase.GetCurrentMethod(), ex, "에러");
                    }
                }

                return(sites);
            }
            catch (Exception ex)
            {
                Util.ErrorLog(MethodBase.GetCurrentMethod(), ex, "에러");
                return(null);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Gets the list of Search Results which match the given search term.
        /// </summary>
        /// <param name="text">Search Term.</param>
        /// <param name="callback">Callback to invoke when the operation completes.</param>
        /// <param name="state">State to pass to the callback.</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void Search(String text, PelletSearchServiceCallback callback, Object state)
        {
            String search = _searchUri + "?search=" + HttpUtility.UrlEncode(text);

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

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = "text/json";

            Tools.HttpDebugRequest(request);

            try
            {
                String jsonText;
                JArray json;
                request.BeginGetResponse(result =>
                {
                    try
                    {
                        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                        {
                            Tools.HttpDebugResponse(response);
                            jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                            json     = JArray.Parse(jsonText);

                            response.Close();

                            // Parse the Response into Search Results

                            List <SearchServiceResult> results = new List <SearchServiceResult>();

                            foreach (JToken res in json.Children())
                            {
                                JToken hit  = res.SelectToken("hit");
                                String type = (String)hit.SelectToken("type");
                                INode node;
                                if (type.ToLower().Equals("uri"))
                                {
                                    node = new UriNode(null, UriFactory.Create((String)hit.SelectToken("value")));
                                }
                                else
                                {
                                    node = new BlankNode(null, (String)hit.SelectToken("value"));
                                }
                                double score = (double)res.SelectToken("score");

                                results.Add(new SearchServiceResult(node, score));
                            }

                            callback(results, state);
                        }
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
            }
            catch (Exception ex)
            {
                callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 创建POST方式的HTTP请求
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
        /// <param name="timeout">请求的超时时间</param>
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary <string, string> parameters, int?timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            //如果是发送HTTPS请求
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                //request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";



            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }

            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //如果需要POST数据
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int           i      = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return(request.GetResponse() as HttpWebResponse);
        }
Esempio n. 23
0
        /// <summary>
        /// Gets the list of Search Results which match the given search term.
        /// </summary>
        /// <param name="text">Search Term.</param>
        /// <returns>A list of Search Results representing Nodes in the Knowledge Base that match the search term.</returns>
        public List <SearchServiceResult> Search(String text)
        {
            String search = _searchUri + "?search=" + HttpUtility.UrlEncode(text);

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

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = "text/json";

            Tools.HttpDebugRequest(request);

            String jsonText;
            JArray json;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Tools.HttpDebugResponse(response);
                jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                json     = JArray.Parse(jsonText);

                response.Close();
            }

            // Parse the Response into Search Results
            try
            {
                List <SearchServiceResult> results = new List <SearchServiceResult>();

                foreach (JToken result in json.Children())
                {
                    JToken hit  = result.SelectToken("hit");
                    String type = (String)hit.SelectToken("type");
                    INode  node;
                    if (type.ToLower().Equals("uri"))
                    {
                        node = new UriNode(null, UriFactory.Create((String)hit.SelectToken("value")));
                    }
                    else
                    {
                        node = new BlankNode(null, (String)hit.SelectToken("value"));
                    }
                    double score = (double)result.SelectToken("score");

                    results.Add(new SearchServiceResult(node, score));
                }

                return(results);
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                throw new RdfReasoningException("A HTTP error occurred while communicating with Pellet Server", webEx);
            }
            catch (Exception ex)
            {
                throw new RdfReasoningException("Error occurred while parsing Search Results from the Search Service", ex);
            }
        }
Esempio n. 24
0
        private void lbl_px4io_Click(object sender, EventArgs e)
        {
            CustomMessageBox.Show("Please save the px4io.bin file to your microsd card to insert into your px4.");

            string baseurl = "http://firmware.diydrones.com/PX4IO/latest/PX4IO/px4io.bin";

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

                long bytes   = response.ContentLength;
                long contlen = bytes;

                byte[] buf1 = new byte[1024];

                FileStream fs = new FileStream(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"px4io.bin", FileMode.Create);

                lbl_status.Text = "Downloading from Internet";

                this.Refresh();
                Application.DoEvents();

                dataStream.ReadTimeout = 30000;

                while (dataStream.CanRead)
                {
                    try
                    {
                        progress.Value = 50;// (int)(((float)(response.ContentLength - bytes) / (float)response.ContentLength) * 100);
                        this.progress.Refresh();
                    }
                    catch { }
                    int len = dataStream.Read(buf1, 0, 1024);
                    if (len == 0)
                    {
                        break;
                    }
                    bytes -= len;
                    fs.Write(buf1, 0, len);
                }

                fs.Close();
                dataStream.Close();
                response.Close();

                lbl_status.Text = "Done";
                Application.DoEvents();
            }
            catch { CustomMessageBox.Show("Error receiving firmware"); return; }

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.FileName = "px4io.bin";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if (sfd.FileName != "")
                {
                    if (File.Exists(sfd.FileName))
                    {
                        File.Delete(sfd.FileName);
                    }

                    File.Copy(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"px4io.bin", sfd.FileName);
                }
            }

            progress.Value = 100;

            CustomMessageBox.Show("Please eject the microsd card, place into the px4, hold down the ioboard safety button, power on,\nand wait 60 seconds for the automated upgrade to take place.\nA upgrade status is created on your microsd card.");
        }
Esempio n. 25
0
        public static string GetTenantId()
        {
            string requesrUrl = $"{string.Format("https://{0}", ClientConst.Sharepoint)}";
            var myWebRequest = WebRequest.Create(requesrUrl);
            myWebRequest.Method = "GET";
            myWebRequest.Headers.Add("Authorization", "Bearer");

            var tenantID = "";
            var resourceID = "";
            WebResponse myWebResponse = null;
            try
            {
                myWebResponse = myWebRequest.GetResponse();
                return myWebResponse.ToString();
            }
            catch (WebException ex)
            {
                //Console.Write(ex.Message);
                //get the Web exception and read the headers

                string[] headerAuthenticateValue = ex.Response.Headers.GetValues("WWW-Authenticate");
                if (headerAuthenticateValue != null)
                {
                    //get the array separated by comma
                    //Console.WriteLine(" Value => " + headerAuthenticateValue.Length);

                    foreach (string stHeader in headerAuthenticateValue)
                    {
                        string[] stArrHeaders = stHeader.Split(',');
                        //loop all the key value pair of WWW-Authenticate

                        foreach (string stValues in stArrHeaders)
                        {
                            // Console.WriteLine(" Value =>" + stValues);
                            if (stValues.StartsWith("Bearer realm="))
                            {
                                tenantID = stValues.Substring(14);
                                tenantID = tenantID.Substring(0, tenantID.Length - 1);
                            }

                            if (stValues.StartsWith("client_id="))
                            {
                                //this value is consider as resourceid which is required for getting the access token
                                resourceID = stValues.Substring(11);
                                resourceID = resourceID.Substring(0, resourceID.Length - 1);
                            }
                        }
                    }
                }

                Console.WriteLine("TenantId: " + tenantID);
                Console.WriteLine("ResourceID: " + resourceID);


                var accessTokenUrl = string.Format(SharepointUrlConst.AccessToken, tenantID);
                myWebRequest = WebRequest.Create(accessTokenUrl);
                myWebRequest.ContentType = "application/x-www-form-urlencoded";
                myWebRequest.Method = "POST";


                // Add the below body attributes to the request
                /*
                 *  grant_type  client_credentials  client_credentials
                 client_id  ClientID@TenantID 
                 client_secret  ClientSecret 
                 resource  resource/SiteDomain@TenantID  resourceid/abc.sharepoint.com@tenantID
                 */


                var postData = "grant_type=client_credentials";
                postData += "&client_id=" + ClientConst.ClientId + "@" + tenantID;
                postData += "&client_secret=" + ClientConst.ClientSecret;
                postData += "&resource=" + resourceID + "/" + ClientConst.Authority + "@" + tenantID;
                var data = Encoding.ASCII.GetBytes(postData);

                using (var stream = myWebRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                var response = (HttpWebResponse)myWebRequest.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                string[] stArrResponse = responseString.Split(',');

                //get the access token and expiry time ,etc

                var accessToken = "";
                foreach (var stValues in stArrResponse)
                {

                    if (stValues.StartsWith("\"access_token\":"))
                    {
                        //Console.WriteLine(" Result => " + stValues);
                        accessToken = stValues.Substring(16);
                        //Console.WriteLine(" Result => " + accessToken);
                        accessToken = accessToken.Substring(0, accessToken.Length - 2);
                        // Console.WriteLine(" Result => " + accessToken);
                    }
                }

                return accessToken;

            }
        }
Esempio n. 26
0
        private void TimerStartPost_Tick(object sender, EventArgs e)
        {
            //公共方法
            DataTable dataTable = myDataTable.StoreDataTable;

            foreach (DataRow dataRow in dataTable.Rows)
            {
                //取得ID
                int topicID = int.Parse(dataRow["TopicID"].ToString());
                ////查找最大楼层数
                LogInfo("正在处理文章ID:" + topicID);

                string postUrl = string.Format(
                    "http://bbs.meizu.com/post.php?action=reply&fid=22&tid={0}&extra=page=1", topicID);
                string pageSource = GetPageSource(cc, postUrl);

                ////查找最大楼层数 已修改存至datatable中
                //var regexMaxFloor =
                //    new Regex("&rsaquo;&rsaquo;</a></div> -->\\s*<div class=\"pages\"><em>&nbsp;(?<maxfloor>\\d+)&nbsp;");
                //string pageIndexSource = GetPageSource(cc,
                //                                       string.Format("http://bbs.meizu.com/thread-{0}-1-1.html", topicID));
                //Match matchMaxPage = regexMaxFloor.Match(pageIndexSource);
                //int currentFloor = 0;
                //if (matchMaxPage.Success)
                //{
                //    currentFloor = int.Parse(matchMaxPage.Groups["maxfloor"].Value);
                //}

                //直接从datatable中获取
                int currentFloor = int.Parse(dataRow["CurrentFloor"].ToString());
                LogInfo("文章当前到了:" + currentFloor + "楼");
                //获取中奖楼层的数组
                foreach (string floor in dataRow["HitFloorIDs"].ToString().Split(','))
                {
                    //在之前3个贴子时开始猛发
                    if (currentFloor < int.Parse(floor) + 1 && currentFloor > int.Parse(floor) - 3)
                    {
                        for (int i = 0; i < int.Parse(floor) - currentFloor; i++)
                        {
                            try
                            {
                                //获取FormHash
                                //fromHash,cookieTime,loginField
                                //正则查找页面参数
                                //查找<input type="hidden" name="formhash" value="2f0a3b07" />
                                //Regex regex = new Regex("<input\\s+type=\"hidden\"\\s+name=\"formhash\"\\s+value=\"(?<formhash>.*?)\"\\s*/>.*?<input\\s+type=\"hidden\"\\s+name=\"cookietime\"\\s+value=\"(?<cookietime>.*?)\"\\s*/>.*?<input\\s+type=\"hidden\"\\s+value=\"(?<loginfield>.*?)\"\\s+name=\"loginfield\"\\s*/>", RegexOptions.Singleline);
                                var regex =
                                    new Regex(
                                        "<input\\s+type=\"hidden\"\\s+name=\"formhash\"\\s+id=\"formhash\"\\s+value=\"(?<formhash>.*?)\"\\s*/>",
                                        RegexOptions.Singleline);
                                Match  match    = regex.Match(pageSource);
                                string formhash = string.Empty;
                                if (match.Success)
                                {
                                    GroupCollection group = match.Groups;
                                    formhash = group["formhash"].Value;
                                }
                                LogInfo("查找到了formhash为:" + formhash);
                                var uri2 =
                                    new Uri(
                                        string.Format(
                                            "http://bbs.meizu.com/post.php?action=reply&fid=22&tid={0}&extra=page=1&replysubmit=yes",
                                            topicID));
                                byte[] byteRequest =
                                    Encoding.Default.GetBytes("subject=&formhash=" + formhash + "&message=" +
                                                              GetRandomMessage());                    //编码
                                var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri2);
                                httpWebRequest.ContentType     = "application/x-www-form-urlencoded"; //这一个参数似乎是必需的。
                                httpWebRequest.Method          = "Post";                              //这个是请求方法,必须是POST,这个可以通过分析实际登录的情况得到采用的方法
                                httpWebRequest.ContentLength   = byteRequest.Length;                  //POST数据的长度,这个参数是必需的。
                                httpWebRequest.CookieContainer = cc;
                                //下面是发送数据到服务器
                                Stream stream = httpWebRequest.GetRequestStream();
                                stream.Write(byteRequest, 0, byteRequest.Length);
                                stream.Close();
                                var webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); //取服务器的响应
                                //Stream sr = webResponse.GetResponseStream();
                                LogInfo("向文章成功发送了一个回复,我觉得应该在:" + (currentFloor + i + 1) + "楼");
                                if ((currentFloor + i + 1) == int.Parse(floor))
                                {
                                    LogInfo("中奖了...........................................");
                                }
                                //Thread.Sleep(20000);
                            }
                            catch
                            {
                                throw;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            strFilePath = strImgURL.Substring(strImgURL.IndexOf("image.php?id=") + 13);

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            var CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                this.EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    this.EventTable.Add(strImgURL, CCObj);
                }
            }

            var strNewURL = "http://www.picbux.com/image/"
                            + strImgURL.Substring(strImgURL.IndexOf("image.php?id=") + 13);

            //////////////////////////////////////////////////////////////////////////
            HttpWebRequest  lHttpWebRequest;
            HttpWebResponse lHttpWebResponse;
            Stream          lHttpWebResponseStream;

            try
            {
                lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL);

                lHttpWebRequest.UserAgent =
                    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6";
                lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
                lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
                lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                lHttpWebRequest.Referer   = strImgURL;
                lHttpWebRequest.Accept    = "image/png,*/*;q=0.5";
                lHttpWebRequest.KeepAlive = true;

                lHttpWebResponse       = (HttpWebResponse)lHttpWebRequest.GetResponse();
                lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream();

                if (lHttpWebResponse.ContentType.IndexOf("image") < 0)
                {
                    // if (lFileStream != null)
                    //  lFileStream.Close();
                    return(false);
                }

                if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg")
                {
                    strFilePath += ".jpg";
                }
                else if (lHttpWebResponse.ContentType.ToLower() == "image/gif")
                {
                    strFilePath += ".gif";
                }
                else if (lHttpWebResponse.ContentType.ToLower() == "image/png")
                {
                    strFilePath += ".png";
                }

                var NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
                }

                // lFileStream = new FileStream(strFilePath, FileMode.Create);
                lHttpWebResponseStream.Close();

                var client = new WebClient();
                client.Headers.Add("Accept-Language: en-us,en;q=0.5");
                client.Headers.Add("Accept-Encoding: gzip,deflate");
                client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add(
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);

                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;

            // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic =
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Esempio n. 28
0
        public async Task <bool> CheckURL(ILog log, string url, bool?useProxyAPI = null)
        {
            // if validation proxy enabled, access to the domain being validated is checked via our
            // remote API rather than directly on the servers
            var useProxy = useProxyAPI ?? _enableValidationProxyAPI;

            //check http request to test path works
            try
            {
                var request = WebRequest.Create(!useProxy ? url :
                                                Models.API.Config.APIBaseURI + "configcheck/testurl?url=" + url);

                request.Timeout = 5000;

                ServicePointManager.ServerCertificateValidationCallback = (obj, cert, chain, errors) =>
                {
                    // ignore all cert errors when validating URL response
                    return(true);
                };

                log.Information($"Checking URL is accessible: {url} [proxyAPI: {useProxy}, timeout: {request.Timeout}ms]");

                var response = (HttpWebResponse)await request.GetResponseAsync();

                //if checking via proxy, examine result
                if (useProxy)
                {
                    if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300)
                    {
                        var encoding = ASCIIEncoding.UTF8;
                        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
                        {
                            var jsonText = reader.ReadToEnd();

                            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <Models.API.URLCheckResult>(jsonText);

                            if (result.IsAccessible == true)
                            {
                                log.Information("URL is accessible. Check passed.");

                                return(true);
                            }
                            else
                            {
                                log.Information($"(proxy api) URL is not accessible. Result: [{result.StatusCode}] {result.Message}");
                            }
                        }
                    }

                    //request failed using proxy api, request again using local http
                    return(await CheckURL(log, url, false));
                }
                else
                {
                    if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300)
                    {
                        log.Information($"(local check) URL is accessible. Check passed. HTTP {response.StatusCode}");

                        return(true);
                    }
                    else
                    {
                        log.Warning($"(local check) URL is not accessible. Check failed. HTTP {response.StatusCode}");

                        return(false);
                    }
                }
            }
            catch (Exception exp)
            {
                if (useProxy)
                {
                    log.Warning($"Problem checking URL is accessible : {url} {exp.Message}");

                    // failed to call proxy API (maybe offline?), let's try a local check
                    return(await CheckURL(log, url, false));
                }
                else
                {
                    // failed to check URL locally
                    log.Error(exp, $"Failed to confirm URL is accessible : {url} ");

                    return(false);
                }
            }
            finally
            {
                // reset callback for other requests to validate using default behavior
                ServicePointManager.ServerCertificateValidationCallback = null;
            }
        }
Esempio n. 29
0
        public void setXcustSUBTbl(MaterialListView lv1, Form form1, MaterialProgressBar pB1)
        {
            String uri = "", dump = "";
            //HttpWebRequest request = CreateWebRequest();
            XmlDocument soapEnvelopeXml = new XmlDocument();
            const Int32 BufferSize      = 128;

            String[] filePO;
            addListView("setXcustSUBTbl ", "Web Service", lv1, form1);
            //filePO = Cm.getFileinFolder(Cm.initC.PathZip);
            //String text = System.IO.File.ReadAllText(filePO[0]);
            //byte[] byteArraytext = Encoding.UTF8.GetBytes(text);
            //byte[] toEncodeAsBytestext = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
            //String Arraytext = System.Convert.ToBase64String(toEncodeAsBytestext);
            //< soapenv:Envelope xmlns:soapenv = "http://schemas	xmlsoap	org/soap/envelope/" xmlns: v2 = "http://xmlns	oracle	com/oxp/service/v2" >
            uri = @" <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:pub='http://xmlns.oracle.com/oxp/service/PublicReportService'>  " +
                  "<soapenv:Header/> " +
                  "<soapenv:Body> " +
                  "<v2:runReport> " +
                  "<v2:reportRequest> " +
                  "<v2:attributeLocale>en-US</v2:attributeLocale> " +
                  "<v2:attributeTemplate>XCUST_SUBINVENTORY_MST_REP</v2:attributeTemplate> " +
                  "<v2:reportAbsolutePath>/Custom/XCUST_CUSTOM/XCUST_SUBINVENTORY_MST_REP.xdo</v2:reportAbsolutePath> " +
                  "<pub:parameterNameValues> " +
                  "<pub:item> " +
                  "<pub:multiValuesAllowed>False</pub:multiValuesAllowed> " +
                  "<pub:name>p_update_from</pub:name> " +
                  "<pub:values> " +
                  "<pub:item>" + Cm.initC.p_update_from + "</pub:item> " +
                  "</pub:values>" +
                  "</pub:item>" +
                  "<pub:item>" +
                  "<pub:multiValuesAllowed>False</pub:multiValuesAllowed> " +
                  "<pub:name>p_update_to</pub:name> " +
                  "<pub:values> " +
                  "<pub:item>" + Cm.initC.p_update_to + "</pub:item> " +
                  "</pub:values> " +
                  "</pub:item> " +
                  "</pub:parameterNameValues>  " +
                  "</v2:reportRequest> " +
                  "<v2:userID>" + Cm.initC.usercloud + "</v2:userID> " +
                  "<v2:password>" + Cm.initC.passcloud + "</v2:password> " +
                  "</v2:runReport> " +
                  "</soapenv:Body> " +
                  "</soapenv:Envelope> ";

            //byte[] byteArray = Encoding.UTF8.GetBytes(envelope);
            byte[] byteArray = Encoding.UTF8.GetBytes(uri);
            addListView("setXcustSUBTbl Start", "Web Service", lv1, form1);
            // Construct the base 64 encoded string used as credentials for the service call
            byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Cm.initC.usercloud + ":" + Cm.initC.passcloud);
            string credentials     = System.Convert.ToBase64String(toEncodeAsBytes);

            // Create HttpWebRequest connection to the service
            HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("https://eglj.fa.us2.oraclecloud.com/xmlpserver/services/PublicReportService");

            // Configure the request content type to be xml, HTTP method to be POST, and set the content length
            request1.Method        = "POST";
            request1.ContentType   = "text/xml;charset=UTF-8";
            request1.ContentLength = byteArray.Length;

            // Configure the request to use basic authentication, with base64 encoded user name and password, to invoke the service.
            request1.Headers.Add("Authorization", "Basic " + credentials);

            // Set the SOAP action to be invoked; while the call works without this, the value is expected to be set based as per standards
            request1.Headers.Add("SOAPAction", "https://eglj.fa.us2.oraclecloud.com/xmlpserver/services/PublicReportService");

            // Write the xml payload to the request
            Stream dataStream = request1.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            addListView("setXcustSUBTbl Request", "Web Service", lv1, form1);
            // Get the response and process it; In this example, we simply print out the response XDocument doc;
            string    actNumber = "";
            XDocument doc;

            using (WebResponse response = request1.GetResponse())
            {
                addListView("setXcustSUBTbl Response", "Web Service", lv1, form1);
                using (Stream stream = response.GetResponseStream())
                {
                    doc = XDocument.Load(stream);
                    foreach (XNode node in doc.DescendantNodes())
                    {
                        if (node is XElement)
                        {
                            XElement element = (XElement)node;
                            if (element.Name.LocalName.Equals("reportBytes"))
                            {
                                actNumber = element.ToString().Replace(@"<ns1:reportBytes xmlns:ns1=""http://xmlns.oracle.com/oxp/service/PublicReportService"">", "");
                                actNumber = actNumber.Replace("</reportBytes>", "").Replace("</result>", "").Replace(@"""", "").Replace("<>", "");
                                actNumber = actNumber.Replace("<reportBytes>", "").Replace("</ns1:reportBytes>", "");
                            }
                        }
                    }
                }
            }
            actNumber = actNumber.Trim();
            actNumber = actNumber.IndexOf("<reportContentType>") >= 0 ? actNumber.Substring(0, actNumber.IndexOf("<reportContentType>")) : actNumber;
            addListView("setXcustSUBTbl Extract html", "Web Service", lv1, form1);
            byte[] data          = Convert.FromBase64String(actNumber);
            string decodedString = Encoding.UTF8.GetString(data);

            //XElement html = XElement.Parse(decodedString);
            //string[] values = html.Descendants("table").Select(td => td.Value).ToArray();

            //int row = -1;
            //var doc1 = new HtmlAgilityPack.HtmlDocument();
            //doc1.LoadHtml(html.ToString());
            //var nodesTable = doc1.DocumentNode.Descendants("tr");
            String[] data1 = decodedString.Split('\n');
            //foreach (var nodeTr in nodesTable)
            for (int row = 0; row < data1.Length; row++)
            {
                if (row == 0)
                {
                    continue;
                }
                if (data1[row].Length <= 0)
                {
                    continue;
                }

                string tmp = data1[row].Replace(System.Environment.NewLine, "");

                //String[] data2 = data1[row].Split(',');
                String[] data2 = tmp.Split(',');

                XcustSubInvMstTbl subinv = new XcustSubInvMstTbl();
                subinv.ORGANIZATION_ID          = data2[0].Trim().ToString();
                subinv.SUBINVENTORY_ID          = data2[1].Trim().ToString();
                subinv.LAST_UPDATE_DATE         = data2[2].Trim().Replace("\"", "");
                subinv.CREATION_DATE            = data2[3].Trim().Replace("\"", "");
                subinv.DESCRIPTION              = data2[4].ToString().Replace("\"", "");
                subinv.LOCATOR_TYPE             = data2[5].Trim().Replace("\"", "");
                subinv.SECONDARY_INVENTORY_NAME = data2[6].Trim().Replace("\"", "");
                subinv.attribute1 = data2[7].Trim().Replace("\"", "");
                subinv.attribute2 = data2[8].Trim().Replace("\"", "");
                subinv.attribute3 = data2[9].Trim().Replace("\"", "");
                //subinv.CODE_COMBINATION_ID = "";// data2[9].Trim().Replace("\"", "");
                //MessageBox.Show("111"+item.CREATION_DATE);
                xCISubDB.insertxCSubInvMst(subinv);
            }
            Console.WriteLine(decodedString);
        }
Esempio n. 30
0
        private static string GetFile(DownloaderParams info)
        {
            string writePath = info.FullLocalPath;

            if (!IsValidPath(writePath))
            {
                Debug.Fail("Generated invalid paths.");
                return null;
            }

            string directory = Path.GetDirectoryName(writePath);

            //if (WriteAccess(writePath))
            //{
            //    Debug.WriteLine("I have write access");
            //}
            //else
            //{
            //    Debug.WriteLine("I don't have write access");
            //}

            if (!FileSystem.DirectoryExists(directory))
            {
                FileSystem.CreateDirectory(directory);
            }
            //check for existence of local file
            bool localFileExists = FileSystem.FileExists(writePath);
            if (localFileExists)
            {
                return writePath;
            }
            var webRequest = new WebRequest();
            IHttpWebResponse response;
            IHttpWebRequest request = webRequest.Create(new Uri(info.RemoteUrl));
            try
            {
                response = request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as System.Net.HttpWebResponse == null
                               ? null
                               : new HttpWebResponse(ex.Response as System.Net.HttpWebResponse);
            }
            if (response == null)
            {
                return null;
            }
            if (response.StatusCode == HttpStatusCode.OK)
            {
                ReadResponseToFileStream(writePath, response);

                return writePath;
            }
            return null;
        }
Esempio n. 31
0
        static string GetMsgById(string argtoken, string argId, string argEmailFrom, string argPath)
        {
            string sret = string.Empty;

            StringBuilder sbXML2 = new StringBuilder();

            sbXML2.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sbXML2.Append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">");
            sbXML2.Append("<soap:Header>");
            sbXML2.Append("<context xmlns=\"urn:zimbra\">");
            sbXML2.Append("<format type=\"xml\"/>");
            sbXML2.Append(string.Format("<authToken>{0}</authToken>", argtoken));
            sbXML2.Append("</context>");
            sbXML2.Append("</soap:Header>");
            sbXML2.Append("<soap:Body>");
            sbXML2.Append("<GetMsgRequest ");
            sbXML2.Append(string.Format(" xmlns=\"urn:zimbraMail\">"));
            sbXML2.Append(string.Format("<m id=\"{0}\" />", argId));
            sbXML2.Append("</GetMsgRequest>");
            sbXML2.Append("</soap:Body>");
            sbXML2.Append("</soap:Envelope>");
            Console.WriteLine(sbXML2);

            HttpWebRequest httpZimbraRequest2 = (HttpWebRequest)WebRequest.Create("https://accounts.mail.go.th/service/soap");

            httpZimbraRequest2.ContentType = "application/soapxml";

            byte[] byteArray2 = Encoding.UTF8.GetBytes(sbXML2.ToString());

            httpZimbraRequest2.Method        = "POST";
            httpZimbraRequest2.ContentLength = byteArray2.Length;

            using (var stream = httpZimbraRequest2.GetRequestStream())
            {
                stream.Write(byteArray2, 0, byteArray2.Length);
            }
            var response2 = (HttpWebResponse)httpZimbraRequest2.GetResponse();

            var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();

            Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<< Response part >>>>>>>>>>>>>>>>>>");
            Console.WriteLine(responseString2);

            XmlDocument responseDoc = new XmlDocument();

            responseDoc.LoadXml(responseString2);
            XmlNodeList docs     = responseDoc.GetElementsByTagName("content");
            string      scontent = string.Empty;

            if (docs[0].InnerText.Length > 0)
            {
                scontent = docs[0].InnerText;
            }
            Console.WriteLine("content ={0}", scontent);

            Console.WriteLine("Catch by Pattern below.........");
            string          sPattern         = "<mp cd=\"attachment\"(.*?)/>";
            MatchCollection mtResults        = Regex.Matches(responseString2, sPattern);
            bool            bHaveNewItem     = false;
            string          sMailBody        = string.Empty;
            int             iCount           = 0;
            StreamWriter    writerLinkResult = new StreamWriter(string.Format(@"{0}\{1}id{2}_link.html", argPath, argEmailFrom, argId), true);

            writerLinkResult.AutoFlush = true;
            StreamWriter writerContent = new StreamWriter(string.Format(@"{0}\{1}id{2}_content.html", argPath, argEmailFrom, argId), true);

            writerContent.AutoFlush = true;

            writerContent.WriteLine(scontent);
            writerLinkResult.WriteLine("Image links for this {0} email", argEmailFrom);
            writerLinkResult.WriteLine("</br></br>");
            foreach (Match m in mtResults)
            {
                iCount += 1;
                string sValue = m.Value;
                Console.WriteLine(sValue);

                string sFilename = sValue.Substring(sValue.IndexOf("filename=\"") + 10, (sValue.IndexOf("s=\"") - sValue.IndexOf("filename=\"")) - 12);
                string sPart     = sValue.Substring(sValue.IndexOf("part=\"") + 6, (sValue.IndexOf("\"/>") - sValue.IndexOf("part=\"")) - 6);
                Console.WriteLine("filename ={0}", sFilename);
                Console.WriteLine("Part ={0}", sPart);
                string simglink = string.Format(@"https://accounts.mail.go.th/service/home/~/?auth=co&loc=th&id={0}&part={1}", argId, sPart);
                downloadImage(simglink + "&disp=a", sFilename, argPath, argtoken);
                string sHref = string.Format("{0}.) ", iCount) + string.Format("<a href=\"{0}\">{1}</a>", simglink, sFilename) + Environment.NewLine + "</br>" + string.Format("\r\n");
                writerLinkResult.WriteLine(sHref);
            }

            writerLinkResult.Close();
            writerContent.Close();
            return(sret);
        }