/// <summary>
		/// Executa o filtro.
		/// </summary>
		public bool Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
		{
			if (!Enabled)
				return true;

			UserAgent ua = null;

			var uaString = context.UnderlyingContext.Request.UserAgent;
			if (uaString != null)
			{
				ua = (UserAgent) cache[uaString];
				if (ua == null)
					cache[uaString] = ua = new UserAgent(uaString);
			}

			if (IsValid(ua))
				return true;

			if (!logged)
			{
				Log.Error("Tentativa de acesso através de browser não suportado: {0}", uaString);
				logged = true;
			}

			controller.PropertyBag["invalidGecko"] = true;
			if (!Redirect)
				return true;

			throw new Exception("redir: " + Redirect);

			//RedirectToNotice(controller);
			//return false;
		}
Example #2
0
        public void SetProgramUserAgentAndReturnFullUserAgent()
        {
            const string programName = "UATest";
            var ua = new UserAgent(programName);

            var currentVersion = GetType().Assembly.GetName().Version;
            var libVersion = Assembly.GetAssembly(ua.GetType()).GetName().Version;
            var expectedResults = String.Format("{0}/{1} (Windows NT 6.3; WOW64) DDNS/{2}",
                                                programName,
                                                currentVersion.ToString(2),
                                                libVersion.ToString(2));
            Assert.AreEqual(expectedResults, ua.ToString());
        }
Example #3
0
        public static string Get(string url, Encoding encoding, CookieCollection cookies, UserAgent userAgent, string referer)
        {
            HttpWebResponse response = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = dictUserAgent[userAgent];
                request.Accept = "text/html";
                request.Referer = referer;
                request.KeepAlive = true;
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                response = (HttpWebResponse)request.GetResponse();
                return new StreamReader(response.GetResponseStream(), encoding).ReadToEnd();
                //using (Stream stream = response.GetResponseStream())
                //{
                //    using (StreamReader reader = new StreamReader(stream, charset))
                //    {
                //        return reader.ReadToEnd();
                //    }
                //}
            }
            catch
            {
                return "";
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Example #4
0
        public void IsEmpty()
        {
            var agent = new UserAgent("");

            Assert.True(agent.IsNullOrEmpty());
        }
Example #5
0
 public override Timer CreateTimer(UserAgent app, SIPStack stack)
 {
     return(new Timer(app));
 }
Example #6
0
 public override string[] Authenticate(UserAgent ua, Header header, SIPStack sipStack)
 {
     throw new NotImplementedException();
 }
Example #7
0
        /// <summary>
        /// Browse the folder
        /// </summary>
        /// <param name="startIndex">start index</param>
        /// <param name="requestedCount">requested count</param>
        /// <param name="userAgent">user agent</param>
        /// <returns>the browse result</returns>
        public override BrowseResult Browse(uint startIndex, uint requestedCount, UserAgent userAgent)
        {
            var entries = new EntryCollection();

            entries.AddRange(Children);
            if (!String.IsNullOrWhiteSpace(Path))
            {
                try
                {
                    bool isFreeboxV5 = (userAgent == UserAgent.FreeboxV5);
                    foreach (var file in Directory.GetFiles(Path, "*.*", SearchOption.TopDirectoryOnly))
                    {
                        try
                        {
                            var f = FileFactory.CreateFile(file);
                            if (f is IContainer)
                            {
                                var entry = ((IContainer)f).GetContent(isFreeboxV5);
                                if (entry == null)
                                {
                                    continue;
                                }
                                if (!(entry is IMedia))
                                {
                                    entries.Add(entry);
                                    continue;
                                }
                                f = (IMedia)entry;
                            }

                            if (f.MediaKind != null && (f.MediaKind & MediaKind) > 0)
                            {
                                entries.Add((Entry)f);
                            }
                        }
                        catch (Exception ex)
                        {
                            Utils.WriteException(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteException(ex);
                }

                try
                {
                    foreach (var directory in Directory.GetDirectories(Path, "*.*", SearchOption.TopDirectoryOnly))
                    {
                        try
                        {
                            var folder = new Folder()
                            {
                                UsePathAsId = true, Path = directory
                            };
                            if (!folder.IsHidden)
                            {
                                entries.Add(folder);
                            }
                        }
                        catch (Exception ex)
                        {
                            Utils.WriteException(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteException(ex);
                }
            }

            entries.Sort(new Comparison <Entry>((e1, e2) =>
            {
                if (e1 is FolderBase && !(e2 is FolderBase))
                {
                    return(-1);
                }
                if (e2 is FolderBase && !(e1 is FolderBase))
                {
                    return(1);
                }
                if (e1.Label == null)
                {
                    return(e2.Label == null ? 0 : -1);
                }
                return(e1.Label.CompareTo(e2.Label));
            }));

            var browseResult = new BrowseResult()
            {
                TotalCount = entries.Count
            };
            int i = 0;

            foreach (Entry entry in entries)
            {
                if (i == startIndex)
                {
                    if (browseResult.Entries.Count < requestedCount)
                    {
                        browseResult.Entries.Add(entry);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    i += 1;
                }
            }
            return(browseResult);
        }
Example #8
0
        // TODO: Try to merge the shared parts between ConfigureWebRequest and ConfigureAsyncWebRequest (quite a bit of code
        // TODO: duplication at the moment).
        private HttpWebRequest ConfigureWebRequest(string method, Uri url)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(url);

#if !PocketPC
            webRequest.UseDefaultCredentials = UseDefaultCredentials;
#endif
            webRequest.PreAuthenticate            = PreAuthenticate;
            ServicePointManager.Expect100Continue = false;

            AppendHeaders(webRequest);
            AppendCookies(webRequest);

            webRequest.Method = method;

            // make sure Content-Length header is always sent since default is -1
            if (!HasFiles && !AlwaysMultipartFormData)
            {
                webRequest.ContentLength = 0;
            }

            webRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None;

            if (ClientCertificates != null)
            {
                webRequest.ClientCertificates.AddRange(ClientCertificates);
            }

            if (UserAgent.HasValue())
            {
                webRequest.UserAgent = UserAgent;
            }

            if (Timeout != 0)
            {
                webRequest.Timeout = Timeout;
            }

            if (ReadWriteTimeout != 0)
            {
                webRequest.ReadWriteTimeout = ReadWriteTimeout;
            }

            if (Credentials != null)
            {
                webRequest.Credentials = Credentials;
            }

            if (Proxy != null)
            {
                webRequest.Proxy = Proxy;
            }

            webRequest.AllowAutoRedirect = FollowRedirects;
            if (FollowRedirects && MaxRedirects.HasValue)
            {
                webRequest.MaximumAutomaticRedirections = MaxRedirects.Value;
            }

            return(webRequest);
        }
Example #9
0
        public ASCommandResponse GetResponse()
        {
            string StatusCode = string.Empty;
            string Meaning    = string.Empty;
            string Cause      = string.Empty;
            string Resolution = string.Empty;

            EASTester.EasHelp oHelp = new EASTester.EasHelp();

            GenerateXMLPayload();

            //if (ProtocolVersion == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Protocol version not specified.");

            //if (ProtocolVersion == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - EAS Protocol version must be set");

            //if (WbxmlBytes == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Request is empty.");

            //if (Server == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Server must be specified.");

            //if (Credentials == null && useCertificateAuthentication == false)
            //    throw new InvalidDataException("ASCommandRequest not initialized for authentication.");

            //if (useCertificateAuthentication == true && certificateFile.Length == 0)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Certificate file must be specified.");

            string uriString = string.Format("{0}//{1}/Microsoft-Server-ActiveSync?{2}",
                                             useSSL ? "https:" : "http:", server, RequestLine);
            Uri serverUri = new Uri(uriString);

            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uriString);

            //httpReq.ClientCertificates.
            httpReq.Method      = "POST";
            httpReq.ContentType = "application/vnd.ms-sync.wbxml";

            // Handle any certificate errors on the certificate from the server.
            //ServicePointManager.CertificatePolicy = new CertPolicy();

            //bool bSettingCredsWasOK = false;
            if (useCertificateAuthentication == true)
            {
                // https://support.microsoft.com/en-us/kb/895971
                try
                {
                    httpReq.UseDefaultCredentials = false;
                    X509Certificate oX509Certificate = null;

                    //oX509Certificate = new X509Certificate.CreateFromCertFile(certificateFile);

                    oX509Certificate = new X509Certificate(certificateFile, certificatePassword);
                    httpReq.ClientCertificates.Add(oX509Certificate);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception: \r\n" + ex.ToString(), "Error setting certificate authentication.");
                    return(null);
                }
            }
            else
            {
                try
                {
                    CredentialCache creds = new CredentialCache();
                    creds.Add(serverUri, "Basic", credential);  // Using Basic authentication
                    httpReq.Credentials = creds;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception: \r\n" + ex.ToString(), "Error setting specified credentials.");
                    return(null);
                }
            }



            if (SpecifyProxySettings == true)
            {
                WebProxy oWebProxy = null;
                oWebProxy = new WebProxy(ProxyServer, ProxyPort);
                //oWebProxy.BypassProxyOnLocal = BypassProxyForLocalAddress;

                if (OverrideProxyCredntials == true)
                {
                    if (ProxyUser.Trim().Length == 0)
                    {
                        oWebProxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        if (ProxyDomain.Trim().Length == 0)
                        {
                            oWebProxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassword);
                        }
                        else
                        {
                            oWebProxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassword, ProxyDomain);
                        }
                    }
                }
                else
                {
                    oWebProxy.UseDefaultCredentials = true;
                }

                httpReq.Proxy = oWebProxy;
            }

            if (UserAgent.Trim().Length != 0)
            {
                httpReq.UserAgent = UserAgent;
            }

            if (!UseEncodedRequestLine)
            {
                httpReq.Headers.Add("MS-ASProtocolVersion", ProtocolVersion);
                httpReq.Headers.Add("X-MS-PolicyKey", PolicyKey.ToString());
            }

            try
            {
                Stream requestStream = httpReq.GetRequestStream();
                requestStream.Write(WbxmlBytes, 0, WbxmlBytes.Length);
                requestStream.Close();

                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();

                //float iisStatusCode = (float)httpResp.StatusCode;


                ASCommandResponse response = WrapHttpResponse(httpResp);

                httpResp.Close();

                //StatusCode = iisStatusCode.ToString();
                //Meaning = string.Empty;
                //Cause = string.Empty;
                //Resolution = string.Empty;
                //oHelp.GetHttpStatusInfo(StatusCode, ref Meaning, ref Cause, ref Resolution);

                //MessageBox.Show("IIS Resposne Code: " + StatusCode + "\r\nDescription: " + Meaning);

                return(response);
            }
            catch (WebException wex)
            {
                MessageBox.Show("Exception: \r\n" + wex.ToString(), "Error");

                return(null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: \r\n" + ex.ToString(), "Error");

                return(null);
            }
        }
Example #10
0
 public void SetUp()
 {
     userAgent = new UserAgent();
 }
Example #11
0
 protected virtual void queueNewOperation(UserAgent _user)
 {
 }
Example #12
0
 public void Start(UserAgent _user)
 {
     checkData();
     startExecute();
     queueNewOperation(_user);
 }
		/// <summary>
		/// Verifica se o <see cref="UserAgent"/> é válido.
		/// </summary>
		/// <param name="ua">O <see cref="UserAgent"/>. Pode ser nulo e inválido.</param>
		/// <returns>
		/// Verdadeiro se o <see cref="UserAgent"/> deva ser
		/// considerado válido, falso caso contrário.
		/// </returns>
		protected virtual bool IsValid(UserAgent ua)
		{
			return ua != null && ua.Valid && ua.GeckoRelease >= MinGeckoRelease;
		}
Example #14
0
        public void IsLower()
        {
            var agent = new UserAgent("ABC");

            Assert.Equal("abc", agent.ToLower());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:SIPLib.SIP.ServerTransaction" /> class.
 /// </summary>
 /// <param name="app">The useragent</param>
 public ServerTransaction(UserAgent app)
     : base(app)
 {
     Server = true;
 }
        private void HandleFlexClientStreamingOpenRequest(HttpRequest request, HttpResponse response, IClient flexClient)
        {
            Session session = FluorineContext.Current.Session as Session;

            if (session == null)
            {
                string msg = string.Format("Cannot grant streaming connection when ASP.NET session state is disabled", this.Id);
                if (log.IsWarnEnabled)
                {
                    log.Warn(msg);
                }
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }
            if (!_canStream || !session.CanStream)
            {
                string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id);
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }

            bool canStream = false;

            lock (this.SyncRoot) {
                _streamingClientsCount.Increment();
                if (_streamingClientsCount.Value == this.MaxStreamingClients)
                {
                    canStream  = true;                    // This thread got the last spot.
                    _canStream = false;
                }
                else if (_streamingClientsCount.Value > this.MaxStreamingClients)
                {
                    canStream = false;                     // This thread lost the last spot.
                    _streamingClientsCount.Decrement();    // We're not going to grant the streaming right to the client.
                }
                else
                {
                    // Allow this thread to stream.
                    canStream = true;
                }
            }
            if (!canStream)
            {
                string msg = string.Format("Cannot service streaming request, max-streaming-clients reached in endpoint {0}", this.Id);
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }

            UserAgent userAgent = this.ChannelDefinition.Properties.UserAgentSettings[request.Browser.Browser];

            if (userAgent != null)
            {
                lock (session.SyncRoot) {
                    session.MaxConnectionsPerSession = userAgent.MaxStreamingConnectionsPerSession;
                }
            }

            lock (session.SyncRoot) {
                session.StreamingConnectionsCount++;
                if (session.StreamingConnectionsCount == session.MaxConnectionsPerSession)
                {
                    canStream         = true;             // This thread got the last spot in the session.
                    session.CanStream = false;
                }
                else if (session.StreamingConnectionsCount > session.MaxConnectionsPerSession)
                {
                    canStream = false;
                    session.StreamingConnectionsCount--;
                    _streamingClientsCount.Decrement();
                }
                else
                {
                    canStream = true;
                }
            }
            if (!canStream)
            {
                string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id);
                try {
                    HandleBadRequest(msg, HttpContext.Current.Response);
                } catch (HttpException) { }
                return;
            }

            EndpointPushNotifier notifier = null;

            try {
                response.ContentType = ContentType.AMF;
                response.AppendHeader("Cache-Control", "no-cache");
                response.AppendHeader("Pragma", "no-cache");
                response.AppendHeader("Connection", "close");
                //response.AppendHeader("Transfer-Encoding", "chunked");
                response.Flush();

                // Setup for specific user agents.
                byte[] kickStartBytesToStream = null;
                int    kickStartBytes         = userAgent != null ? userAgent.KickstartBytes : 0;
                if (kickStartBytes > 0)
                {
                    // The minimum number of actual bytes that need to be sent to kickstart, taking into account transfer-encoding overhead.
                    try {
                        int chunkLengthHeaderSize = System.Text.Encoding.ASCII.GetBytes(System.Convert.ToString(kickStartBytes, 0x10)).Length; //System.Text.ASCIIEncoding.ASCII.GetBytes(kickStartBytes.ToString("X")).Length;
                        int chunkOverhead         = chunkLengthHeaderSize + 4;                                                                 // 4 for the 2 wrapping CRLF tokens.
                        int minimumKickstartBytes = kickStartBytes - chunkOverhead;
                        kickStartBytesToStream = new byte[(minimumKickstartBytes > 0) ? minimumKickstartBytes : kickStartBytes];
                    } catch {
                        kickStartBytesToStream = new byte[kickStartBytes];
                    }
                }
                if (kickStartBytesToStream != null)
                {
                    StreamChunk(kickStartBytesToStream, response);
                }
                try {
                    notifier = new EndpointPushNotifier(this, flexClient);
                    lock (_currentStreamingRequests.SyncRoot) {
                        _currentStreamingRequests.Add(notifier.Id, notifier);
                    }
                    // Push down an acknowledgement for the 'connect' request containing the unique id for this specific stream.
                    AcknowledgeMessage connectAck = new AcknowledgeMessage();
                    connectAck.body          = notifier.Id;
                    connectAck.correlationId = OpenCommand;
                    StreamMessage(connectAck, response);
                } catch (MessageException) {
                }

                if (log.IsDebugEnabled)
                {
                    string msg = string.Format("Start streaming for endpoint with id {0} and client with id {1}", this.Id, flexClient.Id);
                    log.Debug(msg);
                }

                int serverToClientHeartbeatMillis = this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis >= 0 ? this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis : 0;
                serverToClientHeartbeatMillis = 100;
                while (!notifier.IsClosed)
                {
                    IList messages = notifier.GetPendingMessages();
                    StreamMessages(messages, response);
                    lock (notifier.SyncRoot) {
                        Monitor.Wait(notifier.SyncRoot, serverToClientHeartbeatMillis);

                        messages = notifier.GetPendingMessages();
                        // If there are no messages to send to the client, send a 0
                        // byte as a heartbeat to make sure the client is still valid.
                        if ((messages == null || messages.Count == 0) && serverToClientHeartbeatMillis > 0)
                        {
                            try {
                                StreamChunk(Heartbeat, response);
                                response.Flush();
                            } catch (HttpException) {
                                break;
                            } catch (IOException) {
                                break;
                            }
                        }
                        else
                        {
                            StreamMessages(messages, response);
                        }
                    }
                }
                // Terminate the response.
                StreamChunk(null, response);
                if (log.IsDebugEnabled)
                {
                    string msg = string.Format("Releasing streaming connection for endpoint with id {0} and and client with id {1}", this.Id, flexClient.Id);
                    log.Debug(msg);
                }
            } catch (IOException ex)            //HttpException?
            {
                if (log.IsWarnEnabled)
                {
                    log.Warn("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an IO error.", ex);
                }
            } catch (Exception ex) {
                if (log.IsErrorEnabled)
                {
                    log.Error("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an error.", ex);
                }
            } finally {
                if (notifier != null && _currentStreamingRequests != null)
                {
                    if (_currentStreamingRequests != null)
                    {
                        lock (_currentStreamingRequests.SyncRoot) {
                            _currentStreamingRequests.Remove(notifier.Id);
                        }
                    }
                    notifier.Close();
                }
                _streamingClientsCount.Decrement();
                lock (session.SyncRoot) {
                    session.StreamingConnectionsCount--;
                    session.CanStream = session.StreamingConnectionsCount < session.MaxConnectionsPerSession;
                }
            }
        }
Example #17
0
        /// <summary>创建客户端会话</summary>
        /// <returns></returns>
        public virtual HttpClient EnsureCreate()
        {
            var http = _client;

            if (http == null)
            {
                var p = Proxy;
                if (p == null && !ProxyAddress.IsNullOrEmpty())
                {
                    Proxy = p = new WebProxy(ProxyAddress);
                }

                var handler = new HttpClientHandler();
                if (p != null)
                {
                    handler.UseProxy = true;
                    handler.Proxy    = p;
                }
                else
                {
                    handler.UseProxy = false;
                    handler.Proxy    = null;
                }
                if (AutomaticDecompression != DecompressionMethods.None)
                {
                    handler.AutomaticDecompression = AutomaticDecompression;
                }

                http = new HttpClient(handler);

                _client      = http;
                Request      = http.DefaultRequestHeaders;
                http.Timeout = new TimeSpan(0, 0, 0, 0, Timeout);
            }

            var req = http.DefaultRequestHeaders;

            if (!UserAgent.IsNullOrEmpty())
            {
                req.UserAgent.ParseAdd(UserAgent);
            }
            if (!Accept.IsNullOrEmpty())
            {
                req.Accept.ParseAdd(Accept);
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                req.AcceptLanguage.ParseAdd(AcceptLanguage);
            }
            if (AutomaticDecompression != DecompressionMethods.None)
            {
                req.AcceptEncoding.ParseAdd("gzip, deflate");
            }
            if (!Referer.IsNullOrEmpty())
            {
                req.Referrer = new Uri(Referer);
            }
            if (KeepAlive)
            {
                req.Connection.ParseAdd("keep-alive");
            }

            GetCookie(http);

            return(http);
        }
Example #18
0
 public static bool IsWindowsPhone(this HttpRequest request)
 {
     return(request.IsUserAgentMatched(s => UserAgent.IsWindowsPhone(s)));
 }
Example #19
0
        /// <summary>创建头部</summary>
        /// <param name="length"></param>
        /// <returns></returns>
        protected override String BuildHeader(Int32 length)
        {
            if (Method.IsNullOrEmpty())
            {
                Method = length > 0 ? "POST" : "GET";
            }

            // 分解主机和资源
            var host = "";
            var uri  = Url;

            if (uri == null)
            {
                uri = new Uri("/");
            }

            if (uri.Scheme.EqualIgnoreCase("http", "ws"))
            {
                if (uri.Port == 80)
                {
                    host = uri.Host;
                }
                else
                {
                    host = "{0}:{1}".F(uri.Host, uri.Port);
                }
            }
            else if (uri.Scheme.EqualIgnoreCase("https"))
            {
                if (uri.Port == 443)
                {
                    host = uri.Host;
                }
                else
                {
                    host = "{0}:{1}".F(uri.Host, uri.Port);
                }
            }

            // 构建头部
            var sb = Pool.StringBuilder.Get();

            sb.AppendFormat("{0} {1} HTTP/1.1\r\n", Method, uri.PathAndQuery);
            sb.AppendFormat("Host:{0}\r\n", host);

            if (!Accept.IsNullOrEmpty())
            {
                sb.AppendFormat("Accept:{0}\r\n", Accept);
            }
            if (Compressed)
            {
                sb.AppendLine("Accept-Encoding:gzip, deflate");
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                sb.AppendFormat("AcceptLanguage:{0}\r\n", AcceptLanguage);
            }
            if (!UserAgent.IsNullOrEmpty())
            {
                sb.AppendFormat("User-Agent:{0}\r\n", UserAgent);
            }

            // 内容长度
            if (length > 0)
            {
                sb.AppendFormat("Content-Length:{0}\r\n", length);
            }
            if (!ContentType.IsNullOrEmpty())
            {
                sb.AppendFormat("Content-Type:{0}\r\n", ContentType);
            }

            if (KeepAlive)
            {
                sb.AppendLine("Connection:keep-alive");
            }
            if (!Referer.IsNullOrEmpty())
            {
                sb.AppendFormat("Referer:{0}\r\n", Referer);
            }

            foreach (var item in Headers)
            {
                sb.AppendFormat("{0}:{1}\r\n", item.Key, item.Value);
            }

            sb.AppendLine();

            return(sb.Put(true));
        }
Example #20
0
 public static Builder ForClient(UserAgent userAgent, Version version)
 => new Builder(userAgent, version);
 static NuGetPackageInstaller()
 {
     // Set User Agent string
     UserAgent.SetUserAgentString(new UserAgentStringBuilder("Cake NuGet Client"));
 }
Example #22
0
        protected override void InitializeApp(IMvxPluginManager pluginManager, IMvxApplication app)
        {
#if !USE_PRODUCTION_API
            System.Net.ServicePointManager.ServerCertificateValidationCallback
                += (sender, certificate, chain, sslPolicyErrors) => true;
#endif

            const string clientName = "Daneel";
            const string remoteConfigDefaultsFileName = "RemoteConfigDefaults";
            var          version     = NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"].ToString();
            var          database    = new Database();
            var          scheduler   = Scheduler.Default;
            var          timeService = new TimeService(scheduler);
            var          topViewControllerProvider = (ITopViewControllerProvider)Presenter;
            var          dialogService             = new DialogServiceIos(topViewControllerProvider);
            var          platformInfo = new PlatformInfoIos();
            var          suggestionProviderContainer = new SuggestionProviderContainer(
                new MostUsedTimeEntrySuggestionProvider(database, timeService, maxNumberOfSuggestions)
                );
            var intentDonationService       = new IntentDonationServiceIos();
            var privateSharedStorageService = new PrivateSharedStorageServiceIos();

            var appVersion          = Version.Parse(version);
            var keyValueStorage     = new UserDefaultsStorageIos();
            var permissionsService  = new PermissionsServiceIos();
            var userAgent           = new UserAgent(clientName, version);
            var settingsStorage     = new SettingsStorage(Version.Parse(version), keyValueStorage);
            var remoteConfigService = new RemoteConfigServiceIos();
            remoteConfigService.SetupDefaults(remoteConfigDefaultsFileName);
            var schedulerProvider       = new IOSSchedulerProvider();
            var calendarService         = new CalendarServiceIos(permissionsService);
            var notificationService     = new NotificationServiceIos(permissionsService, timeService);
            var backgroundSyncService   = new BackgroundSyncServiceIos();
            var backgroundService       = new BackgroundService(timeService, analyticsService);
            var automaticSyncingService = new AutomaticSyncingService(backgroundService, timeService, analyticsService);
            var errorHandlingService    = new ErrorHandlingService(navigationService, settingsStorage);

            var foundation =
                TogglFoundation
                .ForClient(userAgent, appVersion)
                .WithDatabase(database)
                .WithScheduler(scheduler)
                .WithTimeService(timeService)
                .WithApiEnvironment(environment)
                .WithGoogleService <GoogleServiceIos>()
                .WithRatingService <RatingServiceIos>()
                .WithLicenseProvider <LicenseProviderIos>()
                .WithAnalyticsService(analyticsService)
                .WithSchedulerProvider(schedulerProvider)
                .WithRemoteConfigService(remoteConfigService)
                .WithNotificationService(notificationService)
                .WithApiFactory(new ApiFactory(environment, userAgent))
                .WithBackgroundService(backgroundService)
                .WithAutomaticSyncingService(automaticSyncingService)
                .WithApplicationShortcutCreator(new ApplicationShortcutCreator())
                .WithSuggestionProviderContainer(suggestionProviderContainer)
                .WithIntentDonationService(intentDonationService)
                .WithStopwatchProvider <FirebaseStopwatchProviderIos>()
                .WithPrivateSharedStorageService(privateSharedStorageService)
                .WithPlatformInfo(platformInfo)
                .WithBackgroundSyncService(backgroundSyncService)

                .StartRegisteringPlatformServices()
                .WithDialogService(dialogService)
                .WithLastTimeUsageStorage(settingsStorage)
                .WithBrowserService <BrowserServiceIos>()
                .WithKeyValueStorage(keyValueStorage)
                .WithUserPreferences(settingsStorage)
                .WithCalendarService(calendarService)
                .WithOnboardingStorage(settingsStorage)
                .WithNavigationService(navigationService)
                .WithPermissionsService(permissionsService)
                .WithAccessRestrictionStorage(settingsStorage)
                .WithPasswordManagerService <OnePasswordServiceIos>()
                .WithErrorHandlingService(errorHandlingService)
                .WithSyncErrorHandlingService(new SyncErrorHandlingService(errorHandlingService))
                .WithRxActionFactory(new RxActionFactory(schedulerProvider))
                .Build();

            foundation.RevokeNewUserIfNeeded().Initialize();

            base.InitializeApp(pluginManager, app);
        }
Example #23
0
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var request = context.HttpContext.Request;
            var ip      = context.HttpContext.Connection.RemoteIpAddress.ToString();
            var trueip  = request.Headers[AppConfig.TrueClientIPHeader].ToString();

            if (!string.IsNullOrEmpty(trueip) && ip != trueip)
            {
                ip = trueip;
            }

            var tokenValid = request.Cookies["Email"].MDString3(AppConfig.BaiduAK).Equals(request.Cookies["FullAccessToken"]);

            if (ip.IsDenyIpAddress() && !tokenValid)
            {
                AccessDeny(ip, request, "黑名单IP地址");
                context.Result = new BadRequestObjectResult("您当前所在的网络环境不支持访问本站!");
                return;
            }

            if (CommonHelper.SystemSettings.GetOrAdd("FirewallEnabled", "true") == "false" || context.Filters.Any(m => m.ToString().Contains(nameof(AllowAccessFirewallAttribute))) || tokenValid)
            {
                return;
            }

            var ua      = request.Headers[HeaderNames.UserAgent] + "";
            var agent   = UserAgent.Parse(ua);
            var blocked = CommonHelper.SystemSettings.GetOrAdd("UserAgentBlocked", "").Split(new[] { ',', '|' }, StringSplitOptions.RemoveEmptyEntries);

            if (ua.Contains(blocked))
            {
                AccessDeny(ip, request, $"UA黑名单({agent.Browser} {agent.BrowserVersion}/{agent.Platform})");
                var msg = CommonHelper.SystemSettings.GetOrAdd("UserAgentBlockedMsg", "当前浏览器不支持访问本站");
                context.Result = new ContentResult()
                {
                    Content     = Template.Create(msg).Set("browser", agent.Browser + " " + agent.BrowserVersion).Set("os", agent.Platform).Render(),
                    ContentType = ContentType.Html,
                    StatusCode  = 403
                };
                return;
            }
            if (ip.IsInDenyArea() && !tokenValid)
            {
                AccessDeny(ip, request, "访问地区限制");
                throw new AccessDenyException("访问地区限制");
            }

            if (Regex.IsMatch(request.Method, "OPTIONS|HEAD", RegexOptions.IgnoreCase) || agent.IsRobot)
            {
                return;
            }

            var times = CacheManager.AddOrUpdate("Frequency:" + ip, 1, i => i + 1, 5);

            CacheManager.Expire("Frequency:" + ip, ExpirationMode.Sliding, TimeSpan.FromSeconds(CommonHelper.SystemSettings.GetOrAdd("LimitIPFrequency", "60").ToInt32()));
            var limit = CommonHelper.SystemSettings.GetOrAdd("LimitIPRequestTimes", "90").ToInt32();

            if (times <= limit)
            {
                return;
            }

            if (times > limit * 1.2)
            {
                CacheManager.Expire("Frequency:" + ip, ExpirationMode.Sliding, TimeSpan.FromMinutes(CommonHelper.SystemSettings.GetOrAdd("BanIPTimespan", "10").ToInt32()));
                AccessDeny(ip, request, "访问频次限制");
            }

            throw new TempDenyException("访问频次限制");
        }
Example #24
0
 public override void Cancelled(UserAgent ua, Message request, SIPStack stack)
 {
     throw new NotImplementedException();
 }
Example #25
0
        private HttpWebRequest ConfigureAsyncWebRequest(string method, Uri url)
        {
#if SILVERLIGHT
            WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
#endif
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.UseDefaultCredentials = false;

            AppendHeaders(webRequest);
            AppendCookies(webRequest);

            webRequest.Method = method;

            // make sure Content-Length header is always sent since default is -1
#if !WINDOWS_PHONE
            // WP7 doesn't as of Beta doesn't support a way to set this value either directly
            // or indirectly
            if (!HasFiles)
            {
                webRequest.ContentLength = 0;
            }
#endif

            if (Credentials != null)
            {
                webRequest.Credentials = Credentials;
            }

#if !SILVERLIGHT
            if (UserAgent.HasValue())
            {
                webRequest.UserAgent = UserAgent;
            }
#endif

#if FRAMEWORK
            if (ClientCertificates != null)
            {
                webRequest.ClientCertificates = ClientCertificates;
            }

            webRequest.AutomaticDecompression     = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None;
            ServicePointManager.Expect100Continue = false;

            if (Timeout != 0)
            {
                webRequest.Timeout = Timeout;
            }

            if (Proxy != null)
            {
                webRequest.Proxy = Proxy;
            }

            if (FollowRedirects && MaxRedirects.HasValue)
            {
                webRequest.MaximumAutomaticRedirections = MaxRedirects.Value;
            }
#endif

#if !SILVERLIGHT
            webRequest.AllowAutoRedirect = FollowRedirects;
#endif
            return(webRequest);
        }
Example #26
0
 public override void DialogCreated(Dialog dialog, UserAgent ua, SIPStack stack)
 {
     Useragents.Remove(ua);
     Useragents.Add(dialog);
     Log.Info("New dialog created");
 }
Example #27
0
        public async Task PackageUpdateResource_NoSymbolSourcePushingSymbolAsync(string source)
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                HttpRequestMessage symbolRequest = null;
                var apiKey      = "serverapikey";
                var packageInfo = await SimpleTestPackageUtility.CreateFullPackageAsync(workingDir, "test", "1.0.0");

                var symbolPackageInfo = await SimpleTestPackageUtility.CreateSymbolPackageAsync(workingDir, "test", "1.0.0");

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://nuget.smbsrc.net/api/v2/package/",
                        request =>
                        {
                            symbolRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "http://nuget.smbsrc.net/api/v2/package/",
                        request =>
                        {
                            symbolRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://www.nuget.org/api/v2/package/create-verification-key/test/1.0.0",
                        request =>
                        {
                            var content  = new StringContent(string.Format(JsonData.TempApiKeyJsonData, "tempkey"), Encoding.UTF8, "application/json");
                            var response = new HttpResponseMessage(HttpStatusCode.OK)
                            {
                                Content = content
                            };
                            return(Task.FromResult(response));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                await resource.Push(
                    packagePaths : new[] { packageInfo.FullName },
                    symbolSource : null,
                    timeoutInSecond : 5,
                    disableBuffering : false,
                    getApiKey : _ => apiKey,
                    getSymbolApiKey : _ => null,
                    noServiceEndpoint : false,
                    skipDuplicate : false,
                    symbolPackageUpdateResource : null,
                    log : NullLogger.Instance);

                // Assert
                IEnumerable <string> apiValues;
                IEnumerable <string> symbolClientVersionValues;
                symbolRequest.Headers.TryGetValues(ApiKeyHeader, out apiValues);
                symbolRequest.Headers.TryGetValues(NuGetClientVersionHeader, out symbolClientVersionValues);

                Assert.Equal("tempkey", apiValues.First());
                Assert.NotNull(symbolClientVersionValues.First());
            }
        }
Example #28
0
        public void IndexOfNull()
        {
            var agent = new UserAgent("abc");

            Assert.Throws <NullReferenceException>(() => agent.IndexOf(null));
        }
Example #29
0
        public async Task PackageUpdateResource_GetErrorFromCreateKeyPushingAsync()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source       = "https://www.myget.org/api/v2";
                var symbolSource = "https://nuget.smbsrc.net/";
                HttpRequestMessage sourceRequest = null;
                HttpRequestMessage symbolRequest = null;
                var apiKey = "serverapikey";

                var packageInfo = await SimpleTestPackageUtility.CreateFullPackageAsync(workingDir, "test", "1.0.0");

                var symbolPackageInfo =
                    await SimpleTestPackageUtility.CreateSymbolPackageAsync(workingDir, "test", "1.0.0");

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://www.myget.org/api/v2/", request =>
                        {
                            sourceRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://nuget.smbsrc.net/api/v2/package/", request =>
                        {
                            symbolRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://www.nuget.org/api/v2/package/create-verification-key/test/1.0.0",
                        request =>
                        {
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                var ex = await Assert.ThrowsAsync <HttpRequestException>(
                    async() => await resource.Push(
                        packagePaths: new[] { packageInfo.FullName },
                        symbolSource: symbolSource,
                        timeoutInSecond: 5,
                        disableBuffering: false,
                        getApiKey: _ => apiKey,
                        getSymbolApiKey: _ => apiKey,
                        noServiceEndpoint: false,
                        skipDuplicate: false,
                        symbolPackageUpdateResource: null,
                        log: NullLogger.Instance));

                // Assert
                Assert.True(ex.Message.Contains("Response status code does not indicate success: 500 (Internal Server Error)"));
            }
        }
Example #30
0
        public void IsNotEmpty()
        {
            var agent = new UserAgent("abc");

            Assert.False(agent.IsNullOrEmpty());
        }
Example #31
0
        public async Task PackageUpdateResource_RetryNuGetSymbolPushingAsync()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source                   = "https://nuget.smbsrc.net/";
                var symbolRequest            = new List <HttpRequestMessage>();
                var apiKey                   = "serverapikey";
                var symbolSourceRequestCount = 0;
                var createKeyRequestCount    = 0;

                var symbolPackageInfo = await SimpleTestPackageUtility.CreateSymbolPackageAsync(workingDir, "test", "1.0.0");

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://nuget.smbsrc.net/api/v2/package/",
                        request =>
                        {
                            symbolRequest.Add(request);
                            symbolSourceRequestCount++;
                            if (symbolSourceRequestCount < 3)
                            {
                                return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)));
                            }
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://www.nuget.org/api/v2/package/create-verification-key/test/1.0.0",
                        request =>
                        {
                            createKeyRequestCount++;
                            var content  = new StringContent(string.Format(JsonData.TempApiKeyJsonData, $"tempkey{createKeyRequestCount}"), Encoding.UTF8, "application/json");
                            var response = new HttpResponseMessage(HttpStatusCode.OK)
                            {
                                Content = content
                            };
                            return(Task.FromResult(response));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                await resource.Push(
                    packagePaths : new[] { symbolPackageInfo.FullName },
                    symbolSource : null,
                    timeoutInSecond : 5,
                    disableBuffering : false,
                    getApiKey : _ => apiKey,
                    getSymbolApiKey : _ => null,
                    noServiceEndpoint : false,
                    skipDuplicate : false,
                    symbolPackageUpdateResource : null,
                    log : NullLogger.Instance);

                // Assert
                var apikeys = new List <string>();

                Assert.Equal(3, symbolRequest.Count);

                IEnumerable <string> apiValues;
                for (var i = 1; i <= 3; i++)
                {
                    symbolRequest[i - 1].Headers.TryGetValues(ApiKeyHeader, out apiValues);
                    Assert.Equal($"tempkey{i}", apiValues.First());
                }
            }
        }
Example #32
0
 static Globals()
 {
     Version   = Assembly.GetExecutingAssembly().GetName().Version;
     UserAgent = new UserAgent("IAP-Desktop", Version);
 }
        public override int GetHashCode()
        {
            int hash = 1;

            if (RequestMethod.Length != 0)
            {
                hash ^= RequestMethod.GetHashCode();
            }
            if (RequestUrl.Length != 0)
            {
                hash ^= RequestUrl.GetHashCode();
            }
            if (RequestSize != 0L)
            {
                hash ^= RequestSize.GetHashCode();
            }
            if (Status != 0)
            {
                hash ^= Status.GetHashCode();
            }
            if (ResponseSize != 0L)
            {
                hash ^= ResponseSize.GetHashCode();
            }
            if (UserAgent.Length != 0)
            {
                hash ^= UserAgent.GetHashCode();
            }
            if (RemoteIp.Length != 0)
            {
                hash ^= RemoteIp.GetHashCode();
            }
            if (ServerIp.Length != 0)
            {
                hash ^= ServerIp.GetHashCode();
            }
            if (Referer.Length != 0)
            {
                hash ^= Referer.GetHashCode();
            }
            if (latency_ != null)
            {
                hash ^= Latency.GetHashCode();
            }
            if (CacheLookup != false)
            {
                hash ^= CacheLookup.GetHashCode();
            }
            if (CacheHit != false)
            {
                hash ^= CacheHit.GetHashCode();
            }
            if (CacheValidatedWithOriginServer != false)
            {
                hash ^= CacheValidatedWithOriginServer.GetHashCode();
            }
            if (CacheFillBytes != 0L)
            {
                hash ^= CacheFillBytes.GetHashCode();
            }
            return(hash);
        }
Example #34
0
        // GET: SegmentArticles/Article/5
        public async Task <IActionResult> Article(int?id)
        {
            _user = _context.User.FirstOrDefault(p => p.EmailAddress == _userManager.GetUserAsync(User).GetAwaiter().GetResult().Email);
            _cpy  = _context.Company.FirstOrDefaultAsync(m => m.ID == _user.CompanyID).GetAwaiter().GetResult();
            HttpContext.Session.SetInt32("CompanyID", _cpy.ID);
            HttpContext.Session.SetString("CompanyName", _cpy.CompanyName);
            HttpContext.Session.SetString("CompanyTextMain", _cpy.CompanyTextMain);
            HttpContext.Session.SetString("CompanyTextSecondary", _cpy.CompanyTextSecondary);
            HttpContext.Session.SetString("CompanyMainFontColor", _cpy.CompanyMainFontColor);
            HttpContext.Session.SetString("CompanyLogoImage", _cpy.CompanyLogoImage);
            HttpContext.Session.SetString("CompanyFocusImage", _cpy.CompanyFocusImage ?? "");
            HttpContext.Session.SetString("CompanyBackgroundImage", _cpy.CompanyBackgroundImage ?? "");
            HttpContext.Session.SetString("CompanyHighlightColor", _cpy.CompanyHighlightColor);
            HttpContext.Session.SetString("CompanyHeaderFontColor", _cpy.CompanyHeaderFontColor);
            HttpContext.Session.SetString("CompanyHeaderBackgroundColor", _cpy.CompanyHeaderBackgroundColor);
            HttpContext.Session.SetString("CompanyBackgroundColor", _cpy.CompanyBackgroundColor);
            HttpContext.Session.SetInt32("CompanyNumberOfUsers", _cpy.CompanyNumberOfUsers);
            ViewBag.UploadsLocation = "https://s3-us-west-2.amazonaws.com/wootrixv2uploadfiles/images/Uploads/";

            var segID = HttpContext.Session.GetInt32("SegmentListID");

            if (id == null)
            {
                return(NotFound());
            }

            DataAccessLayer dla = new DataAccessLayer(_context);

            ViewBag.CommentCount = dla.GetArticleApprovedCommentCount(id ?? 0);
            ViewBag.Comments     = dla.GetArticleCommentsList(id ?? 0);


            var segmentArticle = await _context.SegmentArticle
                                 .FirstOrDefaultAsync(m => m.ID == id);

            if (segmentArticle == null)
            {
                return(NotFound());
            }
            if (!string.IsNullOrEmpty(segmentArticle.ArticleUrl))
            {
                Response.Redirect(segmentArticle.ArticleUrl);
            }

            //OK for reporting we need to get some data about the user and save it to the ArticleReporting Table
            ArticleReporting ar = new ArticleReporting();

            ar.CompanyID       = _user.CompanyID;
            ar.UserID          = _user.ID;
            ar.UserName        = _user.Name;
            ar.SegmentID       = segID ?? 0;
            ar.SegmentName     = _context.CompanySegment.FirstOrDefault(m => m.ID == segID).Title;
            ar.ArticleID       = segmentArticle.ID;
            ar.ArticleName     = segmentArticle.Title;
            ar.ArticleReadTime = System.DateTime.Now;


            ar.Country = _user.Country;
            ar.State   = _user.State;
            ar.City    = _user.City;

            var       userAgent = Request.Headers["User-Agent"];
            UserAgent ua        = new UserAgent(userAgent);

            ar.DeviceType = ua.Browser.Name + " " + ua.Browser.Version;
            ar.OSType     = ua.OS.Name + " " + ua.OS.Version;

            _context.Add(ar);
            await _context.SaveChangesAsync();


            return(View(segmentArticle));
        }
Example #35
0
 /// <summary>
 /// Browse the folder
 /// </summary>
 /// <param name="startIndex">start index</param>
 /// <param name="requestedCount">requested count</param>
 /// <param name="userAgent">user agent</param>
 /// <returns>the browse result</returns>
 public abstract BrowseResult Browse(uint startIndex, uint requestedCount, UserAgent userAgent);
        public override HttpResponse DoAction <T>(AcsRequest <T> request, bool autoRetry, int maxRetryNumber,
                                                  string regionId,
                                                  AlibabaCloudCredentials credentials, Signer signer, FormatType?format, List <Endpoint> endpoints)
        {
            var                httpStatusCode    = "";
            var                retryAttemptTimes = 0;
            ClientException    exception;
            RetryPolicyContext retryPolicyContext;

            do
            {
                try
                {
                    var watch = Stopwatch.StartNew();

                    FormatType?requestFormatType = request.AcceptFormat;
                    format = requestFormatType;

                    ProductDomain domain;
                    if (!string.IsNullOrEmpty(this.endpoint))
                    {
                        domain = new ProductDomain("", this.endpoint);
                    }
                    else
                    {
                        domain = request.ProductDomain ??
                                 Aliyun.Acs.Core.Regions.Endpoint.FindProductDomain(regionId, request.Product, endpoints);
                    }

                    if (null == domain)
                    {
                        throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access.");
                    }

                    var userAgent = UserAgent.Resolve(request.GetSysUserAgentConfig(), userAgentConfig);
                    DictionaryUtil.Add(request.Headers, "User-Agent", userAgent);
                    DictionaryUtil.Add(request.Headers, "x-acs-version", request.Version);
                    if (!string.IsNullOrWhiteSpace(request.ActionName))
                    {
                        DictionaryUtil.Add(request.Headers, "x-acs-action", request.ActionName);
                    }

                    var httpRequest = SignRequest(request, signer, credentials, format, domain);
                    Helper.RunInstanceMethod(typeof(DefaultAcsClient), "ResolveTimeout", this, new object[] { httpRequest, request.Product, request.Version, request.ActionName });
                    SetHttpsInsecure(IgnoreCertificate);
                    ResolveProxy(httpRequest, request);
                    var response = GetResponse(httpRequest);

                    httpStatusCode = response.Status.ToString();
                    Helper.RunInstanceMethod(typeof(DefaultAcsClient), "PrintHttpDebugMsg", this, new object[] { request, response });
                    watch.Stop();
                    return(response);
                }
                catch (ClientException ex)
                {
                    retryPolicyContext = new RetryPolicyContext(ex, httpStatusCode, retryAttemptTimes, request.Product,
                                                                request.Version,
                                                                request.ActionName, RetryCondition.BlankStatus);

                    exception = ex;
                }

                Thread.Sleep(retryPolicy.GetDelayTimeBeforeNextRetry(retryPolicyContext));
            } while ((retryPolicy.ShouldRetry(retryPolicyContext) & RetryCondition.NoRetry) != RetryCondition.NoRetry);

            if (exception != null)
            {
                throw new ClientException(exception.ErrorCode, exception.ErrorMessage);
            }

            return(null);
        }
Example #37
0
 public Builder(UserAgent agent, Version version)
 {
     UserAgent = agent;
     Version   = version;
 }
Example #38
0
 public static bool IsMacOS(this HttpRequest request)
 {
     return(request.IsUserAgentMatched(s => UserAgent.IsMacOS(s)));
 }
Example #39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoding"></param>
        /// <param name="cookies"></param>
        /// <param name="userAgent"></param>
        /// <param name="referer"></param>
        /// <param name="data">要提交的数据"username=yongfa365&password=12345" 如果有中文请先HttpUtility.UrlEncode下</param>
        public static void Post(string url, Encoding encoding, CookieCollection cookies, UserAgent userAgent, string referer, string data)
        {
            try
            {
                byte[] datas = encoding.GetBytes(data);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = dictUserAgent[userAgent];
                request.Accept = "text/html";
                request.Referer = referer;
                request.KeepAlive = true;

                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                request.ContentLength = datas.Length;
                request.GetRequestStream().Write(datas, 0, datas.Length);

                request.GetResponse();

                //return new StreamReader(((HttpWebResponse)request.GetResponse()).GetResponseStream(), encoding).ReadToEnd();
            }
            catch
            {
            }
        }