Exemplo n.º 1
0
 public void updateStreamList( )
 {
     CookieAwareWebClient cwc = new CookieAwareWebClient();
     System.IO.Stream stream = cwc.downloadURL(channelsUrl);
     if (stream != null)
         channelList = ParseJson<Channels>.ReadObject(stream);
 }
Exemplo n.º 2
0
        public void updateChat(UInt32 id)
        {
            CookieAwareWebClient cwc = new CookieAwareWebClient();
            System.IO.Stream stream = cwc.downloadURL(String.Format(messagesUrl, id));

            if (stream != null)
                chat = ParseJson<ChatMessages>.ReadObject(stream);
        }
Exemplo n.º 3
0
        public void SetImage(string img_url)
        {
            CookieAwareWebClient wc = new CookieAwareWebClient();
            wc.m_container = cc;
            Image i = Utils.GetImageFromBytes(Comm.DecompressBytes(wc.DownloadData(img_url)));

            Utils.FitImageNicely(ref this.picCAPTCHA, i);
        }
Exemplo n.º 4
0
        //do ponownego merga
        public static void test01()
        {
            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type: application/x-www-form-urlencoded");
            wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
            wc.Headers.Add("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            wc.Headers.Add("Accept-Encoding: identity");
            wc.Headers.Add("Accept-Language: en-US,en;q=0.8");
            wc.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");

            // http://napisy24.pl/search.php?str=piotr+dudzik+%B1%EA%E6+%F3%BF%BC%BFd%F3%F3%F3pa
            // piotr dudzik ąęć óżźżdóóópa
            // Console.WriteLine("EscapeDataReplace: " + Uri.EscapeDataString(testString).Replace("%20", "+"));

            string title = "Hobbit";
            string encodedTitle = Uri.EscapeDataString(title).Replace("%20", "+");
            string napisyURL = "http://napisy24.pl/search.php?str=";
            string requestURL = string.Format("{0}{1}", napisyURL, encodedTitle);
            //string response = wc.DownloadString(requestURL);

            // http://napisy24.pl/logowanie/
            // form_logowanieMail=waaaggh&form_logowanieHaslo=d00pad00pa&form_loginZapamietaj=1&postAction=sendLogowanie
            string loginData = @"form_logowanieMail=waaaggh&form_logowanieHaslo=d00pad00pa&form_loginZapamietaj=1&postAction=sendLogowanie";
            string cookie = string.Empty;

            //cookie = wc.ResponseHeaders["Set-Cookie"].ToString();
            //wc.UploadString("http://napisy24.pl/logowanie/", "POST", loginData);
            //wc.Headers.Add("Cookie", cookie);
            //string r1= wc.UploadString("http://napisy24.pl/logowanie/", "POST", loginData);
            //string DocumentText = wc.DownloadString("http://napisy24.pl/download/67682/");

            // The.Hobbit.2012.DVDScr.XVID.AC3.HQ.Hive-CM8.avi

            // Znaleziono 0 filmów dla "wpisz nazwę filmu basfasfdfądź napisów jakich szukasz "
            // Nie znaleziono wyników

            // Znaleziono 2 filmów dla "hobbit "
            // The Hobbit: An Unexpected Journey
            // Hobbit: Niezwykła podróż, Hobbit: Nieoczekiwana podróż
            // DVDRip.XviD-RISES
            // 06-04-2013

            // http://napisy24.pl/download/67682/

            CookieAwareWebClient wcc = new CookieAwareWebClient();
            wcc.Headers.Add("Content-Type: application/x-www-form-urlencoded");
            wcc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
            wcc.Headers.Add("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            wcc.Headers.Add("Accept-Encoding: identity");
            wcc.Headers.Add("Accept-Language: en-US,en;q=0.8");
            wcc.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
            //string swcc1 = wcc.DownloadString("http://napisy24.pl/logowanie/");
            string swcc2 = wcc.UploadString("http://napisy24.pl/logowanie/", "POST", loginData);
            cookie = wcc.ResponseHeaders["Set-Cookie"].ToString();
            wcc.Headers.Add("Cookie", cookie);
            wcc.DownloadFile("http://napisy24.pl/download/67682/", @"C:\aaa.zip");
            string swcc3 = wcc.DownloadString("http://napisy24.pl/download/67682/");
        }
Exemplo n.º 5
0
        public static async Task<string> LoadAsyncTo(string argument, string destination, IProgress<AsyncProgressEntry> progress = null,
                CancellationToken cancellation = default(CancellationToken)) {
            var loader = CreateLoader(argument);

            try {
                // TODO: Timeout?
                using (var client = new CookieAwareWebClient {
                    Headers = {
                        [HttpRequestHeader.UserAgent] = CmApiProvider.UserAgent
                    }
                }) {
                    progress?.Report(AsyncProgressEntry.Indetermitate);

                    cancellation.ThrowIfCancellationRequested();
                    cancellation.Register(client.CancelAsync);

                    if (!await loader.PrepareAsync(client, cancellation) ||
                            cancellation.IsCancellationRequested) return null;

                    var skipEvent = 0;
                    client.DownloadProgressChanged += (sender, args) => {
                        if (++skipEvent > 50) {
                            skipEvent = 0;
                        } else {
                            return;
                        }

                        var total = args.TotalBytesToReceive;
                        if (total == -1 && loader.TotalSize != -1) {
                            total = Math.Max(loader.TotalSize, args.BytesReceived);
                        }

                        // ReSharper disable once AccessToDisposedClosure
                        progress?.Report(AsyncProgressEntry.CreateDownloading(args.BytesReceived, total));
                    };

                    await loader.DownloadAsync(client, destination, cancellation);
                    if (cancellation.IsCancellationRequested) return null;

                    Logging.Debug("Loaded: " + destination);
                }

                return destination;
            } catch (TaskCanceledException) {
                return null;
            } catch (Exception e) {
                NonfatalError.Notify(ToolsStrings.Common_CannotDownloadFile, ToolsStrings.Common_CannotDownloadFile_Commentary, e);
                return null;
            }
        }
Exemplo n.º 6
0
 private void establishWebMeTLConnection(Credentials cred)
 {
     try
     {
         //setupChrome();
         if (client != null)
             client = null;
         client = setupCAS(cred);
         hideStack();
         if (!String.IsNullOrEmpty(Globals.conversationDetails.Jid))
            JoinConversation(Globals.conversationDetails.Jid); 
     }
     catch (Exception ex)
     {
         App.Now("failed to setup WebMeTL connection with exception: " + ex.Message);
         showRetryWindow();
     }
 }
Exemplo n.º 7
0
        public void updateSmiles()
        {
            CookieAwareWebClient cwc = new CookieAwareWebClient();
            System.IO.Stream stream = cwc.downloadURL(smilesJSUrl);
            System.IO.StreamReader reader = new System.IO.StreamReader(stream);
            if (stream != null)
            {
                List<object> list = JSEvaluator.EvalArrayObject(reader.ReadToEnd());
                smiles.Clear();
                foreach (object obj in list)
                {
                    Smile smile = new Smile();
                    smile.Code = JSEvaluator.ReadPropertyValue(obj, "code");
                    smile.Image = JSEvaluator.ReadPropertyValue(obj, "img");
                    smile.Width = int.Parse(JSEvaluator.ReadPropertyValue(obj, "width"));
                    smile.Height = int.Parse(JSEvaluator.ReadPropertyValue(obj, "height"));
                    smile.bmp = new Bitmap(cwc.downloadURL(String.Format(smilesImagesUrl, smile.Image)));
                    smiles.Add(smile);
                }
            }

        }
Exemplo n.º 8
0
        private void UploadThread(object param)
        {
            var parms = (object[]) param;
            var error = (ErrorReturn) parms[3];

            error.Code = ErrorCodes.Succeeded;
            error.Exception = null;
            error.ReportedError = null;

            try
            {
                CookieAwareWebClient client = new CookieAwareWebClient();
                var text = client.DownloadString("http://minecraft.net/login");

                Match match = Regex.Match(text, @"<input type=""hidden"" name=""authenticityToken"" value=""(.*?)"">");
                string authToken = null;
                if (match.Success)
                    authToken = match.Groups[1].Value;

                if (authToken == null)
                    return;

                var data = new NameValueCollection();
                data.Add("authenticityToken", authToken);
                data.Add("username", (string)parms[0]);
                data.Add("password", (string)parms[1]);
                data.Add("redirect", "/profile");

                var returnData = Encoding.UTF8.GetString(client.UploadValues("https://minecraft.net/login", data));

                match = Regex.Match(returnData, @"<p class=""error"">([\w\W]*?)</p>");

                if (match.Success)
                {
                    error.ReportedError = match.Groups[1].Value.Trim();
                    error.Code = ErrorCodes.WrongCredentials;
                }
                else
                {
                    var dict = new Dictionary<string, string>();
                    dict.Add("authenticityToken", authToken);
                    if ((error.Exception = client.UploadFileEx("http://minecraft.net/profile/skin", parms[2].ToString(), "skin", "image/png", dict)) != null)
                        error.Code = ErrorCodes.Unknown;
                }
            }
            catch (Exception ex)
            {
                error.Exception = ex;
            }
            finally
            {
                Invoke(delegate { _pleaseWaitForm.Close(); });
            }
        }
Exemplo n.º 9
0
        public override bool Login()
        {
            CookieContainer cookieJar = new CookieContainer();
            _client = new CookieAwareWebClient(cookieJar);
            _client.Referer = HOME_URL;

            // the website sets some cookie that is needed for login
            string response = _client.DownloadString(HOME_URL);

            Cookie tokenCookie = cookieJar.List().FirstOrDefault(c => c.Name == "csrftoken");

            StringBuilder postData = new StringBuilder();
            postData.Append("email=" + HttpUtility.UrlEncode(Username) + "&");
            postData.Append("password="******"&");
            postData.Append("remember=False=");

            // the csrf token is sent in the hader
            _client.Headers.Add("User-Agent", USER_AGENT);
            _client.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
            _client.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            _client.Headers.Add("Referer", HOME_URL);
            _client.Headers.Add("X-Requested-With", "XMLHttpRequest");
            _client.Headers.Add("X-CSRFToken", tokenCookie.Value);

            response = _client.UploadString(LOGIN_API, postData.ToString());
            JObject jObject = JObject.Parse(response);
            JToken jToken = jObject.GetValue("success");
            if (!jToken.Value<bool>())
            {
                //The query returned false, either not authenticated or forbiddent (403)
                Console.WriteLine("Wrong email or password logging into Edx.");
                return false;
            }

            //Now get the goods (cookies should be set!)

            return true;
        }
Exemplo n.º 10
0
 /// <summary>
 /// Set CookieAwareWebClient Credential by configuration
 /// </summary>        
 private static CookieAwareWebClient setCredential(CookieAwareWebClient client,string url)
 {
     if (Factory.Instance.i.Project.ScrapingSetting.credential != null)
     {
         if (Factory.Instance.i.Project.ScrapingSetting.credential.useNetworkCredential)
         {
             var credCache = new CredentialCache();
             if (!string.IsNullOrEmpty(Factory.Instance.i.Project.ScrapingSetting.credential.username) && !string.IsNullOrEmpty(Factory.Instance.i.Project.ScrapingSetting.credential.password) && !string.IsNullOrEmpty(Factory.Instance.i.Project.ScrapingSetting.credential.domain))
             {
                 credCache.Add(new Uri(url), "Negotiate", new NetworkCredential(Factory.Instance.i.Project.ScrapingSetting.credential.username, Factory.Instance.i.Project.ScrapingSetting.credential.password, Factory.Instance.i.Project.ScrapingSetting.credential.domain));
                 client.Credentials = credCache;
             }
             if (!string.IsNullOrEmpty(Factory.Instance.i.Project.ScrapingSetting.credential.username) &&
                 !string.IsNullOrEmpty(Factory.Instance.i.Project.ScrapingSetting.credential.password) &&
                 string.IsNullOrEmpty(Factory.Instance.i.Project.ScrapingSetting.credential.domain))
             {
                 credCache.Add(new Uri(url), "Negotiate", new NetworkCredential(Factory.Instance.i.Project.ScrapingSetting.credential.username, Factory.Instance.i.Project.ScrapingSetting.credential.password));
                 client.Credentials = credCache;
             }
         }
     }
     return client;
 }
Exemplo n.º 11
0
        internal string UploadFileToVF(string zipFile, string swiftFilename, UploadPercent callback)
        {
            Login();
            string fileUploadInfo = SendGetRequest(ServerUrl + "/testbench/client_upload_url?filename=" + HttpUtility.UrlEncode(swiftFilename));
            if (fileUploadInfo == null)
            {
                // job creation failed
                //job.Status = Job.StatusEnum.Failed;
                return null;
            }
            int maxProgress = 0;
            object maxProgressLock = new object();
            dynamic fileUploadInfoJson = Newtonsoft.Json.Linq.JObject.Parse(fileUploadInfo);
            string fileUploadUrl = fileUploadInfoJson["url"].Value;
            try
            {
                try
                {
                    using (CookieAwareWebClient webClient = new CookieAwareWebClient())
                    {
                        webClient.cookies = this.AuthCookies;
                        webClient.Timeout = HTTP_WEB_TIMEOUT_BASE;
                        Semaphore progress = new Semaphore(0, int.MaxValue);
                        Semaphore completed = new Semaphore(0, 1);
                        UploadFileCompletedEventArgs completedData = null;
                        webClient.UploadFileCompleted += delegate(object sender, UploadFileCompletedEventArgs e)
                        {
                            completedData = e;
                            completed.Release();
                        };
                        webClient.UploadProgressChanged += delegate(object sender, UploadProgressChangedEventArgs e)
                        {
                            lock (maxProgressLock)
                            {
                                int percentProgress = (int)(((double)e.BytesSent / e.TotalBytesToSend) * 99.0);
                                if (percentProgress > maxProgress)
                                {
                                    // e.ProgressPercentage is not correct, as (almost) all the time is spent uploading
                                    maxProgress = percentProgress;
                                    callback(maxProgress);
                                }
                            }
                            progress.Release();
                        };
                        webClient.UploadFileAsync(new Uri(fileUploadUrl), "PUT", zipFile);
                        while (true)
                        {
                            WaitHandle[] handles = new WaitHandle[] { completed, progress };
                            int timeout = HTTP_WEB_TIMEOUT_BASE;
                            lock (maxProgressLock)
                            {
                                // Workaround for Fiddler proxy: Fiddler accepts all the data at once, then uploads to VF
                                if (maxProgress > 98)
                                {
                                    handles = new WaitHandle[] { completed };
                                    timeout = HTTP_WEB_REQUEST_TIMEOUT;
                                }
                            }
                            int handle = WaitHandle.WaitAny(handles, timeout);
                            if (handle == 0)
                            {
                                lock (maxProgressLock)
                                {
                                    maxProgress = 100;
                                    callback(maxProgress);
                                }
                                break;
                            }
                            if (handle == System.Threading.WaitHandle.WaitTimeout)
                            {
                                webClient.CancelAsync();
                                throw new WebException("Connection timed out");
                            }
                            if (handle != 1)
                                throw new Exception();
                        }

                        Trace.TraceInformation("Upload to S3 " + Encoding.UTF8.GetString(completedData.Result));
                        return fileUploadUrl;
                    }
                }
                catch (System.Reflection.TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }

            }
            catch (WebException ex)
            {
                Trace.TraceError("Error uploading to {0}. Exception follows", fileUploadUrl);
                Trace.TraceError(ex.ToString());
            }
            return null;
        }
Exemplo n.º 12
0
 public SC2TVChat()
 {
     wc = new CookieAwareWebClient();
     wc.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";
 }
Exemplo n.º 13
0
        private bool Login(String username, String password)
        {
            client = new CookieAwareWebClient();
            client.BaseAddress = @"http://www.pixiv.net/";
            NameValueCollection loginData = new NameValueCollection();
            loginData.Add("mode", "login");
            loginData.Add("pixiv_id", username);
            loginData.Add("pass", password);
            loginData.Add("skip", "1");
            client.UploadValues("https://www.secure.pixiv.net/login.php", "POST", loginData);
 
            string htmlSource = client.DownloadString("mypage.php");
            Console.WriteLine(client.DownloadString("mypage.php").Contains("pixiv.user.loggedIn = true"));
            return client.DownloadString("mypage.php").Contains("pixiv.user.loggedIn = true");
        }
Exemplo n.º 14
0
 public void SaveLastConsole(
     string name,
     string path)
 {
     Login();
     // http://129.59.105.75:8080/job/[jobName]/lastBuild/consoleText
     if (JobExists(name))
     {
         try
         {
             // TODO: HEAD it and set Timeout appropriately
             using (CookieAwareWebClient webClient = new CookieAwareWebClient())
             {
                 webClient.cookies = AuthCookies;
                 webClient.DownloadFile(ServerUrl + String.Format(Queries.LAST_BUILD_CONSOLE_TEXT, HttpUtility.UrlEncode(name)), path);
             }
         }
         catch (WebException ex)
         {
             Console.WriteLine(ex.ToString());
         }
     }
 }
Exemplo n.º 15
0
        public void RaiseCallbackEvent(string arg)
        {
            Result = null;
            try {
                string cmd, par = string.Empty;
                int i = arg.IndexOf(':');
                if (i == -1) cmd = arg;
                else {
                    cmd = arg.Substring(0, i);
                    par = arg.Substring(i + 1);
                }

                switch (cmd) {
                case "load":
                    Html.DocumentNode html;

                    var preview = PreviewElement; // if Preview element exists load preview else HtmlElement.Children.
                    if (preview != null) html = preview.Children;
                    else html = Element.Children;
                    EditorConverter.Export(html);
                    Services.JavaScriptTextEditor.Converter.Export(html, out Result);
                    break;
                case "save":
                    var oldText = Element.Children.Text; // save old text

                    preview = CreatePreviewElement();
                    Services.JavaScriptTextEditor.Converter.Import(preview.Children, par);
                    EditorConverter.Import(preview.Children);
                    // TODO preview.Children.AddIdentation(preview.ChildIdentation);
                    CheckParseErrors();
                    Element.Preview();

                    // page is now saved, now get the new html via a WebClient request to the saved page.
                    try {
                        var web = new CookieAwareWebClient(); // start a webrequest to the new preview page.
                        web.UseDefaultCredentials = true;
                        web.Encoding = Encoding.UTF8;
                        web.Headers[HttpRequestHeader.UserAgent] = Request.UserAgent;
                        //web.Headers[HttpRequestHeader.TransferEncoding] = "UTF8";
                        //web.Headers[HttpRequestHeader.ContentEncoding] = "UTF8";
                        foreach (var key in Request.Cookies.Keys.OfType<string>()) {
                            var cookie = Request.Cookies[key];
                            var wc = new Cookie(cookie.Name, cookie.Value, cookie.Path, Request.Url.Host);
                            wc.Expires = cookie.Expires;
                            web.Cookies.Add(wc);
                        }

                        Html.Element e = null;
                        var dochtml = web.DownloadString(Request.Url.AbsoluteUri); // get the new preview page's html.
                        if (dochtml != null) {

                            // parse the received html page for the Container control.
                            if (string.IsNullOrEmpty(Container.ClientID)) CreateChildControls(); // this is needed so we know the Container.ClientID, because otherwise Container get's not instantiated in CallbackEvent.
                            var doc = new Html.Document(dochtml);
                            e = doc.Find(Container.ClientID); // get our element out of the html.
                        }
                        if (e != null) {
                            Result = e.Children.Text; // return the element's html
                        } else {
                            Element.Children.Text = oldText;
                            Save();
                            throw new Exception("Invalid HTML.");
                        }

                    } catch (Exception ex) { // exception viewing the new preview page
                        Element.Children.Text = oldText; // reset text
                        Save();
                        Result = null;
                        throw ex;
                    }

                    break;
                default: throw new NotSupportedException("EditableContent: Unknown callback command.");
                }
            } catch (Exception ex) {
                Services.Log.Error("EditableContent callback exception:", ex);
                throw ex;
            }
        }
Exemplo n.º 16
0
 public OAuth2TokenResponse GetAccessTokenFromUserKey(string userKey,string state,params string[] scopes)
 {
     var request = CreateAuthorizeRequest(userKey, state, scopes);
     CookieAwareWebClient client = new CookieAwareWebClient(this);
     var result = client.DownloadString(request);
     var callback = new Uri(client.LastPage);
     string stateInResponse = string.Empty;
     var code = HandleAuthorizeCallback(callback, out stateInResponse);
     System.Diagnostics.Debug.Assert(stateInResponse == state);
     return base.GetToken(code);
 }
        private string postRequest(string url, NameValueCollection post = null, string referral = "")
        {
            //initialize client
            CookieAwareWebClient webClient = new CookieAwareWebClient(cookies);

            //Set webclient referrer
            if (referral != "")
                webClient.Headers["Referer"] = referral;

            //issue the request
            byte[] responseBytes = webClient.UploadValues(url, "POST", post);
            string result = Encoding.UTF8.GetString(responseBytes);

            //clear buffers and return result
            webClient.Dispose();
            return result;
        }
Exemplo n.º 18
0
        /**
         * This is the lowest level request method. Use higher level if possible.
         */
        public JObject Request(string uri, string method, ClientType client, JObject parameters, JObject headerOverrides, RequestHandler handler, object state)
        {
            JObject request = new JObject();
            request.Add("parameters", parameters);
            JObject header = new JObject();
            if (m_token != null)
            {
                string t = GenerateToken(method);
                header.Add("token", t);
            }
            header.Add("session", m_sid);

            if (client == ClientType.HTML)
                header.Add("client", "htmlshark");
            else if (client == ClientType.JSQueue)
                header.Add("client", "jsqueue");
            else
                throw new Exception("ClientType not supported.");

            header.Add("clientRevision", "20101012.37");
            header.Add("privacy", 0);
            // Somehow this uuid is important, and I don't really know what it is, the UUID of the JSQueue flash object ?
            header.Add("uuid", "6BFBFCDE-B44F-4EC5-AF69-76CCC4A2DAD0");
            header.Add("country", m_countryObj);
            request.Add("header", header);
            request.Add("method", method);

            if (headerOverrides != null)
            {
                IDictionaryEnumerator e = headerOverrides.GetEnumerator();
                while (e.MoveNext())
                {
                    if (header.ContainsKey(e.Key))
                        header[e.Key] = e.Value;
                    else
                        header.Add(e.Key, e.Value);
                }
            }
            string requestStr = request.ToString().Replace("\n", "").Replace(" ", "").Replace("\r", "");
            CookieAwareWebClient wc = new CookieAwareWebClient(m_cc);
            wc.UploadStringCompleted += new UploadStringCompletedEventHandler(GSRequestHandler);
            wc.UploadStringAsync(new Uri(uri + "?" + method), "POST", requestStr, new object[]{ handler, state });
            if(RequestSent != null)
                RequestSent(this, requestStr);
            return request;
        }
Exemplo n.º 19
0
 public void ResetSession()
 {
     _client = new CookieAwareWebClient();
 }
Exemplo n.º 20
0
 //Returns a cookie aware webclient authenticated with the speciefied email and password
 public static CookieAwareWebClient GetAuthenticatedWebClient(string solderUrl, string email, string password)
 {
     string loginAddress = solderUrl + "login";
     System.Collections.Specialized.NameValueCollection loginData = new System.Collections.Specialized.NameValueCollection {{"email", email}, {"password", password}};
     CookieAwareWebClient client = new CookieAwareWebClient();
     client.UploadValues(loginAddress, loginData);
     return client;
 }
Exemplo n.º 21
0
        //TODO: разобраться с возвратом
        //Подключается к серверу, скачевает xlsx фаил, разархивируетв в xml и десереализует/
        public async Task<bool> GetDataFromServer()
        {
            //Рабочая часть, соединяемся с сервером и получаем куки
            var cookie = await GetCookiesAsync("http://bo-otchet.1gl.ru/Account/Login", _loginName, _loginPwd);


            //Получаем данные с помошью WebClient
            using (var client = new CookieAwareWebClient(cookie))
            {
                Uri newUri = new Uri("http://bo-otchet.1gl.ru/Registration/RepostRegistrationExcel?Caption=%D0%A1%20%D0%B2%D1%8B%D0%BF%D1%83%D1%89%D0%B5%D0%BD%D0%BD%D0%BE%D0%B9%20%D0%9A%D0%AD%D0%9F&ShowSearchForm=False&PageId=0&PageSize=50&SuppressFlags=0&ViewId=HaveCertificate&PartnerId=" + PartnerId);
                client.DownloadFile(newUri, $"{_partnerId}.xlsx");
                using (ZipFile zip = ZipFile.Read($"{_partnerId}.xlsx"))
                {
                    if (zip == null) Console.WriteLine("Null");
                    else
                    {
                        foreach (var zp in zip)
                        {
                            zp.Extract(ExtractExistingFileAction.OverwriteSilently);
                        }
                    }
                }
            }
            ShowMessageClass showMessage = new ShowConsoleMessage();
            try
            {
                XmlDocument _xml = new XmlDocument();
                try
                {
                    _xml.Load("xl\\worksheets\\sheet1.xml");
                }
                catch (System.IO.FileNotFoundException ex)
                {
                    showMessage.ShowMessage($"File not found!{Environment.NewLine} Error: {ex.ToString()}");
                }
                string str = _xml.OuterXml;
                str = str.Replace("<v>", "").Replace("</v>", "")
                         .Replace("<f>=TEXT", "").Replace("</f>", "");

                XmlRootAttribute xRoot = new XmlRootAttribute();
                xRoot.ElementName = "worksheet";
                xRoot.Namespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
                xRoot.IsNullable = true;
                var xml = new XmlSerializer(typeof(Worksheet), xRoot);
                Data = xml.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(str))) as Worksheet;
                return true;
            }
            catch (Exception ex)
            {
                showMessage.ShowMessage(ex.Message);
                return false;
            }
        }
Exemplo n.º 22
0
 public void onRemotingCallback(string callUID, string methodName, object result, AsyncOption option)
 {
     switch (methodName)
     {
         case "MailManager.syncUserMail":
             {
                 int is_synced_value = -1;
                 ASObject mail = option.asyncData as ASObject;
                 int is_synced = NumberUtil.parseInt(mail["is_synced"] == null ? "0" : mail["is_synced"].ToString());
                 if (is_synced == 0)
                 {
                     is_synced = 1;
                     is_synced_value = 1;
                 }
                 if (is_synced == 1)
                 {
                     //同步文件
                     string mail_file = mail["mail_file"] as string;
                     string store_path = System.IO.Path.Combine(new string[] { Desktop.instance.ApplicationPath, "mail" });
                     string mail_file_path = store_path + mail_file;
                     if (File.Exists(mail_file_path))
                     {
                         string uuid = mail["uuid"] as string;
                         Dictionary<string, string> param = new Dictionary<string, string>();
                         param["uuid"] = MailReceiveWorker.getFilePath(uuid);
                         using (var client = new CookieAwareWebClient())
                         {
                             client.Param = param;
                             string uri = Desktop.getAbsoluteUrl(upload_mail_message);
                             mail_file_path = mail_file_path.Replace("/", "\\");
                             client.UploadFileAsync(new Uri(uri), mail_file_path);
                         }
                         is_synced_value = 2;
                     }
                 }
                 if (is_synced_value != -1)
                 {
                     mail["is_synced"] = is_synced_value;
                     updateMailRecord(mail, new string[] { "is_synced" });
                 }
             }
             break;
     }
 }
Exemplo n.º 23
0
        private string OldUploadFile(string filename, string response, Uri skinUploadServerURL, NameValueCollection queryString)
        {
            CookieAwareWebClient Client = new CookieAwareWebClient();
            NetworkCredential myCred = new NetworkCredential("editor", _editorPassword);
            CredentialCache MyCrendentialCache = new CredentialCache();
            MyCrendentialCache.Add(skinUploadServerURL, "Basic", myCred);
            Client.Credentials = MyCrendentialCache;
            if (_proxy != String.Empty)
            {
                Client.Proxy = new WebProxy("http://" + _proxy + ":" + _port);
            }
            Client.Cookies = _cookieContainer;

            Client.Headers.Add(HttpRequestHeader.ContentType, "text/xml");


            Client.QueryString.Add("skinstubpath", queryString["skinstubpath"]);
            Client.QueryString.Add("skinname", queryString["skinname"]);
            Client.QueryString.Add("skin", queryString["skin"]);

            byte[] responseArray = Client.UploadFile(skinUploadServerURL, filename);

            response = System.Text.Encoding.ASCII.GetString(responseArray);
            return response;
        }
        //web requests
        private string getRequest(string url, NameValueCollection get = null, string referral = "")
        {
            //initialize client
            CookieAwareWebClient webClient = new CookieAwareWebClient(cookies);

            //generate GET uri
            string request = url;
            if (get != null)
            {
                request += "?";

                int it = 0;
                foreach (string s in get)
                {
                    foreach (string v in get.GetValues(s))
                    {
                        if (it != 0)
                            request += "&";

                        request += s + "=" + v;

                        it++;
                    }
                }
            }

            //Set webclient referrer
            if (referral != "")
                webClient.Headers["Referer"] = referral;

            //issue the request and return output
            string output = webClient.DownloadString(request);
            webClient.Dispose();

            return output;
        }
Exemplo n.º 25
0
 private CookieAwareWebClient setupCAS(Credentials cred){
     var client = new CookieAwareWebClient();
     var data = new NameValueCollection();
     data["access"] = "authcate";
     data["username"] = cred.name;
     data["password"] = cred.password;
     data["request_uri"] = "/authentication/cas/login?service=" + WEB_METL_URL;
     data["submit"] = "login";
     var casResponse = client.UploadValues(CAS_URL,data);
     var wm3Response = client.DownloadString(WEB_METL_URL);
     var cookies = client.GetCookies(new Uri(WEB_METL_URL));
     foreach(var _cookie in cookies)
     {
         var cookie = (Cookie)_cookie;
         var cookieString = String.Format("{0}={1}; domain={2}", cookie.Name, cookie.Value, cookie.Domain);
         WebCore.SetCookie(WEB_METL_URL, cookieString);
         isHealthy = true;
     }
     return client;
 }