Exemple #1
0
 private int ResolveTypeToNodeSpecificTypeIdentifier(TypeInfo typeInfo)
 {
     ArgumentValidator.EnsureArgumentNotNull(typeInfo, "typeInfo");
     return(TypeIdRegistry[typeInfo]);
 }
 public IMailboxAssociationUser GetUserAssociationByItemId(VersionedId itemId)
 {
     ArgumentValidator.ThrowIfNull("itemId", itemId);
     this.CheckDisposed("GetUserAssociationByItemId");
     return(this.xsoFactory.BindToMailboxAssociationUser(this.session, itemId.ObjectId, MailboxAssociationUserSchema.Instance.AllProperties));
 }
        public DocumentData GetDocumentDataFromXmlFile(string filepath)
        {
            ArgumentValidator.ValidateString(filepath);

            return(documentDataProvider.GetDocumentDataFromXmlFile(filepath));
        }
 public void ValidateBoolean_NullParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateBoolean("true", "test", null);
 }
 public SequenceQuery(string selectQuery, SequenceQueryCompartment compartment)
 {
     ArgumentValidator.EnsureArgumentNotNullOrEmpty(selectQuery, "selectQuery");
     SelectQuery = selectQuery;
     Compartment = compartment;
 }
 public void ValidateIncomeEarnedBy_VariedCase_ParsedValue()
 {
     ArgumentValidator validator = new ArgumentValidator();
     IncomeEarnedBy result = validator.ValidateIncomeEarnedBy("oNe", "test", "Test");
     Assert.AreEqual(IncomeEarnedBy.One, result);
 }
 public void ValidateBoolean_EmptyDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateBoolean("true", String.Empty, "Test");
 }
 public IAsyncResult BeginPutObject(AddDirectoryCacheRequest cacheRequest, AsyncCallback callback, object asyncState)
 {
     this.stopwatch = Stopwatch.StartNew();
     return(this.Invoke(delegate
     {
         ArgumentValidator.ThrowIfNull("cacheRequest", cacheRequest);
         CacheResponseContext cacheResponseContext = new CacheResponseContext();
         LazyAsyncResult lazyAsyncResult = new LazyAsyncResult(cacheResponseContext, asyncState, callback);
         ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <AddDirectoryCacheRequest>((long)this.GetHashCode(), "Begin Put. Request {0}", cacheRequest);
         MSExchangeDirectoryCacheServiceCounters.NumberOfCacheInsertionRequests.Increment();
         Tuple <string, KeyType> tuple = cacheRequest.Keys.Find((Tuple <string, KeyType> x) => KeyType.None != (x.Item2 & KeyType.Guid));
         if (tuple == null || CacheManager.Instance.ADObjectCache.Get(tuple.Item1.ToLower(), null) == null)
         {
             Tuple <string, KeyType> tuple2 = cacheRequest.Keys.Find((Tuple <string, KeyType> x) => KeyType.None != (x.Item2 & KeyType.DistinguishedName));
             if (tuple == null)
             {
                 tuple = tuple2;
             }
             else if (tuple2 != null && CacheManager.Instance.ADObjectCache.Get(tuple2.Item1.ToLower(), null) != null)
             {
                 tuple = tuple2;
             }
         }
         if (tuple == null)
         {
             return lazyAsyncResult;
         }
         string text = tuple.Item1.ToLower();
         cacheRequest.Object.Initialize(true);
         CacheItemPolicy cacheItemPolicy = this.GetCacheItemPolicy(cacheRequest);
         CacheEntry cacheEntry = (CacheEntry)CacheManager.Instance.ADObjectCache.Get(text, null);
         if (cacheEntry == null || cacheEntry.Invalid)
         {
             cacheEntry = new CacheEntry(new List <ObjectTuple>(1));
             cacheEntry.SimpleADObjectList.Add(new ObjectTuple(cacheRequest.ObjectType, cacheRequest.Object));
             CacheManager.Instance.ADObjectCache.Set(text, cacheEntry, cacheItemPolicy, null);
         }
         else
         {
             ObjectTuple objectTuple = null;
             foreach (ObjectTuple objectTuple2 in cacheEntry.SimpleADObjectList)
             {
                 if (objectTuple2.ObjType == cacheRequest.ObjectType)
                 {
                     objectTuple = objectTuple2;
                     objectTuple2.ADObject = cacheRequest.Object;
                     break;
                 }
             }
             if (objectTuple == null)
             {
                 cacheEntry.SimpleADObjectList = new List <ObjectTuple>(cacheEntry.SimpleADObjectList)
                 {
                     new ObjectTuple(cacheRequest.ObjectType, cacheRequest.Object)
                 };
             }
         }
         foreach (Tuple <string, KeyType> tuple3 in cacheRequest.Keys)
         {
             foreach (KeyType keyType in DirectoryCacheService.AllSupportedKeyTypes)
             {
                 if ((keyType & tuple3.Item2) != KeyType.None)
                 {
                     cacheEntry.ClearKey(keyType);
                 }
             }
         }
         foreach (Tuple <string, KeyType> tuple4 in cacheRequest.Keys)
         {
             foreach (KeyType keyType2 in DirectoryCacheService.AllSupportedKeyTypes)
             {
                 if ((keyType2 & tuple4.Item2) != KeyType.None)
                 {
                     string composedKey = this.GetComposedKey(cacheRequest.ForestOrPartitionFqdn, tuple4.Item1, keyType2);
                     cacheEntry[keyType2].Add(composedKey.ToLower());
                     CacheManager.Instance.KeyTable.Set(composedKey, text, cacheItemPolicy, null);
                 }
             }
         }
         this.stopwatch.Stop();
         cacheResponseContext.BeginOperationLatency = this.stopwatch.ElapsedMilliseconds;
         this.stopwatch.Restart();
         callback(lazyAsyncResult);
         return lazyAsyncResult;
     }));
 }
 public IAsyncResult BeginGetObject(DirectoryCacheRequest cacheRequest, AsyncCallback callback, object asyncState)
 {
     this.stopwatch = Stopwatch.StartNew();
     return(this.Invoke(delegate
     {
         ArgumentValidator.ThrowIfNull("cacheRequest", cacheRequest);
         if (cacheRequest.ObjectType == ObjectType.ADRawEntry && cacheRequest.Properties == null)
         {
             throw new ArgumentException("properties cannot be null when request object type is ADRawEntry");
         }
         MSExchangeDirectoryCacheServiceCounters.NumberOfCacheReadRequests.Increment();
         GetObjectContext getObjectContext = new GetObjectContext();
         getObjectContext.ResultState = ADCacheResultState.NotFound;
         LazyAsyncResult lazyAsyncResult = new LazyAsyncResult(getObjectContext, asyncState, callback);
         ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <DirectoryCacheRequest>((long)this.GetHashCode(), "Begin GetObject. Request {0}", cacheRequest);
         MSExchangeDirectoryCacheServiceCounters.CacheHitRatioBase.Increment();
         ObjectTuple objectTuple = null;
         foreach (Tuple <string, KeyType> tuple in cacheRequest.Keys)
         {
             CacheEntry cacheEntry = null;
             foreach (KeyType keyType in DirectoryCacheService.AllSupportedKeyTypes)
             {
                 if ((keyType & tuple.Item2) != KeyType.None)
                 {
                     string composedKey = this.GetComposedKey(cacheRequest.ForestOrPartitionFqdn, tuple.Item1, keyType);
                     string text = (string)CacheManager.Instance.KeyTable.Get(composedKey, null);
                     if (text != null)
                     {
                         cacheEntry = (CacheEntry)CacheManager.Instance.ADObjectCache.Get(text, null);
                         if (cacheEntry != null && cacheEntry[keyType].Contains(composedKey.ToLower()))
                         {
                             break;
                         }
                         if (cacheEntry != null)
                         {
                             if (ExTraceGlobals.WCFServiceEndpointTracer.IsTraceEnabled(TraceType.DebugTrace))
                             {
                                 string keyValues = string.Empty;
                                 cacheEntry[keyType].ForEach(delegate(string keyVal)
                                 {
                                     keyValues += keyVal;
                                     keyValues += ",";
                                 });
                                 ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <string, string>((long)this.GetHashCode(), "the key {0} does not match the cacheEntry's one {1}", composedKey, keyValues);
                             }
                             cacheEntry = null;
                         }
                     }
                 }
             }
             if (cacheEntry != null)
             {
                 if (cacheEntry.Invalid)
                 {
                     break;
                 }
                 foreach (ObjectTuple objectTuple2 in cacheEntry.SimpleADObjectList)
                 {
                     if (objectTuple2.ObjType == cacheRequest.ObjectType)
                     {
                         objectTuple = objectTuple2;
                         break;
                     }
                 }
                 if (objectTuple == null)
                 {
                     break;
                 }
                 if (cacheRequest.Properties != null)
                 {
                     foreach (string key in cacheRequest.Properties)
                     {
                         if (!objectTuple.ADObject.Properties.ContainsKey(key))
                         {
                             objectTuple = null;
                             getObjectContext.ResultState = ADCacheResultState.PropertiesMissing;
                             ADProviderPerf.UpdateDirectoryADRawCachePropertiesMismatchRate(true);
                             break;
                         }
                     }
                 }
                 if (objectTuple == null)
                 {
                     break;
                 }
                 getObjectContext.Object = objectTuple.ADObject;
                 getObjectContext.ResultState = ADCacheResultState.Succeed;
                 if (cacheRequest.Properties != null)
                 {
                     ADProviderPerf.UpdateDirectoryADRawCachePropertiesMismatchRate(false);
                     break;
                 }
                 break;
             }
         }
         ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <string, string>((long)this.GetHashCode(), "Begin GetObject. Request {0}. Was Cache {1}", cacheRequest.RequestId, (getObjectContext.Object != null) ? "HIT" : "MISS");
         ADProviderPerf.UpdateDirectoryCacheHitRatio(null != getObjectContext.Object, cacheRequest.ObjectType);
         this.stopwatch.Stop();
         getObjectContext.BeginOperationLatency = this.stopwatch.ElapsedMilliseconds;
         this.stopwatch.Restart();
         callback(lazyAsyncResult);
         return lazyAsyncResult;
     }));
 }
Exemple #10
0
 public StorageDriver CreateNew(Domain domain)
 {
     ArgumentValidator.EnsureArgumentNotNull(domain, "domain");
     return(new StorageDriver(underlyingDriver, ProviderInfo, domain.Configuration, GetModelProvider(domain)));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CatalogNode"/> class.
 /// </summary>
 /// <param name="catalog">The catalog.</param>
 /// <param name="name">The name.</param>
 protected CatalogNode(Catalog catalog, string name)
     : base(name)
 {
     ArgumentValidator.EnsureArgumentNotNull(catalog, "catalog");
     Catalog = catalog;
 }
        /// <summary>
        /// Find with transaction
        /// </summary>
        public IList <CV_PM_ALT_BASE> Find(int pageIndex, int pageSize, IFilter filter, ISort sort, out long totalRecords, DbTransaction transaction)
        {
            ArgumentValidator.CheckForNullArgument(transaction, "transaction");

            if (pageIndex < 0)
            {
                throw new ArgumentOutOfRangeException("pageIndex");
            }

            if (pageSize < -1)
            {
                throw new ArgumentOutOfRangeException("pageSize");
            }

            IList <CV_PM_ALT_BASE> CV_PM_ALT_BASEList = new List <CV_PM_ALT_BASE>();

            totalRecords = 0;

            string cmdText;
            string cmdCountText;

            int beginIndex = pageSize * pageIndex;

            string filterClause = "";

            if (filter == null || String.IsNullOrEmpty(filter.ToQueryString()))
            {
            }
            else
            {
                filterClause = filter.ToQueryString();
            }

            string sortClause = "";

            if (sort == null || String.IsNullOrEmpty(sort.ToSortString()))
            {
                sortClause = "ORDER BY AlertID";
            }
            else
            {
                sortClause = sort.ToSortString();
            }

            cmdCountText = string.Format(CultureInfo.InvariantCulture, SqlCount, filterClause);

            if (pageSize == -1)
            {
                cmdText = string.Format(
                    CultureInfo.InvariantCulture, CV_PM_ALT_BASEDAO.SqlSelectAll, filterClause, sortClause);
            }
            else
            {
                cmdText = String.Format(
                    CultureInfo.InvariantCulture,
                    CV_PM_ALT_BASEDAO.SqlSelect, pageSize.ToString(), filterClause, beginIndex.ToString(), filterClause, sortClause, sortClause);
            }

            try
            {
                Database db = GetDatabaseInstance();

                if (pageSize != 0)
                {
                    DbCommand dbCommand = db.GetSqlStringCommand(cmdText);
                    using (IDataReader dataReader = db.ExecuteReader(dbCommand, transaction))
                    {
                        while (dataReader.Read())
                        {
                            CV_PM_ALT_BASEList.Add(ReadEntity(dataReader));
                        }
                    }
                }

                //DbCommand dbCommandCount = db.GetSqlStringCommand(cmdCountText);
                //totalRecords = Convert.ToInt64(db.ExecuteScalar(dbCommandCount,transaction));
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, ExceptionPolicy.DataAccessDefaultPolicy);
            }

            return(CV_PM_ALT_BASEList);
        }
 internal static bool IsFingerprintRuleCollection(XDocument rulePackXDoc)
 {
     ArgumentValidator.ThrowIfNull("rulePackXDoc", rulePackXDoc);
     return(XmlProcessingUtils.GetRulePackId(rulePackXDoc).StartsWith("00000000-0000-0000-0001", StringComparison.OrdinalIgnoreCase));
 }
 internal static IEnumerable <XElement> GetFingerprintProcessorsInRulePackage(XDocument rulePackXDoc)
 {
     ArgumentValidator.ThrowIfNull("rulePackXDoc", rulePackXDoc);
     return(rulePackXDoc.Descendants(XmlProcessingUtils.GetMceNsQualifiedNodeName("Fingerprint")));
 }
 public void ValidateUnitedStatesStateOrTerritory_EmptyDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateUnitedStatesStateOrTerritory("3", String.Empty, "Test");
 }
        private DateTimeOffset GetCacheItemDateTimeOffsetExpiration(ObjectType objectType, int secondsTimeout)
        {
            ArgumentValidator.ThrowIfOutOfRange <int>("secondsTimeout", secondsTimeout, 1, 2147483646);
            if (2147483646 == secondsTimeout)
            {
                if (objectType <= ObjectType.OWAMiniRecipient)
                {
                    if (objectType <= ObjectType.FederatedOrganizationId)
                    {
                        switch (objectType)
                        {
                        case ObjectType.ExchangeConfigurationUnit:
                        case ObjectType.AcceptedDomain:
                            break;

                        case ObjectType.Recipient:
                            goto IL_93;

                        case ObjectType.ExchangeConfigurationUnit | ObjectType.Recipient:
                            goto IL_A5;

                        default:
                            if (objectType != ObjectType.FederatedOrganizationId)
                            {
                                goto IL_A5;
                            }
                            break;
                        }
                        secondsTimeout = Globals.TenantInfoCacheTime;
                        goto IL_AB;
                    }
                    if (objectType != ObjectType.MiniRecipient && objectType != ObjectType.TransportMiniRecipient && objectType != ObjectType.OWAMiniRecipient)
                    {
                        goto IL_A5;
                    }
                }
                else if (objectType <= ObjectType.ADRawEntry)
                {
                    if (objectType != ObjectType.ActiveSyncMiniRecipient && objectType != ObjectType.ADRawEntry)
                    {
                        goto IL_A5;
                    }
                }
                else if (objectType != ObjectType.StorageMiniRecipient && objectType != ObjectType.LoadBalancingMiniRecipient)
                {
                    if (objectType != ObjectType.MiniRecipientWithTokenGroups)
                    {
                        goto IL_A5;
                    }
                    secondsTimeout = Globals.RecipientTokenGroupsCacheTime;
                    goto IL_AB;
                }
IL_93:
                secondsTimeout = Globals.RecipientInfoCacheTime;
                goto IL_AB;
IL_A5:
                throw new NotImplementedException();
            }
IL_AB:
            return(DateTimeOffset.Now.AddSeconds((double)secondsTimeout));
        }
 public void ValidateUnitedStatesStateOrTerritory_EmptyParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateUnitedStatesStateOrTerritory("3", "test", String.Empty);
 }
 /// <inheritdoc/>
 public override bool Contains(HierarchyDef item)
 {
     ArgumentValidator.EnsureArgumentNotNull(item, "item");
     return(TryGetValue(item.Root) != null);
 }
 public void ValidateIncomeEarnedBy_BadValue_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateIncomeEarnedBy("G", "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
Exemple #20
0
        /// <summary>
        /// Validates a received webhook event by checking the signature of the event and verifying the event originated from PayPal.
        /// </summary>
        /// <param name="apiContext">APIContext containing any configuration settings to be used when validating the event.</param>
        /// <param name="requestHeaders">A collection of HTTP request headers included with the received webhook event.</param>
        /// <param name="requestBody">The body of the received HTTP request.</param>
        /// <param name="webhookId">ID of the webhook resource associated with this webhook event. If not specified, it is assumed the ID is provided via the Config property of the <paramref name="apiContext"/> parameter.</param>
        /// <returns>True if the webhook event is valid and was sent from PayPal; false otherwise.</returns>
        public static bool ValidateReceivedEvent(APIContext apiContext, NameValueCollection requestHeaders, string requestBody, string webhookId = "")
        {
            bool isValid = false;

            // Validate the APIContext object.
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);

            // Make sure the webhook ID has been provided.
            if (string.IsNullOrEmpty(webhookId))
            {
                if (apiContext.Config == null ||
                    !apiContext.Config.ContainsKey(BaseConstants.WebhookIdConfig) ||
                    string.IsNullOrEmpty(apiContext.Config[BaseConstants.WebhookIdConfig]))
                {
                    throw new PayPalException("Webhook ID needed for event validation was not found. Ensure the 'webhook.id' key is included in your application's config file or provide the webhook ID when you call this method.");
                }
                webhookId = apiContext.Config[BaseConstants.WebhookIdConfig];
            }

            // Check the headers and ensure all the correct information is present.
            var transmissionId        = requestHeaders[BaseConstants.PayPalTransmissionIdHeader];
            var transmissionTimestamp = requestHeaders[BaseConstants.PayPalTransmissionTimeHeader];
            var signature             = requestHeaders[BaseConstants.PayPalTransmissionSignatureHeader];
            var certUrl       = requestHeaders[BaseConstants.PayPalCertificateUrlHeader];
            var authAlgorithm = requestHeaders[BaseConstants.PayPalAuthAlgorithmHeader];

            ArgumentValidator.Validate(transmissionId, BaseConstants.PayPalTransmissionIdHeader);
            ArgumentValidator.Validate(transmissionTimestamp, BaseConstants.PayPalTransmissionTimeHeader);
            ArgumentValidator.Validate(signature, BaseConstants.PayPalTransmissionSignatureHeader);
            ArgumentValidator.Validate(certUrl, BaseConstants.PayPalCertificateUrlHeader);
            ArgumentValidator.Validate(authAlgorithm, BaseConstants.PayPalAuthAlgorithmHeader);

            try
            {
                // Convert the provided auth alrogithm header into a known hash alrogithm name.
                var hashAlgorithm = ConvertAuthAlgorithmHeaderToHashAlgorithmName(authAlgorithm);

                // Calculate a CRC32 checksum using the request body.
                var crc32 = Crc32.ComputeChecksum(requestBody);

                // Generate the expected signature.
                var expectedSignature      = string.Format("{0}|{1}|{2}|{3}", transmissionId, transmissionTimestamp, webhookId, crc32);
                var expectedSignatureBytes = Encoding.UTF8.GetBytes(expectedSignature);

                // Get the cert from the cache and load the trusted certificate.
                var x509CertificateCollection = CertificateManager.Instance.GetCertificatesFromUrl(certUrl);
                var trustedX509Certificate    = CertificateManager.Instance.GetTrustedCertificateFromFile(apiContext == null ? null : apiContext.Config);

                // Validate the certificate chain.
                isValid = CertificateManager.Instance.ValidateCertificateChain(trustedX509Certificate, x509CertificateCollection);

                // Verify the received signature matches the expected signature.
                if (isValid)
                {
                    var rsa            = x509CertificateCollection[0].PublicKey.Key as RSACryptoServiceProvider;
                    var signatureBytes = Convert.FromBase64String(signature);
                    isValid = rsa.VerifyData(expectedSignatureBytes, CryptoConfig.MapNameToOID(hashAlgorithm), signatureBytes);
                }
            }
            catch (PayPalException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new PayPalException("Encountered an error while attepting to validate a webhook event.", ex);
            }

            return(isValid);
        }
 public void ValidateIncomeEarnedBy_NullParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateIncomeEarnedBy("3", "test", null);
 }
Exemple #22
0
 public static void ThrowIfNull(AddressFinderSource source, IAddressFinderDiagnostics diagnostics)
 {
     ArgumentValidator.ThrowIfNull("source", source);
     ArgumentValidator.ThrowIfNull("diagnostics", diagnostics);
 }
 public void ValidatePositiveMoneyValue_ValidInput_ParsedValue()
 {
     ArgumentValidator validator = new ArgumentValidator();
     double result = validator.ValidatePositiveMoneyValue("3", "test", "Test");
     Assert.AreEqual(3, result);
 }
Exemple #24
0
        public PhotoResponse Retrieve(PhotoRequest request, PhotoResponse response)
        {
            ArgumentValidator.ThrowIfNull("request", request);
            ArgumentValidator.ThrowIfNull("response", response);
            PhotoResponse result;

            using (new StopwatchPerformanceTracker("HttpHandlerTotal", request.PerformanceLogger))
            {
                using (new ADPerformanceTracker("HttpHandlerTotal", request.PerformanceLogger))
                {
                    if (request.ShouldSkipHandlers(PhotoHandlers.Http))
                    {
                        this.tracer.TraceDebug((long)this.GetHashCode(), "HTTP HANDLER: skipped by request.");
                        result = response;
                    }
                    else if (response.Served)
                    {
                        this.tracer.TraceDebug((long)this.GetHashCode(), "HTTP HANDLER: skipped because photo has already been served by an upstream handler.");
                        result = response;
                    }
                    else if (request.TargetRecipient == null || !(request.TargetRecipient is ADUser))
                    {
                        this.tracer.TraceDebug((long)this.GetHashCode(), "HTTP HANDLER: skipped because target recipient has not been initialized OR is of unexpected type.");
                        result = response;
                    }
                    else
                    {
                        response.HttpHandlerProcessed = true;
                        request.PerformanceLogger.Log("HttpHandlerProcessed", string.Empty, 1U);
                        try
                        {
                            HttpWebRequest httpRequestToConfigure = new HttpPhotoRequestBuilder(this.configuration, this.tracer).Build(this.LocatePhotoService(request), request, this.outgoingRequestProxyProvider, request.Trace);
                            using (HttpWebResponse httpWebResponse = this.ConfigureAndSendRequest(request, httpRequestToConfigure))
                            {
                                result = this.ProcessResponseFromRemoteServer(request, response, httpWebResponse);
                            }
                        }
                        catch (WebException ex)
                        {
                            this.WriteTracesCollectedByRemoteServerOntoLocalTracer(ex.Response);
                            HttpStatusCode httpStatusCodeFromWebException = HttpPhotoHandler.GetHttpStatusCodeFromWebException(ex);
                            this.tracer.TraceDebug <HttpStatusCode, WebExceptionStatus>((long)this.GetHashCode(), "HTTP HANDLER: caught WebException and translated it to HTTP {0}.  Web exception status: {1}", httpStatusCodeFromWebException, ex.Status);
                            HttpStatusCode httpStatusCode = httpStatusCodeFromWebException;
                            if (httpStatusCode <= HttpStatusCode.Unauthorized)
                            {
                                if (httpStatusCode == HttpStatusCode.NotModified)
                                {
                                    response.Served            = true;
                                    response.Status            = HttpStatusCode.NotModified;
                                    response.HttpExpiresHeader = HttpPhotoHandler.GetHeaderValueFromWebException(ex, HttpResponseHeader.Expires);
                                    response.ETag = HttpPhotoHandler.GetHeaderValueFromWebException(ex, HttpResponseHeader.ETag);
                                    return(response);
                                }
                                if (httpStatusCode == HttpStatusCode.Unauthorized)
                                {
                                    response.Status = HttpStatusCode.Unauthorized;
                                    request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                                    return(response);
                                }
                            }
                            else
                            {
                                if (httpStatusCode == HttpStatusCode.NotFound)
                                {
                                    response.Served            = true;
                                    response.Status            = HttpStatusCode.NotFound;
                                    response.HttpExpiresHeader = HttpPhotoHandler.GetHeaderValueFromWebException(ex, HttpResponseHeader.Expires);
                                    return(response);
                                }
                                if (httpStatusCode != HttpStatusCode.InternalServerError)
                                {
                                }
                            }
                            response.Status = HttpStatusCode.InternalServerError;
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (BackEndLocatorException arg)
                        {
                            this.tracer.TraceError <BackEndLocatorException>((long)this.GetHashCode(), "HTTP HANDLER: failed to locate service.  Exception: {0}", arg);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (IOException arg2)
                        {
                            this.tracer.TraceError <IOException>((long)this.GetHashCode(), "HTTP HANDLER: request to remote server failed with I/O exception: {0}", arg2);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (ProtocolViolationException arg3)
                        {
                            this.tracer.TraceError <ProtocolViolationException>((long)this.GetHashCode(), "HTTP HANDLER: request to remote server failed with a protocol violation.  Exception: {0}", arg3);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (InvalidOperationException arg4)
                        {
                            this.tracer.TraceError <InvalidOperationException>((long)this.GetHashCode(), "HTTP HANDLER: request to remote server failed with invalid operation.  Exception: {0}", arg4);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (NotSupportedException arg5)
                        {
                            this.tracer.TraceError <NotSupportedException>((long)this.GetHashCode(), "HTTP HANDLER: request to remote server with an unsupported operation.  Exception: {0}", arg5);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (TimeoutException arg6)
                        {
                            this.tracer.TraceError <TimeoutException>((long)this.GetHashCode(), "HTTP HANDLER: timed out.  Exception: {0}", arg6);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                        catch (TransientException arg7)
                        {
                            this.tracer.TraceError <TransientException>((long)this.GetHashCode(), "HTTP HANDLER: failed with a transient error.  Exception: {0}", arg7);
                            request.PerformanceLogger.Log("HttpHandlerError", string.Empty, 1U);
                            result = response;
                        }
                    }
                }
            }
            return(result);
        }
 public void Create_should_be_null_guarded()
 {
     // Assert
     NullGuardedConstraint.Assert(() =>
                                  ArgumentValidator.Create(this.validations, x => true, "foo"));
 }
Exemple #26
0
        // Constructors

        /// <summary>
        ///   Initializes a new instance of this class.
        /// </summary>
        /// <param name="type">The type of the provider.</param>
        /// <param name="source">The <see cref="Source"/> property value.</param>
        protected UnaryProvider(ProviderType type, CompilableProvider source)
            : base(type, source)
        {
            ArgumentValidator.EnsureArgumentNotNull(source, "source");
            Source = source;
        }
Exemple #27
0
 /// <summary>
 /// Gets <see cref="DefaultSchemaInfo"/> for the specified <paramref name="connection"/>.
 /// </summary>
 /// <param name="connection"><see cref="DbConnection"/> to use.</param>
 /// <param name="transaction"><see cref="DbTransaction"/> to use.</param>
 /// <returns><see cref="DefaultSchemaInfo"/> for the specified <paramref name="connection"/>.</returns>
 public DefaultSchemaInfo GetDefaultSchema(DbConnection connection, DbTransaction transaction = null)
 {
     ArgumentValidator.EnsureArgumentNotNull(connection, "connection");
     return(ReadDefaultSchema(connection, transaction));
 }
 // Token: 0x06000097 RID: 151 RVA: 0x000046CF File Offset: 0x000028CF
 internal static void LogStartProcessingMailboxEvent(Guid activityId, AssistantBase assistant, Guid mailboxGuid, string mailboxDisplayNameTracingOnlyUsage, TimeBasedDatabaseJob job)
 {
     ArgumentValidator.ThrowIfNull("job", job);
     AssistantsLog.InternalLogAssistantEvent(activityId, assistant, AssistantsEventType.StartProcessingMailbox, null, mailboxGuid);
     AssistantsLog.LogMailboxSlaEvent(assistant, mailboxGuid, mailboxDisplayNameTracingOnlyUsage, job, MailboxSlaEventType.StartProcessingMailbox, MailboxSlaFilterReasonType.None, null);
 }
 /// <summary>
 /// Aliases the specified <see cref="Column"/> collection.
 /// </summary>
 /// <param name="alias">The alias to add.</param>
 /// <returns>Aliased collection of columns.</returns>
 public ColumnCollection Alias(string alias)
 {
     ArgumentValidator.EnsureArgumentNotNullOrEmpty(alias, "alias");
     return(new ColumnCollection(this.Select(column => column.Clone(alias + "." + column.Name))));
 }
Exemple #30
0
 protected DiagnosticsProcessorBase(DiagnosticsArgument arguments)
 {
     ArgumentValidator.ThrowIfNull("arguments", arguments);
     this.arguments = arguments;
 }
 public void ValidateUnitedStatesStateOrTerritory_NullDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateUnitedStatesStateOrTerritory("3", null, "Test");
 }
 private static ArgumentValidator <T> CreateValidator <T>(this ArgumentValidatorScope <T> scope, Func <T, bool> predicate, string description)
 {
     return(ArgumentValidator.Create(scope, predicate, description));
 }
 public void ValidateUnitedStatesStateOrTerritory_NullParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateUnitedStatesStateOrTerritory("3", "test", null);
 }
 private static ArgumentValidator <T> CreateValidator <T>(this ArgumentValidatorScope <T> scope, Func <T, bool> predicate, string descriptionFormat, params object[] args)
 {
     return(ArgumentValidator.Create(scope, predicate, descriptionFormat.FormatInvariant(args)));
 }
 public void ValidateIncomeEarnedBy_State_ParsedValue()
 {
     ArgumentValidator validator = new ArgumentValidator();
     IncomeEarnedBy result = validator.ValidateIncomeEarnedBy("both", "test", "Test");
     Assert.AreEqual(IncomeEarnedBy.Both, result);
 }
 public void ValidateMaritalStatus_VariedCase_ParsedValue()
 {
     ArgumentValidator validator = new ArgumentValidator();
     MaritalStatus result = validator.ValidateMaritalStatus("mArRiEd", "test", "Test");
     Assert.AreEqual(MaritalStatus.MarriedRemarried, result);
 }
 public void ValidateIncomeEarnedBy_EmptyInput_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateIncomeEarnedBy(null, "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
 public void ValidateBoolean_BadValue_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateBoolean("G", "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
 public void ValidateIncomeEarnedBy_NullDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateIncomeEarnedBy("3", null, "Test");
 }
 public void ValidateMaritalStatus_EmptyInput_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateMaritalStatus(null, "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
 public void ValidateIncomeEarnedBY_EmptyDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateIncomeEarnedBy("3", String.Empty, "Test");
 }
 public void ValidateMaritalStatus_BadValue_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateMaritalStatus("G", "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
 public void ValidateIncomeEarnedBy_EmptyParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateIncomeEarnedBy("3", "test", String.Empty);
 }
 public void ValidateMaritalStatus_NullDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateMaritalStatus("3", null, "Test");
 }
 public void ValidateBoolean_EmptyParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateBoolean("true", "test", String.Empty);
 }
 public void ValidateMaritalStatus_EmptyDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateMaritalStatus("3", String.Empty, "Test");
 }
 public void ValidatePositiveMoneyValue_BadValue_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidatePositiveMoneyValue("G", "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
 public void ValidateMaritalStatus_NullParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateMaritalStatus("3", "test", null);
 }
 public void Create_should_throw_when_description_is_an_empty_string()
 {
     // Assert
     Assert.Throws <ArgumentNullException>(() =>
                                           ArgumentValidator.Create(this.validations, x => true, string.Empty));
 }
 public void ValidateMaritalStatus_EmptyParamName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateMaritalStatus("3", "test", String.Empty);
 }
 public ConnectionEventData(DbConnection connection, bool reconnect = false)
 {
     ArgumentValidator.EnsureArgumentNotNull(connection, nameof(connection));
     Connection = connection;
     Reconnect  = reconnect;
 }
 public void ValidateUnitedStatesStateOrTerritory_State_ParsedValue()
 {
     ArgumentValidator validator = new ArgumentValidator();
     UnitedStatesStateOrTerritory result = validator.ValidateUnitedStatesStateOrTerritory("minnesota", "test", "Test");
     Assert.AreEqual(UnitedStatesStateOrTerritory.Minnesota, result);
 }
Exemple #53
0
 /// <summary>
 /// Gets connection string for the specified <see cref="ConnectionInfo"/>.
 /// </summary>
 /// <param name="connectionInfo">Connection information to process.</param>
 /// <returns>Connection string for <paramref name="connectionInfo"/>.</returns>
 public string GetConnectionString(ConnectionInfo connectionInfo)
 {
     ArgumentValidator.EnsureArgumentNotNull(connectionInfo, "connectionInfo");
     return(connectionInfo.ConnectionString
            ?? BuildConnectionString(connectionInfo.ConnectionUrl));
 }
 public void ValidateUnitedStatesStateOrTerritory_VariedCase_ParsedValue()
 {
     ArgumentValidator validator = new ArgumentValidator();
     UnitedStatesStateOrTerritory result = validator.ValidateUnitedStatesStateOrTerritory("cAlIfOrNiA", "test", "Test");
     Assert.AreEqual(UnitedStatesStateOrTerritory.California, result);
 }
        public static bool IsIntAttribute(this AttributeBase attributeBase)
        {
            ArgumentValidator.EnsureNotNull(nameof(attributeBase), attributeBase);

            return(attributeBase is IntAttribute);
        }
 public void ValidateUnitedStatesStateOrTerritory_BadValue_ReturnsError()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateUnitedStatesStateOrTerritory("G", "test", "Test");
     Assert.AreEqual(1, validator.Errors.Count);
 }
        public List <DocumentData> GetDocumentDataForMultipleXmlFiles(List <string> filePaths)
        {
            ArgumentValidator.ValidateNotEmptyList(filePaths);

            return(documentDataProvider.GetDocumentDataForMultipleXmlFiles(filePaths));
        }
 public void ValidateBoolean_NullDisplayName_ThrowsException()
 {
     ArgumentValidator validator = new ArgumentValidator();
     validator.ValidateBoolean("true", null, "Test");
 }
Exemple #59
0
 public void AddValidator(ArgumentValidator validator)
 {
     Validate += new ValidateHandler(validator.IsValid);
 }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public static bool ShouldRetryOn(Exception ex)
        {
            ArgumentValidator.EnsureArgumentNotNull(ex, "ex");
            if (ex is SqlException sqlException)
            {
                foreach (SqlError err in sqlException.Errors)
                {
                    switch (err.Number)
                    {
                    // SQL Error Code: 49920
                    // Cannot process request. Too many operations in progress for subscription "%ld".
                    // The service is busy processing multiple requests for this subscription.
                    // Requests are currently blocked for resource optimization. Query sys.dm_operation_status for operation status.
                    // Wait until pending requests are complete or delete one of your pending requests and retry your request later.
                    case 49920:
                    // SQL Error Code: 49919
                    // Cannot process create or update request. Too many create or update operations in progress for subscription "%ld".
                    // The service is busy processing multiple create or update requests for your subscription or server.
                    // Requests are currently blocked for resource optimization. Query sys.dm_operation_status for pending operations.
                    // Wait till pending create or update requests are complete or delete one of your pending requests and
                    // retry your request later.
                    case 49919:
                    // SQL Error Code: 49918
                    // Cannot process request. Not enough resources to process request.
                    // The service is currently busy.Please retry the request later.
                    case 49918:
                    // SQL Error Code: 41839
                    // Transaction exceeded the maximum number of commit dependencies.
                    case 41839:
                    // SQL Error Code: 41325
                    // The current transaction failed to commit due to a serializable validation failure.
                    case 41325:
                    // SQL Error Code: 41305
                    // The current transaction failed to commit due to a repeatable read validation failure.
                    case 41305:
                    // SQL Error Code: 41302
                    // The current transaction attempted to update a record that has been updated since the transaction started.
                    case 41302:
                    // SQL Error Code: 41301
                    // Dependency failure: a dependency was taken on another transaction that later failed to commit.
                    case 41301:
                    // SQL Error Code: 40613
                    // Database XXXX on server YYYY is not currently available. Please retry the connection later.
                    // If the problem persists, contact customer support, and provide them the session tracing ID of ZZZZZ.
                    case 40613:
                    // SQL Error Code: 40501
                    // The service is currently busy. Retry the request after 10 seconds. Code: (reason code to be decoded).
                    case 40501:
                    // SQL Error Code: 40197
                    // The service has encountered an error processing your request. Please try again.
                    case 40197:
                    // SQL Error Code: 10929
                    // Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d.
                    // However, the server is currently too busy to support requests greater than %d for this database.
                    // For more information, see http://go.microsoft.com/fwlink/?LinkId=267637. Otherwise, please try again.
                    case 10929:
                    // SQL Error Code: 10928
                    // Resource ID: %d. The %s limit for the database is %d and has been reached. For more information,
                    // see http://go.microsoft.com/fwlink/?LinkId=267637.
                    case 10928:
                    // SQL Error Code: 10060
                    // A network-related or instance-specific error occurred while establishing a connection to SQL Server.
                    // The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server
                    // is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed
                    // because the connected party did not properly respond after a period of time, or established connection failed
                    // because connected host has failed to respond.)"}
                    case 10060:
                    // SQL Error Code: 10054
                    // A transport-level error has occurred when sending the request to the server.
                    // (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
                    case 10054:
                    // SQL Error Code: 10053
                    // A transport-level error has occurred when receiving results from the server.
                    // An established connection was aborted by the software in your host machine.
                    case 10053:
                    // SQL Error Code: 1205
                    // Deadlock
                    case 1205:
                    // SQL Error Code: 233
                    // The client was unable to establish a connection because of an error during connection initialization process before login.
                    // Possible causes include the following: the client tried to connect to an unsupported version of SQL Server;
                    // the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum
                    // allowed connections) on the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by
                    // the remote host.)
                    case 233:
                    // SQL Error Code: 121
                    // The semaphore timeout period has expired
                    case 121:
                    // SQL Error Code: 64
                    // A connection was successfully established with the server, but then an error occurred during the login process.
                    // (provider: TCP Provider, error: 0 - The specified network name is no longer available.)
                    case 64:
                    // DBNETLIB Error Code: 20
                    // The instance of SQL Server you attempted to connect to does not support encryption.
                    case 20:
                        return(true);
                        // This exception can be thrown even if the operation completed succesfully, so it's safer to let the application fail.
                        // DBNETLIB Error Code: -2
                        // Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.
                        //case -2:
                    }
                }

                return(false);
            }

            return(ex is TimeoutException);
        }