public async Task RetrievesValueWithAlternateKeys()
        {
            const string key = nameof(RetrievesValueWithAlternateKeys);
            using (var credentialCache = new CredentialCache())
            {
                try
                {
                    var credential = Tuple.Create("somebody", "somebody's secret");
                    await credentialCache.InsertObject(key, credential);

                    var retrieved = await credentialCache.GetObject<Tuple<string, string>>(key);

                    Assert.Equal("somebody", retrieved.Item1);
                    Assert.Equal("somebody's secret", retrieved.Item2);

                    var retrieved2 = await credentialCache.GetObject<Tuple<string, string>>("git:" + key + "/");

                    Assert.Equal("somebody", retrieved2.Item1);
                    Assert.Equal("somebody's secret", retrieved2.Item2);

                    var retrieved3 = await credentialCache.GetObject<Tuple<string, string>>("login:"******"/");

                    Assert.Equal("somebody", retrieved3.Item1);
                    Assert.Equal("somebody's secret", retrieved3.Item2);
                }
                finally
                {
                    await credentialCache.Invalidate(key);
                }
            }
        }
        public async Task StoresCredentialForKeyAndGitKey()
        {
            using (var credentialCache = new CredentialCache())
            {
                try
                {
                    var credential = Tuple.Create("somebody", "somebody's secret");

                    await credentialCache.InsertObject(nameof(StoresCredentialForKeyAndGitKey), credential);

                    var retrieved = await credentialCache.GetObject<Tuple<string, string>>(nameof(StoresCredentialForKeyAndGitKey));
                    Assert.Equal("somebody", retrieved.Item1);
                    Assert.Equal("somebody's secret", retrieved.Item2);
                    var retrieved2 = await credentialCache.GetObject<Tuple<string, string>>("git:" + nameof(StoresCredentialForKeyAndGitKey));
                    Assert.Equal("somebody", retrieved2.Item1);
                    Assert.Equal("somebody's secret", retrieved2.Item2);
                }
                finally
                {
                    try
                    {
                        await credentialCache.Invalidate(nameof(StoresCredentialForKeyAndGitKey));
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
 public async Task ThrowsObservableInvalidOperationExceptionWhenRetrievingSomethingNotATuple()
 {
     using (var credentialCache = new CredentialCache())
     {
         await Assert.ThrowsAsync<InvalidOperationException>(
             async () => await credentialCache.GetObject<string>("_"));
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// Instantiates a new OneDriveClient.
 /// </summary>
 public OneDriveClient(
     AppConfig appConfig,
     CredentialCache credentialCache = null,
     IHttpProvider httpProvider = null,
     IServiceInfoProvider serviceInfoProvider = null)
     : base(appConfig, credentialCache, httpProvider, serviceInfoProvider)
 {
 }
Exemplo n.º 5
0
 private static CredentialCache GetCredential()
 {
     string url = @"http://github.com/api/v3/users";
     //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
     CredentialCache credentialCache = new CredentialCache();
     //credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["gitHubUser"], ConfigurationManager.AppSettings["gitHubUserPassword"]));
     credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential("huj", "Savit5ch"));
     return credentialCache;
 }
 /// <summary>
 /// Instantiates a new OneDriveClient.
 /// </summary>
 public OneDriveClient(
     AppConfig appConfig,
     CredentialCache credentialCache = null,
     IHttpProvider httpProvider = null,
     IServiceInfoProvider serviceInfoProvider = null,
     ClientType clientType = ClientType.Consumer)
     : base(appConfig, credentialCache, httpProvider, serviceInfoProvider, clientType)
 {
 }
 public async Task ThrowsObjectDisposedExceptionWhenDisposed()
 {
     using (var credentialCache = new CredentialCache())
     {
         credentialCache.Dispose();
         await Assert.ThrowsAsync<ObjectDisposedException>(
             async () => await credentialCache.GetObject<Tuple<string, string>>("_"));
     }
 }
Exemplo n.º 8
0
        private static CredentialCache UriAuthenticationTypeCredentialCache()
        {
            CredentialCache cc = new CredentialCache();

            cc.Add(uriPrefix1, authenticationType1, credential1);
            cc.Add(uriPrefix1, authenticationType2, credential2);

            cc.Add(uriPrefix2, authenticationType1, credential3);
            cc.Add(uriPrefix2, authenticationType2, credential4);

            return cc;
        }
Exemplo n.º 9
0
        private static CredentialCacheCount CreateUriCredentialCacheCount(CredentialCache cc = null, int count = 0)
        {
            cc = cc ?? new CredentialCache();

            cc.Add(uriPrefix1, authenticationType1, credential1); count++;
            cc.Add(uriPrefix1, authenticationType2, credential2); count++;

            cc.Add(uriPrefix2, authenticationType1, credential3); count++;
            cc.Add(uriPrefix2, authenticationType2, credential4); count++;

            return new CredentialCacheCount(cc, count);
        }
        public void TestRoundTrip()
        {
            var credentials = new CredentialCache { Logon = "user", Password = "******", AccessToken = string.Empty };
            var cache = credentials.ToString();
            Assert.That(cache, Is.Not.Null);
            Assert.That(cache, Does.Contain("user"));
            Assert.That(cache, Does.Not.Contain("password"));

            var parsed = CredentialCache.FromString(cache);
            Assert.That(parsed, Is.Not.Null);
            Assert.That(parsed.Logon, Is.EqualTo("user"));
            Assert.That(parsed.Password, Is.EqualTo("password"));
            Assert.That(parsed.AccessToken, Is.EqualTo(string.Empty));
        }
        public Task<ServiceInfo> GetServiceInfo(AppConfig appConfig, CredentialCache credentialCache, IHttpProvider httpProvider)
        {
            var microsoftAccountServiceInfo = new MicrosoftAccountServiceInfo
            {
                AppId = appConfig.MicrosoftAccountAppId,
                ClientSecret = appConfig.MicrosoftAccountClientSecret,
                CredentialCache = credentialCache,
                HttpProvider = httpProvider,
                Scopes = appConfig.MicrosoftAccountScopes,
            };

            microsoftAccountServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new OnlineIdAuthenticationProvider(microsoftAccountServiceInfo);
            return Task.FromResult<ServiceInfo>(microsoftAccountServiceInfo);
        }
Exemplo n.º 12
0
        private static CredentialCacheCount CreateHostPortCredentialCacheCount(CredentialCache cc = null, int count = 0)
        {
            cc = cc ?? new CredentialCache();

            cc.Add(host1, port1, authenticationType1, credential1); count++;
            cc.Add(host1, port1, authenticationType2, credential2); count++;
            cc.Add(host1, port2, authenticationType1, credential3); count++;
            cc.Add(host1, port2, authenticationType2, credential4); count++;

            cc.Add(host2, port1, authenticationType1, credential5); count++;
            cc.Add(host2, port1, authenticationType2, credential6); count++;
            cc.Add(host2, port2, authenticationType1, credential7); count++;
            cc.Add(host2, port2, authenticationType2, credential8); count++;

            return new CredentialCacheCount(cc, count);
        }
        public Task<ServiceInfo> GetServiceInfo(AppConfig appConfig, CredentialCache credentialCache, IHttpProvider httpProvider)
        {
            var microsoftAccountServiceInfo = new MicrosoftAccountServiceInfo
            {
                AppId = appConfig.MicrosoftAccountAppId,
                ClientSecret = appConfig.MicrosoftAccountClientSecret,
                CredentialCache = credentialCache,
                HttpProvider = httpProvider,
                ReturnUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(),
                Scopes = appConfig.MicrosoftAccountScopes,
                WebAuthenticationUi = this.webAuthenticationUi,
            };

            microsoftAccountServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new WebAuthenticationBrokerAuthenticationProvider(microsoftAccountServiceInfo);
            return Task.FromResult<ServiceInfo>(microsoftAccountServiceInfo);
        }
Exemplo n.º 14
0
        private static CredentialCache HostPortAuthenticationTypeCredentialCache()
        {
            CredentialCache cc = new CredentialCache();

            cc.Add(host1, port1, authenticationType1, credential1);
            cc.Add(host1, port1, authenticationType2, credential2);
            cc.Add(host1, port2, authenticationType1, credential3);
            cc.Add(host1, port2, authenticationType2, credential4);

            cc.Add(host2, port1, authenticationType1, credential5);
            cc.Add(host2, port1, authenticationType2, credential6);
            cc.Add(host2, port2, authenticationType1, credential7);
            cc.Add(host2, port2, authenticationType2, credential8);

            return cc;
        }
 /// <summary>
 /// Creates a OneDrive client for use against OneDrive consumer.
 /// </summary>
 /// <param name="appId">The application ID for Microsoft Account authentication.</param>
 /// <param name="returnUrl">The application return URL for Microsoft Account authentication.</param>
 /// <param name="scopes">The requested scopes for Microsoft Account authentication.</param>
 /// <param name="credentialCache">The cache instance for storing user credentials.</param>
 /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
 /// <param name="webAuthenticationUi">The <see cref="IWebAuthenticationUi"/> for displaying authentication UI to the user.</param>
 /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
 public static IOneDriveClient GetMicrosoftAccountClient(
     string appId,
     string returnUrl,
     string[] scopes,
     CredentialCache credentialCache = null,
     IHttpProvider httpProvider = null,
     IWebAuthenticationUi webAuthenticationUi = null)
 {
     return OneDriveClient.GetMicrosoftAccountClient(
         appId,
         returnUrl,
         scopes,
         /* clientSecret */ null,
         credentialCache,
         httpProvider,
         new ServiceInfoProvider(webAuthenticationUi));
 }
Exemplo n.º 16
0
    /// <summary>
    /// 发送t_news到微博
    /// </summary>
    /// <param name="source">app key</param>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <param name="t_news">需要发送的微博内容</param>
    /// <param name="conn">数据库连接</param>
    public static void RequestWeibo(string source, string username, string password, string t_news, MySqlConnection conn)
    {
        string data = "source=" + source + "&status=" + HttpUtility.UrlEncode(t_news);

        //准备用户验证数据
        string usernamePassword = username + ":" + password;

        //准备调用的URL及需要POST的数据
        string url = "https://api.weibo.com/2/statuses/update.json";

        //准备用于发起请求的HttpWebRequest对象
        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);

        //准备用于用户验证的凭据
        CredentialCache myCache = new CredentialCache();
        myCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
        httpRequest.Credentials = myCache;
        httpRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

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

        //获取服务端的响应内容
        try
        {
            WebResponse wr = httpRequest.GetResponse();
            Stream receiveStream = wr.GetResponseStream();
            StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
            receiveStream.Close();
        }
        catch (Exception e)
        {
            conn.Open();
            MySqlCommand cmd2 = new MySqlCommand("insert into test(msg, date) values ('" + e.ToString() + "','" + DateTime.Now.ToString() + "')", conn);
            cmd2.ExecuteNonQuery();
            conn.Close();
        }
    }
Exemplo n.º 17
0
        private static CredentialCache CreateCredentialCache(int uriCount, int hostPortCount)
        {
            var cc = new CredentialCache();

            for (int i = 0; i < uriCount; i++)
            {
                Uri uri = new Uri(UriPrefix + i.ToString());
                cc.Add(uri, AuthenticationType, s_credential);
            }

            for (int i = 0; i < hostPortCount; i++)
            {
                string host = HostPrefix + i.ToString();
                cc.Add(host, Port, AuthenticationType, s_credential);
            }

            return cc;
        }
        /// <summary>
        /// Creates a OneDrive client for use against OneDrive consumer.
        /// </summary>
        /// <param name="appId">The application ID for Microsoft Account authentication.</param>
        /// <param name="returnUrl">The application return URL for Microsoft Account authentication.</param>
        /// <param name="scopes">The requested scopes for Microsoft Account authentication.</param>
        /// <param name="clientSecret">The client secret for Microsoft Account authentication.</param>
        /// <param name="credentialCache">The cache instance for storing user credentials.</param>
        /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
        /// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
        /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
        public static IOneDriveClient GetMicrosoftAccountClient(
            string appId,
            string returnUrl,
            string[] scopes,
            string clientSecret,
            CredentialCache credentialCache = null,
            IHttpProvider httpProvider = null,
            IServiceInfoProvider serviceInfoProvider = null)
        {
            var appConfig = new AppConfig
            {
                MicrosoftAccountAppId = appId,
                MicrosoftAccountReturnUrl = returnUrl,
                MicrosoftAccountScopes = scopes,
            };

            return new OneDriveClient(appConfig, credentialCache, httpProvider, serviceInfoProvider);
        }
Exemplo n.º 19
0
            /// <summary>
            /// This method creates secure/non secure web
            /// request based on the parameters passed.
            /// </summary>
            /// <param name="uri"></param>
            /// <param name="collHeader">This parameter of type
            ///    NameValueCollection may contain any extra header
            ///    elements to be included in this request      </param>
            /// <param name="RequestMethod">Value can POST OR GET</param>
            /// <param name="NwCred">In case of secure request this would be true</param>
            /// <returns></returns>
            public virtual HttpWebRequest CreateWebRequest(string uri,
              NameValueCollection collHeader,
              string RequestMethod, bool NwCred)
            {
                HttpWebRequest webrequest =
                 (HttpWebRequest)WebRequest.Create(uri);
                webrequest.KeepAlive = false;
                webrequest.Method = RequestMethod;

                int iCount = collHeader.Count;
                string key;
                string keyvalue;

                for (int i = 0; i < iCount; i++)
                {
                    key = collHeader.Keys[i];
                    keyvalue = collHeader[i];
                    webrequest.Headers.Add(key, keyvalue);
                }

                webrequest.ContentType = "text/html";
                //"application/x-www-form-urlencoded";

                if (ProxyServer.Length > 0)
                {
                    webrequest.Proxy = new
                     WebProxy(ProxyServer, ProxyPort);
                }
                webrequest.AllowAutoRedirect = false;

                if (NwCred)
                {
                    CredentialCache wrCache =
                            new CredentialCache();
                    wrCache.Add(new Uri(uri), "Basic",
                      new NetworkCredential(UserName, UserPwd));
                    webrequest.Credentials = wrCache;
                }
                //Remove collection elements
                collHeader.Clear();
                return webrequest;
            }//End of secure CreateWebRequest
Exemplo n.º 20
0
    public static void DoCredentialTest(string url)
    {
        var credential = new NetworkCredential();
        credential.UserName = "******";
        credential.Password =  "******" ;
        var clientHandler = new HttpClientHandler();
        var cc = new CredentialCache();
        cc.Add(new Uri("http://httpbin.org"), "Basic", credential);

        clientHandler.Credentials = cc;
        clientHandler.PreAuthenticate = true;
        var httpClient = new HttpClient(clientHandler);

        httpClient.MaxResponseContentBufferSize = 256000;
        httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        try{
        var responseTask = httpClient.GetAsync(url);
        responseTask.Wait();
            HttpResponseMessage response = responseTask.Result;
        //    response.EnsureSuccessStatusCode();

        if(response.Content != null) {
        var readTask = response.Content.ReadAsStreamAsync();
        readTask.Wait();
        Console.WriteLine(readTask.Result);
        }
        else
        {
        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
        }

        }
        catch(Exception e)
        {
            Console.WriteLine(e);
            return ;
        }

        return;
    }
Exemplo n.º 21
0
    public static string GetWebPage(string url)
    {
        ServicePointManager.CertificatePolicy = new TestCertificatePolicy ();
        ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) (int) protocol;

        ServicePointManager.ClientCipherSuitesCallback += (System.Net.SecurityProtocolType p, IEnumerable<string> allCiphers) => {
            Console.WriteLine ("Protocol: {0}", p);
        //			var ciphers = allCiphers;
            var ciphers = from cipher in allCiphers where !cipher.Contains ("EXPORT") select cipher;
            // string prefix = p == System.Net.SecurityProtocolType.Tls ? "TLS_" : "SSL_";
            //			var ciphers = new List<string> { prefix + "RSA_WITH_AES_128_CBC_SHA", prefix + "RSA_WITH_AES_256_CBC_SHA" };
            foreach (var cipher in ciphers)
                Console.WriteLine ("\t{0}", cipher);
            return ciphers;
        };

        Uri uri = new Uri (url);
        HttpWebRequest req = (HttpWebRequest) WebRequest.Create (uri);

        if ((digestCred != null) || (basicCred != null)) {
            CredentialCache cache = new CredentialCache ();
            if (digestCred != null)
                cache.Add (uri, "Digest", digestCred);
            if (basicCred != null)
                cache.Add (uri, "Basic", basicCred);
            req.Credentials = cache;
        }

        if (certificates.Count > 0)
            req.ClientCertificates.AddRange (certificates);

        WebResponse resp = req.GetResponse ();
        Stream stream = resp.GetResponseStream ();
        StreamReader sr = new StreamReader (stream, Encoding.UTF8);
        return sr.ReadToEnd ();
    }
Exemplo n.º 22
0
        //This is for sending a post request
        private static void post(string jsonData)
        {
            try
            {
                // Create a request using a URL that can receive a post.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strAPIUrl);
                // Set the Method property of the request to POST.
                request.Method = "POST";
                // Create POST data and convert it to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/json";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;

                string          username   = WebUtilities.fetchParamValFromConfig("username");
                string          password   = WebUtilities.fetchParamValFromConfig("password");
                string          dePassword = WebUtilities.decryptString(password);
                CredentialCache credcache  = new CredentialCache();
                credcache.Add(new Uri(strAPIUrl), "NTLM", new NetworkCredential(username, dePassword));
                request.Credentials = credcache;

                // Get the request stream.
                dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                response = (HttpWebResponse)request.GetResponse();
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                statuscode = ((HttpWebResponse)response).StatusCode;
                statusCode = (int)statuscode;

                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                Console.WriteLine(responseFromServer);
                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();

                jsonResArray = JArray.Parse(responseFromServer);
            }
            catch (WebException webEx)
            {
                try
                {
                    if (webEx.Response != null)
                    {
                        response   = (HttpWebResponse)webEx.Response;
                        statuscode = ((HttpWebResponse)response).StatusCode;
                        statusCode = (int)statuscode;

                        // Get the stream containing content returned by the server.
                        dataStream = response.GetResponseStream();
                        // Open the stream using a StreamReader for easy access.
                        StreamReader reader = new StreamReader(dataStream);
                        // Read the content.
                        string responseFromServer = reader.ReadToEnd();
                        // Display the content.
                        Console.WriteLine(responseFromServer);
                        // Clean up the streams.
                        reader.Close();
                        dataStream.Close();
                        response.Close();

                        if (statusCode == 200 || statusCode == 400)
                        {
                            jsonResArray = JArray.Parse(responseFromServer);
                        }
                        else
                        {
                            jsonResObject = JObject.Parse(responseFromServer);
                        }
                    }
                }catch (Exception e)
                {
                    Assert.Fail("Failed to send the Post request" + e);
                }
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VNetWebRequester"/> class.
 /// </summary>
 /// <param name="balancer">the load balancer for the vnet nodes</param>
 /// <param name="contentType">Type of the content.</param>
 public VNetWebRequester(ILoadBalancer balancer, string contentType = "application/x-protobuf")
 {
     _balancer        = balancer;
     _contentType     = contentType;
     _credentialCache = null;
 }
Exemplo n.º 24
0
 /// <summary>
 /// Converts provided cache to <see cref="ICredentialCache"/>.
 /// </summary>
 /// <param name="cache">Cache to convert.</param>
 /// <returns>Converted cache.</returns>
 public static ICredentialCache ToInterface(this CredentialCache cache)
 {
     return((cache == null) ? null : new CredentialCacheAdapter(cache));
 }
Exemplo n.º 25
0
        public async Task ThrowsObjectDisposedExceptionWhenDisposed()
        {
            using (var credentialCache = new CredentialCache())
            {
                await credentialCache.Flush();

                credentialCache.Dispose();
                await Assert.ThrowsAsync<ObjectDisposedException>(async () => await credentialCache.Flush());
            }
        }
Exemplo n.º 26
0
 public void ThrowNotImplementedException()
 {
     using (var credentialCache = new CredentialCache())
     {
         Assert.Throws<NotImplementedException>(() => credentialCache.GetAllKeys());
         Assert.Throws<NotImplementedException>(() => credentialCache.GetCreatedAt(""));
         Assert.Throws<NotImplementedException>(() => credentialCache.InvalidateAll());
         Assert.Throws<NotImplementedException>(() => credentialCache.InvalidateAllObjects<object>());
         Assert.Throws<NotImplementedException>(() => credentialCache.Vacuum());
         Assert.Throws<NotImplementedException>(() => credentialCache.GetAllObjects<object>());
         Assert.Throws<NotImplementedException>(() => credentialCache.GetObjectCreatedAt<object>(""));
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// The purpose of this sample is to login on multiple servers and continuesly
        /// receive "NewEventIndication" and present the events.
        /// </summary>

        public MainForm()
        {
            InitializeComponent();
            _credentialCache = new CredentialCache();
            timer1.Tick     += new EventHandler(timer1_Tick);
        }
Exemplo n.º 28
0
        public async Task InvalidatesTheCredential()
        {
            const string key = nameof(InvalidatesTheCredential);
            using (var credentialCache = new CredentialCache())
            {
                try
                {
                    var credential = Tuple.Create("somebody", "somebody's secret");
                    await credentialCache.InsertObject(key, credential);
                }
                finally
                {
                    await credentialCache.InvalidateObject<Tuple<string, string>>(key);

                    await Assert.ThrowsAsync<KeyNotFoundException>(async () => await credentialCache.Get("unknownkey"));
                }
            }
        }
 public void Setup()
 {
     this.credentialCache = new CredentialCache();
 }
Exemplo n.º 30
0
        public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode)
        {
            Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
            Uri redirectUri = Configuration.Http.RedirectUriForCreds(
                secure:false,
                statusCode:statusCode,
                userName:Username,
                password:Password);
            _output.WriteLine(uri.AbsoluteUri);
            _output.WriteLine(redirectUri.AbsoluteUri);
            var credentialCache = new CredentialCache();
            credentialCache.Add(uri, "Basic", _credential);

            var handler = new HttpClientHandler();
            handler.Credentials = credentialCache;
            using (var client = new HttpClient(handler))
            {
                using (HttpResponseMessage response = await client.GetAsync(redirectUri))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    Assert.Equal(uri, response.RequestMessage.RequestUri);
                }
            }
        }
Exemplo n.º 31
0
 public static void Ctor_Empty_Success()
 {
     CredentialCache cc = new CredentialCache();
 }
Exemplo n.º 32
0
        public async Task <HttpResponseMessage> ToAnyHost()
        {
            var url = Request.RequestUri.ToString();

            var ixApi = url.IndexOf("/api/", StringComparison.InvariantCultureIgnoreCase);

            url = url.Substring(ixApi + 5);
            url = url.Replace("http/", "http://");
            url = url.Replace("https/", "https://");

            var origin = (string)null;

            if (Request.Headers.Contains("Origin"))
            {
                origin = Request.Headers.GetValues("Origin").FirstOrDefault();
            }

            var handler = new HttpClientHandler();

            var username = ConfigurationManager.AppSettings["username"];

            handler.UseDefaultCredentials = string.IsNullOrWhiteSpace(username);
            if (!handler.UseDefaultCredentials)
            {
                var password = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(ConfigurationManager.AppSettings["password"]));
                var domain   = ConfigurationManager.AppSettings["domain"];

                var credential = new NetworkCredential(username, password, domain);
                var myCache    = new CredentialCache();
                myCache.Add(new Uri(url), "NTLM", credential);

                // Create an HttpClientHandler to add some settings
                handler.AllowAutoRedirect = true;
                handler.Credentials       = myCache;
            }


            using (var client = new HttpClient(handler))
            {
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage result;

                if (Request.Method == HttpMethod.Get)
                {
                    result = await ToAnyHostGet(client, url);
                }
                else if (Request.Method == HttpMethod.Options)
                {
                    result = await ToAnyHostOptions(client, url);
                }
                //else if (Request.Method == HttpMethod.Post)
                //    return await ToTfsPost(client, url);
                else
                {
                    throw new NotSupportedException();
                }
                // List data response.
                if (!string.IsNullOrWhiteSpace(origin))
                {
                    if (result.Headers.Contains("Access-Control-Allow-Origin"))
                    {
                        result.Headers.Remove("Access-Control-Allow-Origin");
                    }
                    result.Headers.Add("Access-Control-Allow-Origin", origin);
                }

                result.Headers.Add("Access-Control-Allow-Credentials", "true");
                return(result);
            }
        }
Exemplo n.º 33
0
        public static void Add_HostPortCustomAuthTypeWithDefaultCredential_ThrowsArgumentException(string authType, NetworkCredential nc)
        {
            CredentialCache cc = new CredentialCache();

            AssertExtensions.Throws <ArgumentException>("authenticationType", () => cc.Add(host1, port1, authType, nc));
        }
Exemplo n.º 34
0
        public static void Add_UriCustomAuthTypeWithDefaultCredential_ThrowsArgumentException(string authType, NetworkCredential nc)
        {
            CredentialCache cc = new CredentialCache();

            AssertExtensions.Throws <ArgumentException>("authType", () => cc.Add(uriPrefix1, authType, nc));
        }
Exemplo n.º 35
0
 public CredentialCacheCount(CredentialCache cc, int count)
 {
     CredentialCache = cc;
     Count           = count;
 }
Exemplo n.º 36
0
        public ConcurrentDictionary <string, object> curl_getPost_INIT(string URL, string postData, ConcurrentDictionary <string, object> options = null)
        {
            //From : https://stackoverflow.com/questions/2972643/how-to-use-cookies-with-httpwebrequest
            ConcurrentDictionary <string, object> output = new ConcurrentDictionary <string, object>();

            output["cookies"] = new CookieContainer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.CookieContainer = (CookieContainer)output["cookies"];
            request.UserAgent       = "user_agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36";
            try
            {
                if (options != null)
                {
                    if (options.ContainsKey("login_id") && options.ContainsKey("login_pd"))
                    {
                        CredentialCache mycache = new CredentialCache();
                        Uri             uri     = new Uri(URL);
                        mycache.Add(uri, "Basic", new NetworkCredential(options["login_id"].ToString(), options["login_pd"].ToString()));
                        request.Credentials = mycache;
                    }
                    if (options.ContainsKey("timeout"))
                    {
                        request.Timeout = Convert.ToInt32(options["timeout"]);
                    }
                    if (options.ContainsKey("cookie"))
                    {
                        //request.Headers.Add("Cookie", options["cookie"].ToString());
                        //request.CookieContainer.Add( = options["cookie"].ToString();
                        request.CookieContainer = new CookieContainer();
                        Uri uri = new Uri(URL);
                        request.CookieContainer.SetCookies(uri, options["cookie"].ToString());
                    }
                    if (options.ContainsKey("user_agent"))
                    {
                        request.UserAgent = options["user_agent"].ToString();
                    }
                }
                request.Proxy = null;


                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                if (postData == "")
                {
                    //GET
                    Stream stream = response.GetResponseStream();
                    output["data"] = ReadStream(stream, 32765);
                    stream.Close();
                }
                else
                {
                    //Post
                    byte[] data = Encoding.UTF8.GetBytes(postData);
                    request.Method        = "POST";
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;

                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                        stream.Close();
                    }
                }
                output["realCookie"] = response.Headers[HttpResponseHeader.SetCookie];
                response.Close();
                output["reason"] = "";
                return(output);
            }
            catch (Exception ex)
            {
                output["data"]   = new byte[0];
                output["reason"] = ex.Message + "\n\r" + ex.StackTrace;
                return(output);
            }
        }
Exemplo n.º 37
0
        public static string HTTPRequest(TelegramParams TelegramParams, string typeRequest, string request, string data)
        {
            //AdditionalFunc.Trace("Request: \n" + request + "\n\n" + "Data:\n" + data + "\n\n");

            try
            {
                ServicePointManager.Expect100Continue = true;

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                CredentialCache cache = new CredentialCache();
                HttpWebRequest  req   = (HttpWebRequest)HttpWebRequest.Create(request);

                if (TelegramParams != null)
                {
                    req.Proxy = new WebProxy(TelegramParams.Proxy.IP, TelegramParams.Proxy.Port);
                    //req.Proxy = new WebProxy("http://" + TelegramParams.Proxy.IP + ":" + TelegramParams.Proxy.Port + "/", true);

                    if (!String.IsNullOrEmpty(TelegramParams.Proxy.Login) & !String.IsNullOrEmpty(TelegramParams.Proxy.Password))
                    {
                        req.Proxy.Credentials = new NetworkCredential(TelegramParams.Proxy.Login, TelegramParams.Proxy.Password);
                    }
                }

                //Игнорируем недостоверный сертификат SSL
                ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                                                                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                                                                                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
                {
                    return(true);
                };

                req.KeepAlive       = false;
                req.PreAuthenticate = true;
                req.Method          = typeRequest;
                req.Timeout         = 10000;

                if (!String.Equals(typeRequest, Variables.get))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(data);
                    req.ContentType   = "application/json";
                    req.ContentLength = byteArray.Length;
                    Stream dataStreamReq = req.GetRequestStream();
                    dataStreamReq.Write(byteArray, 0, byteArray.Length);
                    dataStreamReq.Close();
                }

                WebResponse response       = req.GetResponse();
                Stream      dataStreamResp = response.GetResponseStream();

                StreamReader reader             = new StreamReader(dataStreamResp, Encoding.UTF8);
                string       responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStreamResp.Close();
                response.Close();

                //AdditionalFunc.Trace("Responce: \n" + responseFromServer + "\n\n\n");
                return(responseFromServer);
            }
            catch (Exception ex)
            {
                AdditionalFunc.Trace("Request: \n" + request + "\n\n" + "Data:\n" + data);
                AdditionalFunc.Trace("Responce: \n" + ex.ToString());
                return(Variables.requestStateError);
            }
        }
Exemplo n.º 38
0
        public async Task InvalidatesTheCredential()
        {
            using (var credentialCache = new CredentialCache())
            {
                var credential = Tuple.Create("somebody", "somebody's secret");
                await credentialCache.InsertObject(nameof(InvalidatesTheCredential), credential);
                await credentialCache.Invalidate(nameof(InvalidatesTheCredential));

                await Assert.ThrowsAsync<KeyNotFoundException>(async () => await credentialCache.Get(nameof(InvalidatesTheCredential)));
            }
        }
        /// <summary>
        /// Get Currency Conversion Rate from API
        /// </summary>
        /// <param name="from">Currency From</param>
        /// <param name="to">Currency To</param>
        /// <param name="url">URL of given API</param>
        /// <param name="apiKey">API key if required</param>
        /// <returns>Response or Exchange Rate as String</returns>
        public static string GetConvertedCurrencyValue(string from, string to, string url, string apiKey)
        {
            string response = "";

            if (url.ToUpper().Contains("XE.COM"))
            {
                if (from == to)
                {
                    response = Convert.ToString(1);
                    return(response);
                }
                //string newUrl = @"http://www.xe.com/ucc/convert/?Amount=1&From=" + from.ToString() + "&To=" + to.ToString() + "";
                //HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(newUrl);
                //HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();//send sms
                //StreamReader responseReader = new StreamReader(resp.GetResponseStream());//read the response
                //response = responseReader.ReadToEnd();//get result
                //response = response.Substring(response.IndexOf("<td width=\"47%\" align=\"left\" class=\"rightCol\">"));
                //response = response.Substring(response.IndexOf("rightCol\">") + 10); // +10 to remove unwanted things before the converted value

                //response = response.Substring(0, response.IndexOf('&'));
                //responseReader.Close();
                //resp.Close();
                //return response;

                decimal         exchangeRate = 0;
                string          newUrl       = @"https://xecdapi.xe.com/v1/convert_from.json/?from=" + from.ToString().ToUpper() + "&to=" + to.ToString().ToUpper() + "&amount=1";
                WebRequest      myReq        = WebRequest.Create(newUrl);
                CredentialCache mycache      = new CredentialCache();
                myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(apiKey));
                WebResponse  wr            = myReq.GetResponse();
                Stream       receiveStream = wr.GetResponseStream();
                StreamReader reader        = new StreamReader(receiveStream, Encoding.UTF8);
                string       content       = reader.ReadToEnd();
                dynamic      rates         = JsonConvert.DeserializeObject <dynamic>(content);
                if (rates != null && rates.to != null && rates.to.Count > 0)
                {
                    exchangeRate = rates.to[0]["mid"];
                }
                return(exchangeRate.ToString());
            }
            else if (url.ToUpper().Contains("GOOGLE.COM"))
            {
                if (from == to)
                {
                    response = Convert.ToString(1);
                    return(response);
                }
                WebClient web    = new WebClient();
                string    newUrl = @"http://www.google.com/finance/converter?a=1&from=" + from.ToString().ToUpper() + "&to=" + to.ToString().ToUpper() + "";
                response = web.DownloadString(newUrl);
                if (response.Contains("currency_converter_result"))
                {
                    response = response.Substring(response.IndexOf("currency_converter_result"), 70);
                    response = response.Substring(response.IndexOf(">") + 1);
                    response = response.Substring(response.IndexOf(">") + 1);
                    response = response.Substring(0, response.IndexOf(" "));
                    return(response);
                }
            }
            else if (url.ToLower().Contains("api.bnm.gov.my"))
            {
                string newUrl = @"https://api.bnm.gov.my/public/exchange-rate";

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(newUrl);
                myReq.Method = "GET";
                myReq.Accept = "application/vnd.BNM.API.v1+json";

                HttpWebResponse wr = (HttpWebResponse)myReq.GetResponse();

                Stream       receiveStream = wr.GetResponseStream();
                StreamReader reader        = new StreamReader(receiveStream, Encoding.UTF8);
                string       content       = reader.ReadToEnd();
                return(content);
            }
            //else if (url.ToLower().Contains("pwebapps.ezv.admin.ch"))
            //{
            //decimal exchangeRate = 0;
            //string currencyQty = "";

            //string newUrl = @"http://www.pwebapps.ezv.admin.ch/apps/rates/rate/getxml?activeSearchType=userDefinedDay";
            //WebRequest myReq = WebRequest.Create(newUrl);
            //WebResponse wr = myReq.GetResponse();
            //Stream receiveStream = wr.GetResponseStream();
            //StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
            //string content = reader.ReadToEnd();
            //return content;

            //XmlDocument xml = new XmlDocument();
            //xml.LoadXml(content);

            //XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
            //manager.AddNamespace("xsi", "http://www.pwebapps.ezv.admin.ch/apps/rates");
            //manager.AddNamespace("car", "http://www.pwebapps.ezv.admin.ch/apps/rates");

            //XmlNodeList xnList = xml.SelectNodes("//car:wechselkurse/car:devise", manager);

            //foreach (XmlNode xn in xnList)
            //{
            //    if (xn.Attributes["code"].Value == to.ToLower())
            //    {
            //        currencyQty = xn["waehrung"].InnerText;
            //        exchangeRate = Util.GetValueOfDecimal(xn["kurs"].InnerText);
            //        break;
            //    }
            //}

            //if (!String.IsNullOrEmpty(currencyQty) && exchangeRate != 0)
            //{
            //    decimal qty = Util.GetValueOfDecimal(currencyQty.Substring(0, currencyQty.Length - 4));
            //    exchangeRate = exchangeRate / qty;
            //}

            //return exchangeRate.ToString();
            //}
            else
            {
                WebClient web    = new WebClient();
                string    newUrl = "https://api.exchangerate-api.com/v4/latest/" + from.ToUpper();
                response = new WebClient().DownloadString(newUrl);
                decimal exchangeRate = 0;
                dynamic rate         = JsonConvert.DeserializeObject <dynamic>(response);
                if (rate.rates != null)
                {
                    exchangeRate = rate.rates[to.ToUpper()];
                }
                return(exchangeRate.ToString());

                //string newUrl = string.Format("http://rate-exchange.appspot.com/currency?from={0}&to={1}", from.ToString().ToUpper(), to.ToString().ToUpper());
                //response = web.DownloadString(url);
                //Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(response);
                //decimal exchangeRate = (decimal)token.SelectToken("rate");
                ////dynamic rate = JsonConvert.DeserializeObject<dynamic>(response);
                ////decimal exchangeRate = rate.rate;
                //return exchangeRate.ToString();
            }

            return(response);
        }
Exemplo n.º 40
0
 public async Task ThrowsKeyNotFoundExceptionWhenKeyNotFound()
 {
     using (var credentialCache = new CredentialCache())
     {
         await Assert.ThrowsAsync<KeyNotFoundException>(
             async () => await credentialCache.InvalidateObject<Tuple<string, string>>("git:_"));
         await Assert.ThrowsAsync<KeyNotFoundException>(
             async () => await credentialCache.InvalidateObject<Tuple<string, string>>("_"));
     }
 }
Exemplo n.º 41
0
        private void Push()
        {
            SharedClass.Logger.Info("Started");
            string smsResponse = string.Empty;

            while (!SharedClass.HasStopSignal)
            {
                SMSResult smsResult = null;
                smsResult = new SMSResult();

                try
                {
                    if (this.SMSQueueCount() > 0)
                    {
                        SMS sms = this.DeQueueSMS();
                        smsResult.sms = sms;
                        JObject Jobj = new JObject();
                        if (sms != null)
                        {
                            JObject smsPostdata;
                            sms.MobileNumber = sms.MobileNumber.Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("+", "");
                            HttpWebRequest  webRequestObj   = null;
                            HttpWebResponse webResponseObj  = null;
                            StreamWriter    streamWriterObj = null;
                            StreamReader    streamReaderObj = null;
                            CredentialCache credentials     = new CredentialCache();

                            //if ((IsUnicode(sms.Message) == true)) {
                            //    sms.MessageType = "OL";
                            //}
                            //else {
                            //    sms.MessageType = "N";
                            //}

                            //if ((sms.MessageType == "OL")) {
                            //    sms.Message = convertHexa(sms.Message);
                            //}

                            smsPostdata = new JObject(
                                new JProperty("Text", sms.Message),
                                new JProperty("Number", sms.MobileNumber),
                                new JProperty("DRNotifyUrl", ""),
                                new JProperty("DRNotifyHttpMethod", "POST"),
                                new JProperty("Tool", "API"),
                                new JProperty("SenderId", sms.SenderId));
                            SharedClass.Logger.Info("PostData" + smsPostdata.ToString());
                            credentials.Add(new Uri(SharedClass.SMSProvider),
                                            "Basic", new NetworkCredential(SharedClass.SMSProviderAuthkey, SharedClass.SMSProviderSecretKey));
                            webRequestObj             = (HttpWebRequest)WebRequest.Create(SharedClass.SMSProvider);
                            webRequestObj.Method      = "Post";
                            webRequestObj.Credentials = credentials;
                            webRequestObj.ContentType = "application/json";
                            streamWriterObj           = new StreamWriter(webRequestObj.GetRequestStream());
                            streamWriterObj.Write(smsPostdata);
                            streamWriterObj.Flush();
                            streamWriterObj.Close();
                            webResponseObj  = (HttpWebResponse)webRequestObj.GetResponse();
                            streamReaderObj = new StreamReader(webResponseObj.GetResponseStream());
                            smsResponse     = streamReaderObj.ReadToEnd();
                            streamReaderObj.Close();

                            Jobj = JObject.Parse(smsResponse);

                            sms.JobNumber = Jobj.SelectToken("ApiId").ToString();
                            if (Convert.ToBoolean(Jobj.SelectToken("Success").ToString()))
                            {
                                smsResult.IsSuccess = true;
                                smsResult.StatusId  = 3;
                                smsResult.JobNumber = sms.JobNumber;
                            }
                            else
                            {
                                smsResult.IsSuccess = false;
                                smsResult.StatusId  = 5;
                                smsResult.JobNumber = sms.JobNumber;
                            }
                            this.EnQueueSMSStatus(smsResult);
                        }
                    }
                    else
                    {
                        try
                        {
                            Thread.Sleep(2000);
                        }
                        catch (ThreadInterruptedException e)
                        { }
                        catch (ThreadAbortException e)
                        { }
                    }
                }
                catch (Exception e)
                {
                    smsResult.StatusId  = 5;
                    smsResult.JobNumber = "";
                    this.EnQueueSMSStatus(smsResult);
                    SharedClass.Logger.Error(e.ToString());
                }
            }
            SharedClass.Logger.Info("Exit");
        }
Exemplo n.º 42
0
 public void SignalsShutdown()
 {
     bool shutdown = false;
     using (var credentialCache = new CredentialCache())
     {
         credentialCache.Shutdown.Subscribe(_ => shutdown = true);
     }
     Assert.True(shutdown);
 }
Exemplo n.º 43
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        protected string GetResponseString(HttpWebRequest req)
        {
            Request = req;

            if (!string.IsNullOrEmpty(Variables.HttpAuthUsername) && !string.IsNullOrEmpty(Variables.HttpAuthPassword))
            {
                NetworkCredential login = new NetworkCredential
                {
                    UserName = Variables.HttpAuthUsername,
                    Password = Variables.HttpAuthPassword,
                    // Domain = "",
                };

                CredentialCache myCache = new CredentialCache
                {
                    { new Uri(URL), "Basic", login }
                };
                req.Credentials = myCache;

                req = (HttpWebRequest)SetBasicAuthHeader(req, login.UserName, login.Password);
            }

            try
            {
                using (WebResponse resp = req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                    {
                        return(sr.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                var resp = (HttpWebResponse)ex.Response;
                if (resp == null)
                {
                    throw;
                }
                switch (resp.StatusCode)
                {
                case HttpStatusCode.Unauthorized:     // 401
                    break;

                case HttpStatusCode.NotFound: // 404
                    return("");               // emulate the behaviour of Tools.HttpGet()
                }

                // just reclassifying
                if (ex.Status == WebExceptionStatus.RequestCanceled)
                {
                    throw new AbortedException(this);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                Request = null;
            }
        }
Exemplo n.º 44
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(NegotiateCredential));

            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));

            // Get the user name from the credential data.
            string userName;

            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.UserName, out userName))
            {
                userName = null;
            }

            ArgUtil.NotNullOrEmpty(userName, nameof(userName));
            trace.Info("User name retrieved.");

            // Get the password from the credential data.
            string password;

            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Password, out password))
            {
                password = null;
            }

            ArgUtil.NotNullOrEmpty(password, nameof(password));
            trace.Info("Password retrieved.");

            // Get the URL from the credential data.
            string url;

            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out url))
            {
                url = null;
            }

            ArgUtil.NotNullOrEmpty(url, nameof(url));
            trace.Info($"URL retrieved: {url}");

            // Create the Negotiate and NTLM credential object.
            var credential      = new NetworkCredential(userName, password);
            var credentialCache = new CredentialCache();

            switch (Constants.Agent.Platform)
            {
            case Constants.OSPlatform.Linux:
            case Constants.OSPlatform.OSX:
                credentialCache.Add(new Uri(url), "NTLM", credential);
                break;

            case Constants.OSPlatform.Windows:
                credentialCache.Add(new Uri(url), "Negotiate", credential);
                break;
            }

            VssCredentials creds = new VssClientCredentials(new WindowsCredential(credentialCache));

            trace.Verbose("cred created");
            return(creds);
        }
Exemplo n.º 45
0
        public void TestDeserializationAksiok()
        {
            var ac = new AksiokAddAndUpdateObjectDb();
            DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.EquipmentType[]> allType = null;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback = (senders, certificate, chain, sslPolicyErrors) =>
            {
                return(true);
            };
            CredentialCache myCache = new CredentialCache();

            myCache.Add(new Uri("https://aksiok.dpc.tax.nalog.ru"), "Negotiate", new NetworkCredential("7751-00-099", "Qwerty12345678!"));
            var cookies = new CookieContainer();

            cookies.Add(new Cookie(".ASPXAUTH", "585B2C7DA8479B5A1A355A9F3CED47C3BDE9539CD6924311DDAAC368C951513252E0F2C706D11BF4E3FE31B2869A374962E555235370CED6DD63BD067095D3CA6CCF470768E7C61FB6C796A080FDE124CBB359D96133240B1983198864BE9836763DD7C13122BDE0703A5A760F3ACAD8FF62F43EF367170C1617A3DC956EBA471A7F81BC7F76C5B4C9B643C4AF5559F7B81100F25E81BB997A02BC99985B2F57D45A6F4FBAAD9B43D9A0EC7CDCB6C96C2AC2FB6C677AB2DAB99DC56CDF7D0CD9398671643E630F126A26230990F07DEA19DB6FC52AE3C450598FB3BAF75C3C9CD18B6E3AF61482DE5E4006BB3BDC5E909B1945D775E57D10837CBF2138E7F742255B522AEFBB296ABA7553CC5FC89AA0D97951003D431095E4D10B7C9F9BAF761D62E45475E9A99394FE4D3789A7D88E5429B1280A5EA9859C0446A1C6E74FFA6282CF4309A11F30DF0320343F40BC0D97F640E635637A8618E7EF35B8E43774C1305E4B3BC5FA7DA6A237F19452082C95229D90566C2BE802ACEF1EDB8EFBC199EC9D55C9F7C28064CFAB322930BE5454B12B99E430BF7E5B37F3678D5720AD", "/", "dpc.tax.nalog.ru"));

            //Справочник производитель
            DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"actualDate\":\"2022-04-19T00: 00:00\",\"page\":1,\"start\":0,\"limit\":25,\"sort\":[{\"property\":\"Code\",\"direction\":\"ASC\"}]}");
            Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/Producer/List?_dc=1650353905544");
            Request.Accept          = "*/*";
            Request.KeepAlive       = true;
            Request.Credentials     = myCache;
            Request.CookieContainer = cookies;
            Request.Host            = "aksiok.dpc.tax.nalog.ru";
            Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
            Request.ContentType     = "application/json";
            Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
            Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
            Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
            Request.Headers.Add("sec-ch-ua-mobile", "?0");
            Request.Headers.Add("sec-ch-ua-platform", "Windows");
            Request.Headers.Add("Sec-Fetch-Dest", "empty");
            Request.Headers.Add("Sec-Fetch-Mode", "cors");
            Request.Headers.Add("Sec-Fetch-Site", "same-origin");
            Request.Method        = "POST";
            Request.ContentLength = DatesBytesFile.Length;
            using (var stream = Request.GetRequestStream())
            {
                stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
            }
            Response = (HttpWebResponse)Request.GetResponse();
            cookies.Add(Response.Cookies);
            if (Response.StatusCode == HttpStatusCode.OK)
            {
                using (var receiveStream = Response.GetResponseStream())
                {
                    StreamReader readStream;
                    readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                        ? new StreamReader(receiveStream)
                        : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                    string data = readStream.ReadToEnd();
                    var    dataModelServerAksiok = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.Producer[]> >(data);

                    ac.AddAndUpdateFullLoadAksiok(dataModelServerAksiok.Data, "Producer");
                }
            }
            //Справочник типы оборудования
            DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"actualDate\":\"2022-04-19T00: 00:00\",\"page\":1,\"start\":0,\"limit\":25,\"sort\":[{\"property\":\"Code\",\"direction\":\"ASC\"}]}");
            Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EquipmentType/list?_dc=1650354780285");
            Request.Accept          = "*/*";
            Request.KeepAlive       = true;
            Request.Credentials     = myCache;
            Request.CookieContainer = cookies;
            Request.Host            = "aksiok.dpc.tax.nalog.ru";
            Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
            Request.ContentType     = "application/json";
            Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
            Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
            Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
            Request.Headers.Add("sec-ch-ua-mobile", "?0");
            Request.Headers.Add("sec-ch-ua-platform", "Windows");
            Request.Headers.Add("Sec-Fetch-Dest", "empty");
            Request.Headers.Add("Sec-Fetch-Mode", "cors");
            Request.Headers.Add("Sec-Fetch-Site", "same-origin");
            Request.Method        = "POST";
            Request.ContentLength = DatesBytesFile.Length;
            using (var stream = Request.GetRequestStream())
            {
                stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
            }
            Response = (HttpWebResponse)Request.GetResponse();
            cookies.Add(Response.Cookies);
            if (Response.StatusCode == HttpStatusCode.OK)
            {
                using (var receiveStream = Response.GetResponseStream())
                {
                    StreamReader readStream;
                    readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                        ? new StreamReader(receiveStream)
                        : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                    string data = readStream.ReadToEnd();
                    allType = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.EquipmentType[]> >(data);
                    ac.AddAndUpdateFullLoadAksiok(allType.Data, "EquipmentType");
                }
            }

            DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.Producer[]> product = null;

            //Справочник модель оборудования
            foreach (var type in allType.Data)
            {
                //Сначала запрос типов (Продуктов)
                DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"node\":" + type.Id + ",\"nodeLevel\":0,\"rootNode\":null,\"actualDate\":\"2022-04-19T00: 00:00\",\"page\":1,\"start\":0,\"limit\":25,\"id\":" + type.Id + "}");
                Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EquipmentModel/ListTree?_dc=1650356158346 ");
                Request.Accept          = "*/*";
                Request.KeepAlive       = true;
                Request.Credentials     = myCache;
                Request.CookieContainer = cookies;
                Request.Host            = "aksiok.dpc.tax.nalog.ru";
                Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
                Request.ContentType     = "application/json";
                Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
                Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
                Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
                Request.Headers.Add("sec-ch-ua-mobile", "?0");
                Request.Headers.Add("sec-ch-ua-platform", "Windows");
                Request.Headers.Add("Sec-Fetch-Dest", "empty");
                Request.Headers.Add("Sec-Fetch-Mode", "cors");
                Request.Headers.Add("Sec-Fetch-Site", "same-origin");
                Request.Method        = "POST";
                Request.ContentLength = DatesBytesFile.Length;
                using (var stream = Request.GetRequestStream())
                {
                    stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
                }
                Response = (HttpWebResponse)Request.GetResponse();
                cookies.Add(Response.Cookies);
                if (Response.StatusCode == HttpStatusCode.OK)
                {
                    using (var receiveStream = Response.GetResponseStream())
                    {
                        StreamReader readStream;
                        readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                            ? new StreamReader(receiveStream)
                            : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                        string data = readStream.ReadToEnd();
                        product = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.Producer[]> >(data);
                    }
                }

                foreach (var p in product.Data)
                {
                    //Сначала запрос типов (Продуктов)
                    DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"node\":" + p.Id + ",\"nodeLevel\":1,\"rootNode\":" + type.Id + ",\"actualDate\":\"2022-04-19T00:00:00\",\"page\":1,\"start\":0,\"limit\":25,\"id\":" + p.Id + "}");
                    Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EquipmentModel/ListTree?_dc=1650356158346 ");
                    Request.Accept          = "*/*";
                    Request.KeepAlive       = true;
                    Request.Credentials     = myCache;
                    Request.CookieContainer = cookies;
                    Request.Host            = "aksiok.dpc.tax.nalog.ru";
                    Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
                    Request.ContentType     = "application/json";
                    Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                    Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
                    Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                    Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
                    Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
                    Request.Headers.Add("sec-ch-ua-mobile", "?0");
                    Request.Headers.Add("sec-ch-ua-platform", "Windows");
                    Request.Headers.Add("Sec-Fetch-Dest", "empty");
                    Request.Headers.Add("Sec-Fetch-Mode", "cors");
                    Request.Headers.Add("Sec-Fetch-Site", "same-origin");
                    Request.Method        = "POST";
                    Request.ContentLength = DatesBytesFile.Length;
                    using (var stream = Request.GetRequestStream())
                    {
                        stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
                    }
                    Response = (HttpWebResponse)Request.GetResponse();
                    cookies.Add(Response.Cookies);
                    if (Response.StatusCode == HttpStatusCode.OK)
                    {
                        using (var receiveStream = Response.GetResponseStream())
                        {
                            StreamReader readStream;
                            readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                                ? new StreamReader(receiveStream)
                                : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                            string data = readStream.ReadToEnd();
                            var    dataModelServerAksiok = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.EquipmentModel[]> >(data);
                            ac.AddAndUpdateFullLoadAksiok(dataModelServerAksiok.Data, "EquipmentModel", type.Id, p.Id);
                        }
                    }
                }
            }



            DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.ModelDocumentType[]> modelDocumentType = null;
            DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.ModelDocument[]>     modelDocument     = null;

            DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"page\":1,\"start\":0,\"limit\":1000}");
            Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EpoRegistry/List?_dc=1649674857153");
            Request.Accept          = "*/*";
            Request.KeepAlive       = true;
            Request.Credentials     = myCache;
            Request.CookieContainer = cookies;
            Request.Host            = "aksiok.dpc.tax.nalog.ru";
            Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
            Request.ContentType     = "application/json";
            Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
            Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
            Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
            Request.Headers.Add("sec-ch-ua-mobile", "?0");
            Request.Headers.Add("sec-ch-ua-platform", "Windows");
            Request.Headers.Add("Sec-Fetch-Dest", "empty");
            Request.Headers.Add("Sec-Fetch-Mode", "cors");
            Request.Headers.Add("Sec-Fetch-Site", "same-origin");
            Request.Method        = "POST";
            Request.ContentLength = DatesBytesFile.Length;
            using (var stream = Request.GetRequestStream())
            {
                stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
            }
            Response = (HttpWebResponse)Request.GetResponse();
            cookies.Add(Response.Cookies);
            if (Response.StatusCode == HttpStatusCode.OK)
            {
                using (var receiveStream = Response.GetResponseStream())
                {
                    StreamReader readStream;
                    readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                        ? new StreamReader(receiveStream)
                        : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                    string data = readStream.ReadToEnd();
                    modelDocumentType = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.ModelDocumentType[]> >(data);
                    ac.AddAndUpdateFullLoadAksiok(modelDocumentType.Data, "ModelDocumentType");
                }
            }


            foreach (var p in modelDocumentType.Data)
            {
                DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"epoDocumentId\":" + p.Id + ",\"page\":1,\"start\":0,\"limit\":500}");
                Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EquipmentCard/ListEquipments?_dc=1649676212262");
                Request.Accept          = "*/*";
                Request.KeepAlive       = true;
                Request.Credentials     = myCache;
                Request.CookieContainer = cookies;
                Request.Host            = "aksiok.dpc.tax.nalog.ru";
                Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
                Request.ContentType     = "application/json";
                Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
                Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
                Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
                Request.Headers.Add("sec-ch-ua-mobile", "?0");
                Request.Headers.Add("sec-ch-ua-platform", "Windows");
                Request.Headers.Add("Sec-Fetch-Dest", "empty");
                Request.Headers.Add("Sec-Fetch-Mode", "cors");
                Request.Headers.Add("Sec-Fetch-Site", "same-origin");
                Request.Method        = "POST";
                Request.ContentLength = DatesBytesFile.Length;
                using (var stream = Request.GetRequestStream())
                {
                    stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
                }
                Response = (HttpWebResponse)Request.GetResponse();
                cookies.Add(Response.Cookies);
                if (Response.StatusCode == HttpStatusCode.OK)
                {
                    using (var receiveStream = Response.GetResponseStream())
                    {
                        StreamReader readStream;
                        readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                            ? new StreamReader(receiveStream)
                            : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                        string data = readStream.ReadToEnd();
                        modelDocument = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.ModelDocument[]> >(data);
                    }
                }

                foreach (var document in modelDocument.Data)
                {
                    DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"id\":" + document.Id + "}");
                    Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EquipmentCard/get?_dc=1649676459600");
                    Request.Accept          = "*/*";
                    Request.KeepAlive       = true;
                    Request.Credentials     = myCache;
                    Request.CookieContainer = cookies;
                    Request.Host            = "aksiok.dpc.tax.nalog.ru";
                    Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
                    Request.ContentType     = "application/json";
                    Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                    Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
                    Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                    Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
                    Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
                    Request.Headers.Add("sec-ch-ua-mobile", "?0");
                    Request.Headers.Add("sec-ch-ua-platform", "Windows");
                    Request.Headers.Add("Sec-Fetch-Dest", "empty");
                    Request.Headers.Add("Sec-Fetch-Mode", "cors");
                    Request.Headers.Add("Sec-Fetch-Site", "same-origin");
                    Request.Method        = "POST";
                    Request.ContentLength = DatesBytesFile.Length;
                    using (var stream = Request.GetRequestStream())
                    {
                        stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
                    }
                    Response = (HttpWebResponse)Request.GetResponse();
                    cookies.Add(Response.Cookies);
                    if (Response.StatusCode == HttpStatusCode.OK)
                    {
                        using (var receiveStream = Response.GetResponseStream())
                        {
                            StreamReader readStream;
                            readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                                ? new StreamReader(receiveStream)
                                : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                            string data = readStream.ReadToEnd();
                            var    dataModelServerAksiok = Newtonsoft.Json.JsonConvert.DeserializeObject <DataAksiokFullSchemes <EfDatabase.ModelAksiok.Aksiok.EpoDocument> >(data, new JsonSerializerSettings()
                            {
                                NullValueHandling = NullValueHandling.Ignore
                            });
                            ac.AddAndUpdateFullLoadAksiok(dataModelServerAksiok.Data, "EpoDocument", p.Id);
                        }
                    }
                    DatesBytesFile          = Encoding.UTF8.GetBytes("{\"records\":[],\"id\":" + document.Id + "}");
                    Request                 = (HttpWebRequest)WebRequest.Create("https://aksiok.dpc.tax.nalog.ru/api/EquipmentCardAddChar/get?_dc=1649676665906");
                    Request.Accept          = "*/*";
                    Request.KeepAlive       = true;
                    Request.Credentials     = myCache;
                    Request.CookieContainer = cookies;
                    Request.Host            = "aksiok.dpc.tax.nalog.ru";
                    Request.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
                    Request.ContentType     = "application/json";
                    Request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                    Request.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
                    Request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                    Request.Headers.Add("Origin", "https://aksiok.dpc.tax.nalog.ru/");
                    Request.Headers.Add("sec-ch-ua", "Not A;Brand\";v=\"99\", \"Chromium\"; v=\"96\", \"Google Chrome\"; v=\"96\"");
                    Request.Headers.Add("sec-ch-ua-mobile", "?0");
                    Request.Headers.Add("sec-ch-ua-platform", "Windows");
                    Request.Headers.Add("Sec-Fetch-Dest", "empty");
                    Request.Headers.Add("Sec-Fetch-Mode", "cors");
                    Request.Headers.Add("Sec-Fetch-Site", "same-origin");
                    Request.Method        = "POST";
                    Request.ContentLength = DatesBytesFile.Length;
                    using (var stream = Request.GetRequestStream())
                    {
                        stream.Write(DatesBytesFile, 0, DatesBytesFile.Length);
                    }
                    Response = (HttpWebResponse)Request.GetResponse();
                    cookies.Add(Response.Cookies);
                    if (Response.StatusCode == HttpStatusCode.OK)
                    {
                        using (var receiveStream = Response.GetResponseStream())
                        {
                            StreamReader readStream;
                            readStream = String.IsNullOrWhiteSpace(Response.CharacterSet)
                                ? new StreamReader(receiveStream)
                                : new StreamReader(receiveStream, Encoding.GetEncoding(Response.CharacterSet));
                            string data = readStream.ReadToEnd();
                            var    dataModelServerAksiok = JsonConvert.DeserializeObject <DataAksiokFullSchemes <ValueCharacteristicJson> >(data, new JsonSerializerSettings()
                            {
                                NullValueHandling = NullValueHandling.Ignore
                            });
                            ac.AddAndUpdateFullLoadAksiok(dataModelServerAksiok.Data, "ValueCharacteristicJson");
                        }
                    }
                }
            }
            ac.AddAndUpdateFullLoadAksiok <ValueCharacteristicJson>(null, "FinishProcess");
        }
Exemplo n.º 46
0
        public (HttpWebResponse, double) SetAPIRequest(RequestParameters _requestparameters)
        {
            var webRequest = WebRequest.CreateHttp(_requestparameters.Url);

            webRequest.Method = _requestparameters.Method.ToString();
            webRequest.Host   = _requestparameters.Url.Host;

            if (_requestparameters.HeaderKeyValues != null)
            {
                foreach (KeyValuePair <string, string> credentialpair in _requestparameters.HeaderKeyValues)
                {
                    webRequest.Headers[credentialpair.Key] = credentialpair.Value;
                }
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            if (_requestparameters.Authentication)
            {
                var networkCredential = new NetworkCredential(_requestparameters.UserName, _requestparameters.Password);
                var myCredentialCache = new CredentialCache {
                    { _requestparameters.Url, _requestparameters.Protocol.ToString(), networkCredential }
                };

                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;

                webRequest.PreAuthenticate = true;
                webRequest.Credentials     = myCredentialCache;
            }

            ServicePointManager.ServerCertificateValidationCallback +=
                (sender, certificate, chain, sslPolicyErrors) => true;
            ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;

            if (_requestparameters.Method == HttpMethod.POST ||
                _requestparameters.Method == HttpMethod.PUT ||
                _requestparameters.Method == HttpMethod.PATCH)
            {
                if (_requestparameters.RequestData != null)
                {
                    var data = Encoding.UTF8.GetBytes(_requestparameters.RequestData);
                    webRequest.ContentLength = data.Length;

                    using (Stream stream = webRequest.GetRequestStream())
                    {
                        GenerateStreamFromString(_requestparameters.RequestData).CopyTo(stream);
                    }
                }
                else
                {
                    webRequest.ContentLength = 0;
                }
            }

            WebProxy DefaultProxy = new WebProxy {
                UseDefaultCredentials = true
            };

            webRequest.Proxy       = _requestparameters.ProxyServer ?? DefaultProxy;
            webRequest.Referer     = _requestparameters.Referer ?? "";
            webRequest.ContentType = _requestparameters.ContentType ?? "application/json;charset=utf-8";

            HttpRequestCachePolicy requestPolicy;

            if (_requestparameters.CacheTime != "0")
            {
                int numberOfHours = Convert.ToInt16(_requestparameters.CacheTime);
                requestPolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(numberOfHours));
            }
            else
            {
                requestPolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            }

            webRequest.CachePolicy = requestPolicy;
            webRequest.Timeout     = 15000;
            var requeststopwatch = Stopwatch.StartNew();

            try
            {
                Response = (HttpWebResponse)webRequest.GetResponse();
                requeststopwatch.Stop();
                ResponseTime = requeststopwatch.Elapsed.TotalMilliseconds;
                Console.WriteLine($"Time taken by request to execute is : {ResponseTime} ms ");
            }

            catch (WebException requestFailure)
            {
                Console.WriteLine("Request failed. Printing parameters used to send request for debugging purpose");
                Console.WriteLine($"Request type : {webRequest.Method}");
                Console.WriteLine($"Header Values : {webRequest.Headers}");
                Console.WriteLine($"Request URI : {webRequest.RequestUri}");
                Console.WriteLine($"Content length : {webRequest.ContentLength}");
                Console.WriteLine($"Failure message from response is : {requestFailure.Message}");
                requeststopwatch.Stop();
                ResponseTime = requeststopwatch.Elapsed.TotalMilliseconds;
                Console.WriteLine($"Time taken by request to execute is : {ResponseTime} ms ");
                Response = (HttpWebResponse)requestFailure.Response;
                Console.WriteLine($"Api Request failed due to error : {requestFailure.Message}");
            }
            return(Response, ResponseTime);
        }
Exemplo n.º 47
0
 public HttpWebHelper(string uri, string method, string username, string password) : this(true)
 {
     this.credentialCache = new CredentialCache();
     this.credentialCache.Add(new Uri(uri), method, new NetworkCredential(username, password));
 }
Exemplo n.º 48
0
	public HttpWebResponse Submit (Uri uri, FSpot.ProgressItem progress_item) 
	{
		this.Progress = progress_item;
		Request = (HttpWebRequest) WebRequest.Create (uri);
		CookieCollection cookie_collection = Cookies.GetCookies (uri);

		if (uri.UserInfo != null && uri.UserInfo != String.Empty) {
			NetworkCredential cred = new NetworkCredential ();
			cred.GetCredential (uri, "basic");
			CredentialCache credcache = new CredentialCache();
			credcache.Add(uri, "basic", cred);
			
			Request.PreAuthenticate = true;
			Request.Credentials = credcache;	
		}

		Request.ServicePoint.Expect100Continue = expect_continue;

		Request.CookieContainer = new CookieContainer ();
		foreach (Cookie c in cookie_collection) {
			if (SuppressCookiePath) 
				Request.CookieContainer.Add (new Cookie (c.Name, c.Value));
			else
				Request.CookieContainer.Add (c);
		}

		Request.Method = "POST";
		Request.Headers["Accept-Charset"] = "utf-8;";
		
		//Request.UserAgent = "F-Spot Gallery Remote Client";
		Request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040626 Firefox/0.9.1";

		Request.Proxy = WebProxy.GetDefaultProxy ();

		if (multipart) {
			GenerateBoundary ();
			Request.ContentType = "multipart/form-data; boundary=" + boundary;
			Request.Timeout = Request.Timeout * 3;

			long length = 0;
			for (int i = 0; i < Items.Count; i++) {
				FormItem item = (FormItem)Items[i];
				
				length += MultipartLength (item);
			}
			length += end_boundary.Length + 2;
			
			//Request.Headers["My-Content-Length"] = length.ToString ();
			if (Buffer == false) {
				Request.ContentLength = length;	
				Request.AllowWriteStreamBuffering = false;
			}
		} else {
			Request.ContentType = "application/x-www-form-urlencoded";
		}
		
		stream_writer = new StreamWriter (Request.GetRequestStream ());
		
		first_item = true;
		for (int i = 0; i < Items.Count; i++) {
			FormItem item = (FormItem)Items[i];
			
			Write (item);
		}
		
		if (multipart)
			stream_writer.Write (end_boundary + "\r\n");
		
		stream_writer.Flush ();
		stream_writer.Close ();

		HttpWebResponse response; 

		try {
			response = (HttpWebResponse) Request.GetResponse ();
			
			//Console.WriteLine ("found {0} cookies", response.Cookies.Count);
			
			foreach (Cookie c in response.Cookies) {
				Cookies.Add (c);
			}
		} catch (WebException e) {
			if (e.Status == WebExceptionStatus.ProtocolError 
			    && ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.ExpectationFailed && expect_continue) {
				e.Response.Close ();
				expect_continue = false;
				return Submit (uri, progress_item);
			}
			
			throw new WebException (Mono.Unix.Catalog.GetString ("Unhandled exception"), e);
		}

		return response;
	}
Exemplo n.º 49
0
 /// <summary>
 /// Constructor
 /// </summary>
 public CswClient()
 {
     _credentialCache = new CredentialCache();
     _cookieContainer = new CookieContainer();
 }
Exemplo n.º 50
0
        static void Main(string[] args)
        {
            #region Working with StringBuilder
            StringBuilder SomeString       = new StringBuilder();
            StringBuilder SomeStringToPlay = new StringBuilder();

            string SourceString = "X", DestinationString = "";
            int    iteration = 10;


            //Fun with StringBuilder

            //define StopWatch
            Stopwatch sw = new Stopwatch();

            //define new ClString object
            var objStrBuilder = new ClString();
            sw.Start();
            for (int i = 0; i < iteration; i++)
            {
                //display progess in %

                /*
                 * if (i % 100 == 0)
                 * {
                 *      Console.Write("{0:p2}",(double)i/iteration);
                 * }
                 */
                DestinationString = objStrBuilder.StrAppend(DestinationString, SourceString);
            }

            sw.Stop();
            Console.WriteLine();
            //Console.WriteLine("SomeString: {0}", DestinationString);
            Console.WriteLine("Elapsed time using StringBuilder Method: {0:n10}", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Number of objects: {0}", DestinationString.Length);


            //reset SB strings
            SomeString.Clear();
            SomeStringToPlay.Clear();


            //stopwatch for classis string operation
            sw.Reset();
            sw.Start();
            DestinationString = "";
            for (int i = 0; i < iteration; i++)
            {
                DestinationString += SourceString;
            }
            sw.Stop();
            Console.WriteLine("Elapsed time using classic string operation: {0:n10}", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Number of objects: {0}", DestinationString.Length);

            //stopwatch for string with StringBuilder
            sw.Reset();
            sw.Start();
            DestinationString = "";
            for (int i = 0; i < iteration; i++)
            {
                SomeString.Append("X");
            }
            DestinationString = SomeString.ToString();
            sw.Stop();
            Console.WriteLine("Elepsed time using StringBuilder: {0:n10}", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Number of objects: {0}", DestinationString.Length);

            //fun with StringBuilder
            SomeStringToPlay.AppendFormat("Some text {0}. Next text will be on new line: \n {1}", "StringBuilder", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            SomeStringToPlay.AppendLine();
            SomeStringToPlay.AppendLine("New line with text");
            SomeStringToPlay.Append("\n");
            SomeStringToPlay.Append("end of game");

            //normal string operations
            Console.WriteLine("End presseent:{0}", SomeStringToPlay.ToString().Contains("end"));
            //SomeStringToPlay - show on console
            Console.WriteLine(SomeStringToPlay);

            //Empty string
            SomeStringToPlay.Clear();

            //Add some text to play with
            SomeStringToPlay.AppendLine("This is text to plat with");

            //Replace 'e' by 'E'
            SomeStringToPlay.Replace("e", "E");

            //SomeStringToPlay - show on console
            Console.WriteLine("Replace 'e' by 'E': {0}", SomeStringToPlay);

            //Replace 'plat' by 'play'
            SomeStringToPlay.Replace("plat", "play");

            //SomeStringToPlay - show on console
            Console.WriteLine("'plat' by 'play': {0}", SomeStringToPlay);

            //Numbers
            double BigNumber = 23132156464.1534564;
            Console.WriteLine("Exponatial - E2: {0:E2}", BigNumber);
            Console.WriteLine("Exponatial - E4: {0:E4}", BigNumber);
            #endregion

            #region Work with files

            var objDir = new ClFile();
            //get current dir
            string path = objDir.ShowCurrentPath().ToString();
            Console.WriteLine("DIR 1:{0}", path);
            Console.WriteLine("DIR 2:{0}", objDir.ShowCurrentPath());

            //get all subdirs
            var MyDir      = Directory.GetCurrentDirectory();
            var CurrentDir = "C:\\DataFolder\\Downloads";


            if (Directory.Exists(CurrentDir))
            {
                var DirList  = Directory.GetDirectories(CurrentDir);
                var FileList = Directory.GetFiles(CurrentDir);

                /*foreach (var DirItem in DirList)
                 * {
                 *      Console.WriteLine("DIR: {0}", DirItem);
                 * }*/
                Console.WriteLine("Number of DIRS: {0}", DirList.Count());
                Console.WriteLine("Number of FILES:{0}", FileList.Count());

                //work with all dirs - enum type
                foreach (var _dir in DirList)
                {
                    var MyDirInfo = new DirectoryInfo(_dir);

                    //List only Dirs with Extension
                    if (!(MyDirInfo.Extension.Length == 0))
                    {
                        Console.WriteLine("Name: {0}", MyDirInfo.Name);
                        Console.WriteLine("FullName: {0}", MyDirInfo.FullName);
                        Console.WriteLine("Extension: {0}", MyDirInfo.Extension);
                    }
                }
                //work with all files - enum type
                long TotalSize = 0;
                foreach (var _file in FileList)
                {
                    var MyFileInfo = new FileInfo(_file);

                    //List only *.exe files
                    if ((MyFileInfo.Extension == ".exe"))
                    {
                        Console.WriteLine("File in DIR:{0}", MyFileInfo.DirectoryName);
                        Console.WriteLine("Name: {0}", MyFileInfo.Name);
                        Console.WriteLine("FullName: {0}", MyFileInfo.FullName);
                        Console.WriteLine("Extension: {0}", MyFileInfo.Extension);
                        Console.WriteLine("Lenght: {0:N}", MyFileInfo.Length);
                        TotalSize += MyFileInfo.Length;
                    }
                }
                Console.WriteLine("Number of files: {0:D5}, Total Size of files: {1:N}", FileList.Count(), TotalSize);

                //Lambda try
                var LambdaFiles = FileList.Where(item => item.Contains(".exe")).Select(item => item.ToString());
                foreach (var _file in LambdaFiles)
                {
                    Console.WriteLine("Lambda Files: {0}", _file);
                }
            }
            else
            {
                Console.WriteLine("DIR: {0} dont exist", CurrentDir);
            }
            #endregion

            #region Work with FileStream
            //FileStream read
            string FilePath    = "C:\\DataFolder\\Downloads\\TestShare\\BigFile.txt";
            string FilePathNew = "C:\\DataFolder\\Downloads\\TestShare\\BigFileNew.txt";

            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                int bytesToRead      = 1;
                int currentPossition = 0;

                byte[] bytes    = new byte[fs.Length];
                byte[] tempFile = new byte[bytesToRead];

                //read 1 by 1 byte from file
                while (currentPossition < (int)fs.Length)
                {
                    int readData = fs.Read(bytes, currentPossition, bytesToRead);
                    if (readData == 0)
                    {
                        break;
                    }
                    //Console.WriteLine("Possition: {0} - Data: {1}", currentPossition, (char)bytes[currentPossition]);
                    currentPossition += bytesToRead;
                }

                //write stream

                /*
                 * using (FileStream fsWrite = new FileStream(FilePathNew, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                 * {
                 *      fsWrite.Write(bytes, 0, (int)fs.Length);
                 * }
                 */


                //list bytes content

                /*
                 * foreach (byte bit in bytes)
                 * {
                 *      Console.WriteLine((char)bit);
                 * }
                 */
            }
            #endregion

            #region Work with files using SYSTEM.NET

            /*
             * Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
             * string computer_name = Environment.MachineName;
             * //not working as sharing not possible
             * var fileRequest = WebRequest.Create(@"file://"+computer_name+"/TestShare/BigFile.txt");
             * fileRequest.Method = "POST";
             * Console.WriteLine(fileRequest.GetType());
             * System.IO.Stream readStream = null;
             * byte[] byteArray = new byte[10];
             * string TextToWrite = "Text to write to file";
             * //fileRequest.ContentLength = TextToWrite.Length;
             *
             * try
             * {
             *      readStream = fileRequest.GetRequestStream();
             * }
             * catch (Exception)
             * {
             *      Console.WriteLine("Muhahaha !!!");
             *      throw;
             *
             * }
             * readStream.SetLength(fileRequest.ContentLength);
             * readStream.Read(byteArray, 0, 10);
             *
             * readStream.Close();
             */
            #endregion


            #region Work with Secure String
            SecureString SecurelyStoredPassword = new SecureString();
            Console.WriteLine("Enter User Name:");
            string userName = Console.ReadLine();
            Console.WriteLine("Enter User Password:"******"";
            foreach (char ch in samplePassword.ToCharArray())
            {
                SecurelyStoredPassword.AppendChar(ch);
            }
            SecurelyStoredPassword.MakeReadOnly();

            Console.WriteLine("User Name: {0}", userName);
            Console.WriteLine("User Password: {0}", SecurelyStoredPassword.ToString());

            NetworkCredential myCred      = new NetworkCredential(userName, SecurelyStoredPassword, userDomain);
            CredentialCache   myCredCache = new CredentialCache();

            myCredCache.Add(new Uri("https://myService.com/GiveMeSomething.svc"), "Basic", myCred);
            myCredCache.Add(new Uri("https://anotherMyService.com/GiveMeSomethingElse.svc"), "Basic", myCred);

            WebRequest myWebRequest = WebRequest.Create("https://google.com");
            myWebRequest.Credentials = myCredCache;
            WebResponse myWebResponse = myWebRequest.GetResponse();

            Console.WriteLine("Server: {0}", ((System.Net.HttpWebResponse)myWebResponse).Server);
            Console.WriteLine("Absolute Uri: {0}", myWebResponse.ResponseUri.AbsoluteUri);
            Console.WriteLine("Charecter Set: {0}", ((System.Net.HttpWebResponse)myWebResponse).CharacterSet);
            Console.WriteLine("Protocol Version: {0}", ((System.Net.HttpWebResponse)myWebResponse).ProtocolVersion);
            //Looks like WebResponce and HttpWebResponse are two different classes :)

            SecurelyStoredPassword.Dispose();


            #endregion


            //press any key
            Console.WriteLine("press any key ...");
            Console.ReadKey(true);
        }
Exemplo n.º 51
0
    public static void SendAnalytics(BuildTarget target, string path)
    {
        if (Application.isPlaying)
        {
            return;
        }
        try
        {
            string appID = "", bundleID = "", prodName, compName, gameVer, unityVer, isPro, targetPlat;
            string url      = "http://api.fusepowered.com/unity/buildstats.php";
            string baseJson = @"{
							""game_id"" : ""{{game_id}}"",
							""bundle_id"" : ""{{bundle_id}}"",
							""product_name"" : ""{{product_name}}"",
							""company_name"" : ""{{company_name}}"",
							""game_ver"" : ""{{game_ver}}"",
							""platform"": 
								{
									""version"": ""{{version}}"",
									""is_pro"": ""{{is_pro}}"",
									""target"": ""{{target}}""
								}
							}"                            ;

            //App ID
            var fuse = LoadAsset <FuseSDK>("Assets/FuseSDK/FuseSDK.prefab");
            if (fuse != null)
            {
#if UNITY_IOS
                appID = fuse.iOSAppID;
#elif UNITY_ANDROID
                appID = fuse.AndroidAppID;
#endif
            }

            //Bundle ID of currently selected platform
#if UNITY_5_6_OR_NEWER
            bundleID = PlayerSettings.applicationIdentifier;
#else
            bundleID = PlayerSettings.bundleIdentifier;
#endif

            //Product name
            prodName = PlayerSettings.productName;

            //Company Name
            compName = PlayerSettings.companyName;

            //Game Ver
            gameVer = PlayerSettings.bundleVersion;

            //Unity version
            unityVer = Application.unityVersion;

            //Unity Pro
            isPro = PlayerSettings.advancedLicense ? "1" : "0";

            //Target platform
            targetPlat = target.ToString();

            //Fill out json
            string json = System.Text.RegularExpressions.Regex.Replace(baseJson, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1")
                          .Replace("{{game_id}}", appID)
                          .Replace("{{bundle_id}}", bundleID)
                          .Replace("{{product_name}}", prodName)
                          .Replace("{{company_name}}", compName)
                          .Replace("{{game_ver}}", gameVer)
                          .Replace("{{version}}", unityVer)
                          .Replace("{{is_pro}}", isPro)
                          .Replace("{{target}}", targetPlat);

            string query = "d=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(json));

            WebRequest request = WebRequest.Create(url);
            var        creds   = new CredentialCache();
            creds.Add(new Uri(url), "Basic", new NetworkCredential("jimmyjimmyjango", "awP2yTECEbXErKcn"));             //oh noes, you gots our passw0rds
            request.Credentials   = creds;
            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = query.Length;
            request.Timeout       = 500;

            Stream dataStream = request.GetRequestStream();
            byte[] data       = Encoding.UTF8.GetBytes(query);
            dataStream.Write(data, 0, data.Length);
            dataStream.Close();

            request.BeginGetResponse(new AsyncCallback(_ => {}), null);
        }
        catch {}
    }
Exemplo n.º 52
0
        public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
                out port,
                requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
                expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            const string BasicAuth = "Basic";
            if (wrapCredsInCache)
            {
                Assert.IsAssignableFrom<NetworkCredential>(creds);
                var cache = new CredentialCache();
                cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds);
                creds = cache;
            }

            using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) })
            using (var client = new HttpClient(handler))
            {
                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth);
                string expectedAuth =
                    nc == null || nc == CredentialCache.DefaultCredentials ? null :
                    string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
                    $"{nc.Domain}\\{nc.UserName}:{nc.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
Exemplo n.º 53
0
        /// <summary>
        /// start the SiteAddForm
        /// make a dictionary of the added site
        /// subscribe to events from the sites in the dictionary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            SiteAddForm form = new SiteAddForm();

            if (form.ShowDialog() == DialogResult.OK)
            {
                Item ii = form.SelectedSiteItem;
                if (_dicServerObjects.ContainsKey(form.SelectedSiteItem.FQID.ServerId.Id))
                {
                    MessageBox.Show(
                        form.SelectedSiteItem.Name + " is allready in the system and will not be added again.",
                        "Multi-site StatusViewer adding servers",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning
                        );
                }
                else
                {
                    _credentialCache = form.CredentialCache;
                    string myName = form.SelectedSiteItem.FQID.ServerId.ServerHostname + " - " +
                                    form.SelectedSiteItem.Name;

                    TreeNode tn = treeViewSites.Nodes.Add(myName);
                    tn.Tag = form.SelectedSiteItem;
                    treeViewSites.ShowNodeToolTips = true;

                    _dicServerObjects.Add(form.SelectedSiteItem.FQID.ServerId.Id, new ServerObject()
                    {
                        Name          = form.SelectedSiteItem.Name,
                        SiteItem      = form.SelectedSiteItem,
                        SitesTreeNode = tn
                    });
                    if (form.IncludeChildSites)
                    {
                        foreach (Item site in form.SelectedSiteItem.GetChildren())
                        {
                            AddSiteInfo(site, form.CredentialCache, tn);
                        }
                    }
                    treeViewSites.ShowNodeToolTips = true;
                    treeViewSites.Refresh();

                    bool startTimer = false;
                    foreach (ServerObject smo in _dicServerObjects.Values)
                    {
                        if (AddServer(smo))
                        {
                            StartMessaging(smo);
                        }
                        else
                        {
                            startTimer = true; //todo
                            TreeNode stn = smo.SitesTreeNode;
                            if (IsHandleCreated && !IsDisposed)
                            {
                                this.BeginInvoke(new MethodInvoker(delegate()
                                {
                                    stn.ToolTipText = "not logged in";
                                    stn.ForeColor   = Color.Red;
                                }
                                                                   ));
                            }
                        }
                    }
                    if (startTimer)
                    {
                        timer1.Interval = 30000;
                        timer1.Enabled  = true;
                        timer1.Start();
                    }
                }
            }
        }
Exemplo n.º 54
0
        private resp _doReq(string url, string method, HttpStatusCode expectedCode, string payload = null, TimeSpan timeout = default(TimeSpan))
        {
            if (timeout == default(TimeSpan))
            {
                timeout = TimeSpan.FromMinutes(5);
            }
            lock (ReqLock)
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Timeout = (int)timeout.TotalMilliseconds;
                req.Method  = method;
                CredentialCache cred = new CredentialCache();
                cred.Add(new Uri(url), "Basic", new NetworkCredential(_username, _password));
                req.Credentials     = cred;
                req.PreAuthenticate = true;

                if (payload != null)
                {
                    req.ContentType = "application/json";
                    Byte[] dataBytes = Encoding.ASCII.GetBytes(payload);
                    req.ContentLength = dataBytes.Length;
                    using (Stream stream = req.GetRequestStream())
                    {
                        stream.Write(dataBytes, 0, dataBytes.Length);
                    }
                }

                try
                {
                    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                    {
                        using (Stream respStream = resp.GetResponseStream())
                        {
                            using (StreamReader respStreamReader = new StreamReader(respStream))
                            {
                                string contentString = respStreamReader.ReadToEnd();

                                if (resp.StatusCode != expectedCode)
                                {
                                    throw nasAccessException.create(resp, url, contentString);
                                }

                                return(new resp()
                                {
                                    text = contentString
                                });
                            }
                        }
                    }
                }
                catch (WebException e)
                {
                    HttpWebResponse resp = e.Response as HttpWebResponse;

                    if (resp == null)
                    {
                        throw new nasAccessException(e.Message);
                    }

                    if (resp.StatusCode == (HttpStatusCode)510)
                    {
                        // Oh no! ctld has run out of ports! Time to recompile the kernel!
                        throw new nasServerFullException("ctld is full! Delete some iscsi exports or rebuild the kernel with increased limits.");
                    }

                    using (Stream respStream = resp.GetResponseStream())
                    {
                        if (respStream == null)
                        {
                            throw new nasAccessException(e.Message);
                        }

                        using (StreamReader respStreamReader = new StreamReader(respStream))
                        {
                            string contentString = respStreamReader.ReadToEnd();
                            throw nasAccessException.create(resp, url, contentString);
                        }
                    }
                }
            }
        }
Exemplo n.º 55
0
        public ConcurrentDictionary <string, object> curl_getPost_continue(ConcurrentDictionary <string, object> C, string URL, string postData, ConcurrentDictionary <string, object> options = null)
        {
            ConcurrentDictionary <string, object> output = new ConcurrentDictionary <string, object>();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.Proxy           = null;
            request.UserAgent       = "user_agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36";
            request.CookieContainer = (CookieContainer)C["cookies"];
            C["cookies"]            = request.CookieContainer;
            try
            {
                if (options != null)
                {
                    if (options.ContainsKey("login_id") && options.ContainsKey("login_pd"))
                    {
                        CredentialCache mycache = new CredentialCache();
                        Uri             uri     = new Uri(URL);
                        mycache.Add(uri, "Basic", new NetworkCredential(options["login_id"].ToString(), options["login_pd"].ToString()));
                        request.Credentials = mycache;
                    }
                    if (options.ContainsKey("timeout"))
                    {
                        request.Timeout = Convert.ToInt32(options["timeout"]);
                    }
                    if (options.ContainsKey("user_agent"))
                    {
                        request.UserAgent = options["user_agent"].ToString();
                    }

                    //file_put_contents(pwd() + "\\log\\cookie.txt", json_encode(C["cookies"]));
                    if (options.ContainsKey("cookie"))
                    {
                        //request.Headers.Add("Cookie", options["cookie"].ToString());
                        //request.CookieContainer.Add( = options["cookie"].ToString();
                        //request.CookieContainer = new CookieContainer();

                        /*
                         * List<Cookie> LC = cookieStrToCookie(options["cookie"].ToString());
                         * for (int i = 0, max_i = LC.Count; i < max_i; i++)
                         * {
                         *  request.CookieContainer.Add(LC[i]);
                         * }
                         */
                        Uri uri = new Uri(URL);
                        request.CookieContainer.SetCookies(uri, options["cookie"].ToString());
                    }
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (postData == "")
                {
                    //GET
                    Stream stream = response.GetResponseStream();
                    output["data"] = ReadStream(stream, 32765);
                    stream.Close();
                }
                else
                {
                    //Post
                    byte[] data = Encoding.UTF8.GetBytes(postData);
                    request.Method        = "POST";
                    request.ContentType   = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;

                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                        stream.Close();
                    }
                }
                output["realCookie"] = response.Headers[HttpResponseHeader.SetCookie];
                response.Close();
                output["reason"] = "";
                return(output);
            }
            catch (Exception ex)
            {
                output["data"]   = new byte[0];
                output["reason"] = ex.Message + "\n\r" + ex.StackTrace;
                return(output);
            }
        }