System.Object.Equals(object, object)

Here are the examples of the csharp api System.Object.Equals(object, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

708 Examples 7

19 View Source File : UISliderExtended.cs
License : Apache License 2.0
Project Creator : 365082218

public void UpdateGridProperties()
		{
			if (this.m_OptionsContGrid == null)
				return;
			
			// Grid Padding
			if (!this.m_OptionsContGrid.padding.Equals(this.m_OptionsPadding))
				this.m_OptionsContGrid.padding = this.m_OptionsPadding;
			
			// Grid Cell Size
			Vector2 cellSize = (this.m_OptionSprite != null) ? new Vector2(this.m_OptionSprite.rect.width, this.m_OptionSprite.rect.height) : Vector2.zero;
			
			if (!this.m_OptionsContGrid.cellSize.Equals(cellSize))
				this.m_OptionsContGrid.cellSize = cellSize;
			
			// Grid spacing
			float spacingX = (this.m_OptionsContRect.rect.width - ((float)this.m_OptionsPadding.left + (float)this.m_OptionsPadding.right) - ((float)this.m_Options.Count * cellSize.x)) / ((float)this.m_Options.Count - 1f);
			
			if (this.m_OptionsContGrid.spacing.x != spacingX)
				this.m_OptionsContGrid.spacing = new Vector2(spacingX, 0f);
		}

19 View Source File : BaseViewModel.cs
License : MIT License
Project Creator : admaiorastudio

protected bool SetProperty<T>(ref T backingStore, T value,
            string chainedPropertyName = "",
            [CallerMemberName]string propertyName = "",
            Action onChanged = null)
        {
            if (EqualityComparer<T>.Default.Equals(backingStore, value))
                return false;

            backingStore = value;
            onChanged?.Invoke();
            OnPropertyChanged(propertyName);
            OnPropertyChanged(chainedPropertyName);
            return true;
        }

19 View Source File : Notepad.cs
License : MIT License
Project Creator : ASHTeam

void SheetSelectionMouseUp(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left && SourceTab != null)
            {
                SuspendLayout();
                TabPage currTabPage = GetTabPageFromXY(e.X, e.Y);
                if (currTabPage != null && !currTabPage.Equals(SourceTab))
                {   
                    SourceTab.SuspendLayout();
                    if (SheetSelection.TabPages.IndexOf(currTabPage) < SheetSelection.TabPages.IndexOf(SourceTab))
                    {
                        SheetSelection.TabPages.Remove(SourceTab);
                        SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage), SourceTab);
                        SheetSelection.SelectedTab = SourceTab;
                    }
                    else if (SheetSelection.TabPages.IndexOf(currTabPage) > SheetSelection.TabPages.IndexOf(SourceTab))
                    {
                        SheetSelection.TabPages.Remove(SourceTab);
                        SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage) + 1, SourceTab);
                        SheetSelection.SelectedTab = SourceTab;
                    }
                    SourceTab.ResumeLayout();
                }
            }
            ResumeLayout();
            SourceTab = null;
            Cursor = Cursors.Default;
        }

19 View Source File : Notepad.cs
License : MIT License
Project Creator : ASHTeam

void SheetSelection_MouseUp(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left && SourceTab != null)
            {
                SuspendLayout();
                TabPage currTabPage = GetTabPageFromXY(e.X, e.Y);
                if (currTabPage != null && !currTabPage.Equals(SourceTab))
                {   
                    SourceTab.SuspendLayout();
                    if (SheetSelection.TabPages.IndexOf(currTabPage) < SheetSelection.TabPages.IndexOf(SourceTab))
                    {
                        SheetSelection.TabPages.Remove(SourceTab);
                        SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage), SourceTab);
                        SheetSelection.SelectedTab = SourceTab;
                    }
                    else if (SheetSelection.TabPages.IndexOf(currTabPage) > SheetSelection.TabPages.IndexOf(SourceTab))
                    {
                        SheetSelection.TabPages.Remove(SourceTab);
                        SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage) + 1, SourceTab);
                        SheetSelection.SelectedTab = SourceTab;
                    }
                    SourceTab.ResumeLayout();
                }
            }
            ResumeLayout();
            SourceTab = null;
            Cursor = Cursors.Default;
        }

19 View Source File : CookieCollection.cs
License : GNU Affero General Public License v3.0
Project Creator : AugustToko

private static CookieCollection parseResponse (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var pairs = splitCookieHeaderValue (value);
      for (int i = 0; i < pairs.Length; i++) {
        var pair = pairs [i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Version = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
        }
        else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
          var buffer = new StringBuilder (pair.GetValueInternal ("="), 32);
          if (i < pairs.Length - 1)
            buffer.AppendFormat (", {0}", pairs [++i].Trim ());

          DateTime expires;
          if (!DateTime.TryParseExact (
            buffer.ToString (),
            new [] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
            CultureInfo.CreateSpecificCulture ("en-US"),
            DateTimeStyles.AdjustToUniversal | DateTimeStyles.replacedumeUniversal,
            out expires))
            expires = DateTime.Now;

          if (cookie != null && cookie.Expires == DateTime.MinValue)
            cookie.Expires = expires.ToLocalTime ();
        }
        else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
          var max = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
          var expires = DateTime.Now.AddSeconds ((double) max);
          if (cookie != null)
            cookie.Expires = expires;
        }
        else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValueInternal ("=");
        }
        else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValueInternal ("=");
        }
        else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValueInternal ("=");

          if (cookie != null)
            cookie.Port = port;
        }
        else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Comment = pair.GetValueInternal ("=").UrlDecode ();
        }
        else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.CommentUri = pair.GetValueInternal ("=").Trim ('"').ToUri ();
        }
        else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Discard = true;
        }
        else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Secure = true;
        }
        else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.HttpOnly = true;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }

19 View Source File : CookieCollection.cs
License : GNU Affero General Public License v3.0
Project Creator : AugustToko

private static CookieCollection parseRequest (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var version = 0;
      var pairs = splitCookieHeaderValue (value);
      for (int i = 0; i < pairs.Length; i++) {
        var pair = pairs [i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("$version", StringComparison.InvariantCultureIgnoreCase)) {
          version = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
        }
        else if (pair.StartsWith ("$path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValueInternal ("=");
        }
        else if (pair.StartsWith ("$domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValueInternal ("=");
        }
        else if (pair.StartsWith ("$port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("$port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValueInternal ("=");

          if (cookie != null)
            cookie.Port = port;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
          if (version != 0)
            cookie.Version = version;
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }

19 View Source File : AscClient.cs
License : MIT License
Project Creator : Azure

private async Task<T> GetAscResponse<T>(HttpRequestMessage requestMessage, bool isBlobRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!string.IsNullOrWhiteSpace(SubscriptionLocationPlacementId) && SubscriptionLocationPlacementId.Equals(DiagAscHeaderValue, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new InvalidOperationException("This subscription is not allowed for ASC calls");
            }
            var response = await SendAscRequestAsync(requestMessage, isBlobRequest, cancellationToken);
            string responseContent = await response.Content.ReadreplacedtringAsync();
            if (response.IsSuccessStatusCode)
            {
                if (typeof(T).Equals(typeof(string)))
                {
                    return CastTo<T>(responseContent);
                }
                else
                {
                    T value;
                    try
                    {
                        value = JsonConvert.DeserializeObject<T>(responseContent);
                    }
                    catch (JsonSerializationException serializeException)
                    {
                        throw new JsonSerializationException($" Failed to serialize ASC response to type {typeof(T).ToString()} : Response from ASC ==> {responseContent}", serializeException);
                    }

                    return value;
                }
            }
            else
            {
                string responseLogBody = await GetRequestDetailsForLogging(response);
                throw new HttpRequestException(string.Format("Request to fetch content from blob for ASC failed. AppLens request Id : {0} ==> Details : {1}", requestId, responseLogBody));
            }
        }

19 View Source File : KustoClusterMappingsController.cs
License : MIT License
Project Creator : Azure

[HttpPost]
        public async Task<IActionResult> AddOrUpdateMapping(string provider, [FromBody]List<Dictionary<string, string>> kustoMappings)
        {
            var cacheId = GetGitHubId(provider);
            try
            {         
                var sourcewatchertype = _sourceWatcherService.Watcher.GetType();
                if (sourcewatchertype != typeof(StorageWatcher))
                {
                    await _sourceWatcherService.Watcher.WaitForFirstCompletion();
                }
                //TODO the equals condition always fail due to the strings in the data structures are never compared
                if (_kustoMappingsCache.TryGetValue(cacheId, out List<Dictionary<string, string>> cacheValue) && cacheValue.Equals(kustoMappings))
                {
                    return Ok();
                }

                var gitHubPackage = new GithubPackage(cacheId, "kustoClusterMappings", "json", JsonConvert.SerializeObject(kustoMappings));
                await _sourceWatcherService.Watcher.CreateOrUpdatePackage(gitHubPackage);
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode((int)HttpStatusCode.InternalServerError, ex);
            }
        }

19 View Source File : GithubKustoConfigurationWorker.cs
License : MIT License
Project Creator : Azure

public override async Task CreateOrUpdateCacheAsync(DirectoryInfo subDir)
        {
            var workerId = await FileHelper.GetFileContentAsync(subDir.FullName, _workerIdFileName);

            if (IsWorkerApplicable(subDir) || workerId.Equals(Name, StringComparison.CurrentCultureIgnoreCase))
            {
                // Check if delete marker file exists.
                var deleteMarkerFile = new FileInfo(Path.Combine(subDir.FullName, _deleteMarkerName));
                if (deleteMarkerFile.Exists)
                {
                    _cacheService.TryRemoveValue(subDir.Name, out var throwAway);
                    return;
                }

                var kustoMappingsStringContent = await FileHelper.GetFileContentAsync(subDir.FullName, $"{_kustoClusterFileName}.json");
                var kustoMappings = (List<Dictionary<string, string>>)JsonConvert.DeserializeObject(kustoMappingsStringContent, typeof(List<Dictionary<string, string>>));

                if (!_cacheService.ContainsKey(subDir.Name) || (_cacheService.TryGetValue(subDir.Name, out List<Dictionary<string, string>> value) && value != null && !value.Equals(kustoMappings)))
                {
                    _cacheService.AddOrUpdate(subDir.Name, kustoMappings);
                }
            }
        }

19 View Source File : IGithubService.cs
License : MIT License
Project Creator : Azure

public async Task<T> GetFileContentByType<T>(string url)
        {
            var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, url));
            var responseContent = await response.Content.ReadreplacedtringAsync();

            if (typeof(T).Equals(typeof(string)))
            {
                return (T)(object)responseContent;
            }
            else
            {

                T value;
                try
                {
                    value = JsonConvert.DeserializeObject<T>(responseContent);
                }
                catch (JsonSerializationException serializeException)
                {
                    throw new JsonSerializationException($"Failed to serialize response {responseContent}", serializeException);
                }

                return value;
            }
        }

19 View Source File : ClientEncryptionKeyProperties.cs
License : MIT License
Project Creator : Azure

public bool Equals(ClientEncryptionKeyProperties other)
        {
            return other != null &&
                   this.Id == other.Id &&
                   this.EncryptionAlgorithm == other.EncryptionAlgorithm &&
                   ClientEncryptionKeyProperties.Equals(this.WrappedDataEncryptionKey, other.WrappedDataEncryptionKey) &&
                   EqualityComparer<EncryptionKeyWrapMetadata>.Default.Equals(this.EncryptionKeyWrapMetadata, other.EncryptionKeyWrapMetadata) &&
                   this.AdditionalProperties.EqualsTo(other.AdditionalProperties) &&
                   this.CreatedTime == other.CreatedTime &&
                   this.ETag == other.ETag &&
                   this.LastModified == other.LastModified &&
                   this.SelfLink == other.SelfLink &&
                   this.ResourceId == other.ResourceId;
        }

19 View Source File : GatewayAddressCache.cs
License : MIT License
Project Creator : Azure

private async Task<ParreplacedionAddressInformation> GetAddressesForRangeIdAsync(
            DoreplacedentServiceRequest request,
            string collectionRid,
            string parreplacedionKeyRangeId,
            bool forceRefresh)
        {
            using (DoreplacedentServiceResponse response =
                await this.GetServerAddressesViaGatewayAsync(request, collectionRid, new[] { parreplacedionKeyRangeId }, forceRefresh))
            {
                FeedResource<Address> addressFeed = response.GetResource<FeedResource<Address>>();

                bool inNetworkRequest = this.IsInNetworkRequest(response);

                IEnumerable<Tuple<ParreplacedionKeyRangeIdenreplacedy, ParreplacedionAddressInformation>> addressInfos =
                    addressFeed.Where(addressInfo => ProtocolFromString(addressInfo.Protocol) == this.protocol)
                        .GroupBy(address => address.ParreplacedionKeyRangeId, StringComparer.Ordinal)
                        .Select(group => this.ToParreplacedionAddressAndRange(collectionRid, @group.ToList(), inNetworkRequest));

                Tuple<ParreplacedionKeyRangeIdenreplacedy, ParreplacedionAddressInformation> result =
                    addressInfos.SingleOrDefault(
                        addressInfo => StringComparer.Ordinal.Equals(addressInfo.Item1.ParreplacedionKeyRangeId, parreplacedionKeyRangeId));

                if (result == null)
                {
                    string errorMessage = string.Format(
                        CultureInfo.InvariantCulture,
                        RMResources.ParreplacedionKeyRangeNotFound,
                        parreplacedionKeyRangeId,
                        collectionRid);

                    throw new ParreplacedionKeyRangeGoneException(errorMessage) { ResourceAddress = collectionRid };
                }

                return result.Item2;
            }
        }

19 View Source File : CosmosDatabaseTests.cs
License : MIT License
Project Creator : Azure

private static async Task<ClientEncryptionKeyProperties> CreateCekAsync(DatabaseInlineCore databaseCore, string cekId)
        {
            byte[] rawCek = new byte[32];
            // Generate random bytes cryptographically.
            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                rngCsp.GetBytes(rawCek);
            }

            ClientEncryptionKeyProperties cekProperties = new ClientEncryptionKeyProperties(cekId, "AEAD_AES_256_CBC_HMAC_SHA256", rawCek, new EncryptionKeyWrapMetadata("custom", "metadataName", "metadataValue"));

            ClientEncryptionKeyResponse cekResponse = await databaseCore.CreateClientEncryptionKeyAsync(cekProperties);

            replacedert.AreEqual(HttpStatusCode.Created, cekResponse.StatusCode);
            replacedert.IsTrue(cekResponse.RequestCharge > 0);
            replacedert.IsNotNull(cekResponse.ETag);

            ClientEncryptionKeyProperties retrievedCekProperties = cekResponse.Resource;
            replacedert.IsTrue(rawCek.SequenceEqual(retrievedCekProperties.WrappedDataEncryptionKey));
            EqualityComparer<EncryptionKeyWrapMetadata>.Default.Equals(cekResponse.Resource.EncryptionKeyWrapMetadata, retrievedCekProperties.EncryptionKeyWrapMetadata);
            replacedert.AreEqual(cekResponse.ETag, retrievedCekProperties.ETag);
            replacedert.AreEqual(cekId, retrievedCekProperties.Id);
            replacedert.AreEqual("AEAD_AES_256_CBC_HMAC_SHA256", retrievedCekProperties.EncryptionAlgorithm);
            return retrievedCekProperties;
        }

19 View Source File : HandlerTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task TestPreProcessingHandler()
        {
            RequestHandler preProcessHandler = new PreProcessingTestHandler();
            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient((builder) => builder.AddCustomHandlers(preProcessHandler));

            replacedert.IsTrue(typeof(RequestInvokerHandler).Equals(client.RequestHandler.GetType()));
            replacedert.IsTrue(typeof(PreProcessingTestHandler).Equals(client.RequestHandler.InnerHandler.GetType()));

            Container container = client.GetDatabase("testdb")
                                        .GetContainer("testcontainer");

            HttpStatusCode[] testHttpStatusCodes = new HttpStatusCode[]
                                {
                                    HttpStatusCode.OK
                                };

            // User operations
            foreach (HttpStatusCode code in testHttpStatusCodes)
            {
                ItemRequestOptions options = new ItemRequestOptions
                {
                    Properties = new Dictionary<string, object>()
                {
                    { PreProcessingTestHandler.StatusCodeName, code },
                }
                };

                ItemResponse<object> response = await container.ReadItemAsync<object>("id1", new Cosmos.ParreplacedionKey("pk1"), options);
                Console.WriteLine($"Got status code {response.StatusCode}");
                replacedert.AreEqual(code, response.StatusCode);
            }

            // Meta-data operations
            foreach (HttpStatusCode code in testHttpStatusCodes)
            {
                ContainerRequestOptions options = new ContainerRequestOptions
                {
                    Properties = new Dictionary<string, object>()
                {
                    { PreProcessingTestHandler.StatusCodeName, code }
                }
                };

                ContainerResponse response = await container.DeleteContainerAsync(options);

                Console.WriteLine($"Got status code {response.StatusCode}");
                replacedert.AreEqual(code, response.StatusCode);

            }
        }

19 View Source File : DataEncryptionKeyProperties.cs
License : MIT License
Project Creator : Azure

public bool Equals(DataEncryptionKeyProperties other)
        {
            return other != null &&
                   this.Id == other.Id &&
                   this.EncryptionAlgorithm == other.EncryptionAlgorithm &&
                   DataEncryptionKeyProperties.Equals(this.WrappedDataEncryptionKey, other.WrappedDataEncryptionKey) &&
                   EqualityComparer<EncryptionKeyWrapMetadata>.Default.Equals(this.EncryptionKeyWrapMetadata, other.EncryptionKeyWrapMetadata) &&
                   this.CreatedTime == other.CreatedTime &&
                   this.ETag == other.ETag &&
                   this.LastModified == other.LastModified &&
                   this.SelfLink == other.SelfLink &&
                   this.ResourceId == other.ResourceId;
        }

19 View Source File : Library.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object obj)
        {
            return obj is PythonPyPiLibrary library &&
                   EqualityComparer<PythonPyPiLibrarySpec>.Default.Equals(PythonPyPiLibrarySpec,
                       library.PythonPyPiLibrarySpec);
        }

19 View Source File : Library.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object obj)
        {
            return obj is RCranLibrary library &&
                   EqualityComparer<RCranLibrarySpec>.Default.Equals(RCranLibrarySpec, library.RCranLibrarySpec);
        }

19 View Source File : Library.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object obj)
        {
            return obj is MavenLibrary library &&
                   EqualityComparer<MavenLibrarySpec>.Default.Equals(MavenLibrarySpec, library.MavenLibrarySpec);
        }

19 View Source File : SyntaxNodeUtils.cs
License : MIT License
Project Creator : Azure

private static bool TryGetCollectionType(ITypeSymbol type, out ITypeSymbol collectionType)
        {
            if (type != null)
            {
                if (type.Kind.Equals(SymbolKind.ArrayType))
                {
                    collectionType = ((IArrayTypeSymbol)type).ElementType;
                    return true;
                }

                if (type.Kind.Equals(SymbolKind.NamedType))
                {
                    collectionType = ((INamedTypeSymbol)type).TypeArguments.FirstOrDefault();
                    return collectionType != null;
                }
            }

            collectionType = null;
            return false;
        }

19 View Source File : LinuxAppServiceLogger.cs
License : MIT License
Project Creator : Azure

private string GenerateLogStr(EventWrittenEventArgs eventData)
        {
            var values = eventData.Payload;
            var keys = eventData.PayloadNames;

            // We pack them into a JSON
            JObject json = new JObject
            {
                { "ProviderName", eventData.EventSource.Name },
                { "TaskName", eventData.EventName },
                { "EventId", eventData.EventId },
                { "EventTimestamp", DateTime.UtcNow },
                { "Pid", this.procID },
                { "Tid", Thread.CurrentThread.ManagedThreadId },
                { "Level", (int)eventData.Level },
            };

            if (!string.IsNullOrEmpty(this.stamp) && !string.IsNullOrEmpty(this.primaryStamp))
            {
                json.Add("EventStampName", this.stamp);
                json.Add("EventPrimaryStampName", this.primaryStamp);
            }

            if (!(this.roleInstance is null))
            {
                json.Add("RoleInstance", this.roleInstance);
            }

            if (!(this.tenant is null))
            {
                json.Add("Tenant", this.tenant);
            }

            // Add payload elements
            for (int i = 0; i < values.Count; i++)
            {
                json.Add(keys[i], JToken.FromObject(values[i]));
            }

            // Add ActivityId and RelatedActivityId, if non-null
            if (!eventData.ActivityId.Equals(Guid.Empty))
            {
                json.Add("ActivityId", eventData.ActivityId);
            }

            if (!eventData.RelatedActivityId.Equals(Guid.Empty))
            {
                json.Add("RelatedActivityId", eventData.RelatedActivityId);
            }

            // Generate string-representation of JSON.
            // Newtonsoft should take care of removing newlines for us.
            // It is also important to specify no formatting to avoid
            // pretty printing.
            string logString = json.ToString(Newtonsoft.Json.Formatting.None);
            return logString;
        }

19 View Source File : MethodInformation.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object obj)
        {
            return obj is MethodInformation information &&
                   EqualityComparer<ISymbol>.Default.Equals(DeclarationSymbol, information.DeclarationSymbol);
        }

19 View Source File : TupleStringIgnoreCasesComparer.cs
License : MIT License
Project Creator : Azure

public bool Equals((string, string, string) x, (string, string, string) y)
        {
            return StringComparer.InvariantCultureIgnoreCase.Equals(x.Item1, y.Item1) &&
                   StringComparer.InvariantCultureIgnoreCase.Equals(x.Item2, y.Item2) &&
                   StringComparer.InvariantCultureIgnoreCase.Equals(x.Item3, y.Item3);
        }

19 View Source File : ListVirtualMachineImages.cs
License : MIT License
Project Creator : Azure

public static void RunSample(IAzure azure)
        {
            //=================================================================
            // List all virtual machine image publishers and
            // list all virtual machine images
            // published by Canonical, Red Hat and SUSE
            // by browsing through locations, publishers, offers, SKUs and images

            var publishers = azure
                    .VirtualMachineImages
                    .Publishers
                    .ListByRegion(Region.USEast);

            Utilities.Log("US East data center: printing list of \n" + 
                            "a) Publishers and\n" + 
                            "b) Images published by Canonical, Red Hat and Suse");
            Utilities.Log("=======================================================");
            Utilities.Log("\n");

            foreach (var publisher in publishers)
            {
                Utilities.Log("Publisher - " + publisher.Name);

                if (StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Canonical") || 
                    StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Suse") || 
                    StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "RedHat"))
                {
                    Utilities.Log("\n\n");
                    Utilities.Log("=======================================================");
                    Utilities.Log("Located " + publisher.Name);
                    Utilities.Log("=======================================================");
                    Utilities.Log("Printing entries as publisher/offer/sku/image/version");

                    foreach (var offer in publisher.Offers.List())
                    {
                        foreach (var sku in offer.Skus.List())
                        {
                            foreach (var image in sku.Images.List())
                            {
                                Utilities.Log($"Image - {publisher.Name}/{offer.Name}/{sku.Name}/{image.Version}");
                            }
                        }
                    }

                    Utilities.Log("\n\n");
                }
            }
        }

19 View Source File : ListVirtualMachineExtensionImages.cs
License : MIT License
Project Creator : Azure

public static void RunSample(IAzure azure)
        {
            //=================================================================
            // List all virtual machine extension image publishers and
            // list all virtual machine extension images
            // published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions
            // y browsing through extension image publishers, types, and versions

            var publishers = azure
                    .VirtualMachineImages
                    .Publishers
                    .ListByRegion(Region.USEast);

            Utilities.Log("US East data center: printing list of \n"
                    + "a) Publishers and\n"
                    + "b) virtual machine images published by Microsoft.OSTCExtensions and Microsoft.Azure.Extensions");
            Utilities.Log("=======================================================");
            Utilities.Log("\n");

            foreach (var publisher in publishers)
            {
                Utilities.Log("Publisher - " + publisher.Name);

                if (StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Microsoft.OSTCExtensions") || 
                    StringComparer.OrdinalIgnoreCase.Equals(publisher.Name, "Microsoft.Azure.Extensions"))
                {
                    Utilities.Log("\n\n");
                    Utilities.Log("=======================================================");
                    Utilities.Log("Located " + publisher.Name);
                    Utilities.Log("=======================================================");
                    Utilities.Log("Printing entries as publisher/type/version");

                    foreach (var imageType in publisher.ExtensionTypes.List())
                    {
                        foreach (var version in imageType.Versions.List())
                        {
                            var image = version.GetImage();
                            Utilities.Log($"Image - {publisher.Name}/{image.TypeName}/{image.VersionName}");
                        }
                    }
                    Utilities.Log("\n\n");
                }
            }
        }

19 View Source File : Azure.cs
License : MIT License
Project Creator : Azure

private static ISubscription GetDefaultSubscription(IEnumerable<ISubscription> subscriptions)
            {
                return subscriptions
                    .FirstOrDefault(s =>
                        StringComparer.OrdinalIgnoreCase.Equals(s.State, "Enabled") ||
                        StringComparer.OrdinalIgnoreCase.Equals(s.State, "Warned") ||
                        StringComparer.OrdinalIgnoreCase.Equals(s.State, "PastDue"));
            }

19 View Source File : RedisCacheImpl.cs
License : MIT License
Project Creator : Azure

public async Task RemoveLinkedServerAsync(string linkedServerName, CancellationToken cancellationToken)
        {
            var linkedServer = await this.Manager.Inner.LinkedServer.GetAsync(
                this.ResourceGroupName, 
                this.Name, 
                linkedServerName, 
                cancellationToken);

            await this.Manager.Inner.LinkedServer.DeleteAsync(
                this.ResourceGroupName,
                this.Name,
                linkedServerName,
                cancellationToken);

            RedisResourceInner innerLinkedResource = null;
            RedisResourceInner innerResource = null;
            while (innerLinkedResource == null ||
                !(StringComparer.OrdinalIgnoreCase.Equals(innerLinkedResource.ProvisioningState, "Succeeded")) || 
                innerResource == null ||
                !(StringComparer.OrdinalIgnoreCase.Equals(innerResource.ProvisioningState, "Succeeded"))) 
                {
                    await SdkContext.DelayProvider.DelayAsync(30 * 1000, cancellationToken);

                    innerLinkedResource = await this.Manager.Inner.Redis.GetAsync(
                        ResourceUtils.GroupFromResourceId(linkedServer.Id),
                        ResourceUtils.NameFromResourceId(linkedServer.Id),
                        cancellationToken);

                innerResource = await this.Manager.Inner.Redis.GetAsync(this.ResourceGroupName, this.Name);
            }

        }

19 View Source File : ResourceGroupsTests.cs
License : MIT License
Project Creator : Azure

[Fact]
        public void CanCRUDResourceGroup()
        {
            using (var context = FluentMockContext.Start(this.GetType().FullName))
            {
                var rgName = TestUtilities.GenerateName("rgchash-");
                Action<IResourceGroup> checkResourceGroup = (IResourceGroup resourceGroup) =>
                {
                    replacedert.NotNull(resourceGroup.Name);
                    replacedert.Equal(resourceGroup.Name, rgName, ignoreCase: true);
                    replacedert.NotNull(resourceGroup.RegionName);
                    replacedert.True(StringComparer.CurrentCultureIgnoreCase.Equals(resourceGroup.RegionName, Region.USEast2.Name));
                    replacedert.NotNull(resourceGroup.Id);
                    replacedert.NotNull(resourceGroup.Tags);
                    replacedert.Equal(3, resourceGroup.Tags.Count);
                };

                try
                {
                    var resourceManager = TestHelper.CreateResourceManager();
                    var resourceGroup = resourceManager.ResourceGroups.Define(rgName)
                        .WithRegion(Region.USEast2)
                        .WithTag("t1", "v1")
                        .WithTag("t2", "v2")
                        .WithTag("t3", "v3")
                        .Create();
                    checkResourceGroup(resourceGroup);

                    // Check existence  
                    replacedert.True(resourceManager.ResourceGroups.Contain(rgName));

                    resourceGroup = resourceManager.ResourceGroups.GetByName(rgName);
                    checkResourceGroup(resourceGroup);

                    // check tag list 
                    var resourceGroups = resourceManager.ResourceGroups.ListByTag("t3", "v3").ToList();

                    replacedert.Single(resourceGroups);
                    checkResourceGroup(resourceGroups.ElementAt(0));

                    // check tag list with single quotes also works
                    resourceGroups = resourceManager.ResourceGroups.ListByTag("'t2'", "'v2'").ToList();

                    replacedert.Single(resourceGroups);
                    checkResourceGroup(resourceGroups.ElementAt(0));

                    resourceGroup.Update()
                        .WithoutTag("t1")
                        .WithTag("t4", "v4")
                        .WithTag("t5", "v5")
                        .Apply();
                    replacedert.NotNull(resourceGroup.Tags);
                    replacedert.Equal(4, resourceGroup.Tags.Count);
                }
                finally
                {
                    try
                    {
                        TestHelper.CreateResourceManager().ResourceGroups.BeginDeleteByName(rgName);
                    }
                    catch
                    { }
                }
            }
        }

19 View Source File : Check.cs
License : MIT License
Project Creator : Azure

static void NonNegativeNumber<T>(T number, string argumentName = "argument") 
        {
            string typeName = typeof(T).Name;
            bool throwException = false;

            string exceptionString = string.Format("Only int32 and int64 is supported. Provided type '{0}' is not a valid applicable type for argument '{1}'", typeof(T).Name, argumentName);

            if(!IsNumericType(number))
            {
                throw new ArgumentOutOfRangeException(exceptionString);
            }

            if (!(typeof(T).Equals(typeof(Int32))) || !(typeof(T).Equals(typeof(long))))
            {
                throwException = true;
            }
            else if ((typeof(T).Equals(typeof(Int32))) || (typeof(T).Equals(typeof(long))))
            {
                if(typeName.Equals(typeof(Int32).Name, StringComparison.OrdinalIgnoreCase))
                {
                    int intNum = Convert.ToInt32(number);
                    if(intNum < 0)
                    {
                        throwException = true;
                    }
                }
                else if (typeName.Equals(typeof(Int64).Name, StringComparison.OrdinalIgnoreCase))
                {
                    Int64 intNum = Convert.ToInt64(number);
                    if (intNum < 0)
                    {
                        throwException = true;
                    }
                }
            }

            if(throwException == true)
            {
                throw new ArgumentOutOfRangeException(exceptionString);
            }
        }

19 View Source File : FindCustomerRelatedIssuesInvalidState.cs
License : MIT License
Project Creator : Azure

private bool ValidateServiceLabels(Issue issue, StringBuilder problemsWithTheIssue)
        {
            //   - Service attention requires a service label to be set
            //   - If 'Service' is set, service attention is required

            ImpactArea impactedArea = GetImpactArea(issue.Labels);
            // has service attention
            bool hreplacederviceAttentionLabel = issue.Labels.Any(i => StringComparer.OrdinalIgnoreCase.Equals(i.Name, Constants.Labels.ServiceAttention));

            if (!hreplacederviceAttentionLabel && impactedArea.HasFlag(ImpactArea.Service))
            {
                problemsWithTheIssue.Append("The Azure SDK team does not own any issues in the Service. ");
                return false;
            }

            bool hreplacederviceLabel = issue.Labels.Any(i => i.Color == "e99695" && i.Name != Constants.Labels.ServiceAttention);

            // check to see if it has a service label if service attention is set
            if (hreplacederviceAttentionLabel && !hreplacederviceLabel)
            {
                problemsWithTheIssue.Append("The issue needs a service label. ");
                return false;
            }

            // check to see if the issue has an ownership (one of Client, Mgmt, Service)
            if (impactedArea == ImpactArea.None)
            {
                problemsWithTheIssue.Append("The issue needs an impacted area (i.e. Client, Mgmt or Service). ");
                return false;
            }

            // the issue should not have more than 1 type of labels to indicate the type.
            if ((impactedArea & (impactedArea - 1)) != 0)
            {
                problemsWithTheIssue.Append("The impacted area must have just one of the 'Client', 'Mgmt', 'Service', 'EngSys' and 'EngSys-Mgmt' labels. ");
                return false;
            }

            return true;
        }

19 View Source File : FindCustomerRelatedIssuesInvalidState.cs
License : MIT License
Project Creator : Azure

private IssueType GetIssueType(IReadOnlyList<Label> labels)
        {
            IssueType type = IssueType.None;
            foreach (Label label in labels)
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.Bug))
                {
                    type |= IssueType.Bug;
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.Feature))
                {
                    type |= IssueType.Feature;
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.Question))
                {
                    type |= IssueType.Question;
                }
            }
            return type;
        }

19 View Source File : FindCustomerRelatedIssuesInvalidState.cs
License : MIT License
Project Creator : Azure

private ImpactArea GetImpactArea(IReadOnlyList<Label> labels)
        {
            ImpactArea area = ImpactArea.None;
            foreach (Label label in labels)
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.Client))
                {
                    area |= ImpactArea.Client;
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.Mgmt))
                {
                    area |= ImpactArea.Mgmt;
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.Service))
                {
                    area |= ImpactArea.Service;
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.EngSys))
                {
                    area |= ImpactArea.EngSys;
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(label.Name, Constants.Labels.MgmtEngSys))
                {
                    area |= ImpactArea.MgmtEngSys;
                }
            }
            return area;
        }

19 View Source File : ObjectEx.cs
License : MIT License
Project Creator : Azure

public static T? ToNullable<T>(this T value, T nil) where T : struct {
            return EqualityComparer<T>.Default.Equals(value, nil) ? (T?)null : value;
        }

19 View Source File : StringEx.cs
License : MIT License
Project Creator : Azure

public static bool EqualsIgnoreCase(this string str, string to) {
            return StringComparer.OrdinalIgnoreCase.Equals(str, to);
        }

19 View Source File : IPAddressEx.cs
License : MIT License
Project Creator : Azure

public static bool IsEmpty(this IPAddress address) {
            return address == null ||
address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any) ||
address.Equals(IPAddress.None) || address.Equals(IPAddress.IPv6None);
        }

19 View Source File : PhysicalAddressEx.cs
License : MIT License
Project Creator : Azure

public static bool IsEmpty(this PhysicalAddress address) {
            return address == null || address.Equals(PhysicalAddress.None);
        }

19 View Source File : IPv4Address.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object comparand) {
            return base.Equals(comparand);
        }

19 View Source File : NetInterface.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object obj) {
            return obj is NetInterface context &&
                EqualityComparer<PhysicalAddress>.Default.Equals(
                    MacAddress, context.MacAddress) &&
                EqualityComparer<IPAddress>.Default.Equals(
                    UnicastAddress, context.UnicastAddress) &&
                EqualityComparer<IPAddress>.Default.Equals(
                    SubnetMask, context.SubnetMask) &&
                EqualityComparer<IPAddress>.Default.Equals(
                    Gateway, context.Gateway) &&
                // EqualityComparer<IPAddress>.Default.Equals(
                //     DnsServers, context.DnsServers) &&
                EqualityComparer<string>.Default.Equals(
                    DnsSuffix, context.DnsSuffix);
        }

19 View Source File : DiscovererRegistration.cs
License : MIT License
Project Creator : Azure

public override bool Equals(object obj) {
            if (!(obj is DiscovererRegistration registration)) {
                return false;
            }
            if (!base.Equals(registration)) {
                return false;
            }
            if (ModuleId != registration.ModuleId) {
                return false;
            }
            if (LogLevel != registration.LogLevel) {
                return false;
            }
            if (Discovery != registration.Discovery) {
                return false;
            }
            if (AddressRangesToScan != registration.AddressRangesToScan) {
                return false;
            }
            if (!EqualityComparer<TimeSpan?>.Default.Equals(
                    NetworkProbeTimeout, registration.NetworkProbeTimeout)) {
                return false;
            }
            if (!EqualityComparer<int?>.Default.Equals(
                    MaxNetworkProbes, registration.MaxNetworkProbes)) {
                return false;
            }
            if (PortRangesToScan != registration.PortRangesToScan) {
                return false;
            }
            if (!EqualityComparer<TimeSpan?>.Default.Equals(
                    PortProbeTimeout, registration.PortProbeTimeout)) {
                return false;
            }
            if (!EqualityComparer<int?>.Default.Equals(
                    MaxPortProbes, registration.MaxPortProbes)) {
                return false;
            }
            if (!EqualityComparer<int?>.Default.Equals(
                    MinPortProbesPercent, registration.MinPortProbesPercent)) {
                return false;
            }
            if (!EqualityComparer<TimeSpan?>.Default.Equals(
                    IdleTimeBetweenScans, registration.IdleTimeBetweenScans)) {
                return false;
            }
            if (!EqualityComparer<SecurityMode?>.Default.Equals(
                    SecurityModeFilter, registration.SecurityModeFilter)) {
                return false;
            }
            if (!TrustListsFilter.DecodeAsList().SequenceEqualsSafe(
                    registration.TrustListsFilter.DecodeAsList())) {
                return false;
            }
            if (!SecurityPoliciesFilter.DecodeAsList().SequenceEqualsSafe(
                    registration.SecurityPoliciesFilter.DecodeAsList())) {
                return false;
            }
            if (!DiscoveryUrls.DecodeAsList().SequenceEqualsSafe(
                    registration.DiscoveryUrls.DecodeAsList())) {
                return false;
            }
            if (!Locales.DecodeAsList().SequenceEqualsSafe(
                    registration.Locales.DecodeAsList())) {
                return false;
            }
            return true;
        }

19 View Source File : ModuleLogOptions.cs
License : MIT License
Project Creator : Azure

public bool Equals(ModuleLogOptions other)
            => other != null &&
               this.ContentEncoding == other.ContentEncoding &&
               this.ContentType == other.ContentType &&
               EqualityComparer<ModuleLogFilter>.Default.Equals(this.Filter, other.Filter);

19 View Source File : DockerReportedRuntimeInfo.cs
License : MIT License
Project Creator : Azure

public bool Equals(DockerReportedRuntimeInfo other) =>
            other != null &&
            base.Equals(other) &&
            EqualityComparer<DockerPlatformInfo>.Default.Equals(this.Platform, other.Platform);

19 View Source File : AgentState.cs
License : MIT License
Project Creator : Azure

public bool Equals(AgentState other) =>
            other != null &&
            this.LastDesiredVersion == other.LastDesiredVersion &&
            this.SchemaVersion == other.SchemaVersion &&
            EqualityComparer<VersionInfo>.Default.Equals(this.Version, other.Version) &&
            EqualityComparer<DeploymentStatus>.Default.Equals(this.LastDesiredStatus, other.LastDesiredStatus) &&
            EqualityComparer<IRuntimeInfo>.Default.Equals(this.RuntimeInfo, other.RuntimeInfo) &&
            this.SystemModules.Equals(other.SystemModules) &&
            StringModuleDictionaryComparer.Equals(this.Modules.ToImmutableDictionary(), other.Modules.ToImmutableDictionary());

19 View Source File : DockerReportedUnknownRuntimeInfo.cs
License : MIT License
Project Creator : Azure

public bool Equals(DockerReportedUnknownRuntimeInfo other) =>
            other != null &&
            EqualityComparer<DockerPlatformInfo>.Default.Equals(this.Platform, other.Platform);

19 View Source File : DockerRuntimeInfo.cs
License : MIT License
Project Creator : Azure

public bool Equals(DockerRuntimeInfo other) =>
            other != null && this.Type == other.Type &&
            EqualityComparer<DockerRuntimeConfig>.Default.Equals(this.Config, other.Config);

19 View Source File : Program.cs
License : MIT License
Project Creator : Azure

static Option<T> GetConfigIfExists<T>(string fieldName, IConfiguration configuration, ILogger logger = default(ILogger))
        {
            T storageParamValue = default(T);
            try
            {
                storageParamValue = configuration.GetValue<T>(fieldName);
            }
            catch
            {
                logger?.LogError($"Cannot get parameter '{fieldName}' from the config");
            }

            return EqualityComparer<T>.Default.Equals(storageParamValue, default(T)) ? Option.None<T>() : Option.Some(storageParamValue);
        }

19 View Source File : SystemModules.cs
License : MIT License
Project Creator : Azure

public bool Equals(SystemModules other)
        {
            return other != null &&
                   EqualityComparer<Option<IEdgeHubModule>>.Default.Equals(this.EdgeHub, other.EdgeHub) &&
                   EqualityComparer<Option<IEdgeAgentModule>>.Default.Equals(this.EdgeAgent, other.EdgeAgent);
        }

19 View Source File : Update.cs
License : MIT License
Project Creator : Azure

bool Equals(Update<T> other) => EqualityComparer<T>.Default.Equals(this.From, other.From) && EqualityComparer<T>.Default.Equals(this.To, other.To);

19 View Source File : AmqpExceptionsHelper.cs
License : MIT License
Project Creator : Azure

public static AmqpException GetAmqpException(Exception ex)
        {
            // If this exception is an AmqpException with LinkRedirect or NotAllowed errors, return it.
            if (ex is AmqpException amqpException)
            {
                if (amqpException.Error.Condition.Equals(AmqpErrorCode.LinkRedirect) || amqpException.Error.Condition.Equals(AmqpErrorCode.NotAllowed))
                {
                    return amqpException;
                }
            }

            // Convert exception to EdgeAmqpException
            // TODO: Make sure EdgeAmqpException is thrown from the right places.
            EdgeAmqpException edgeHubAmqpException = GetEdgeHubAmqpException(ex);
            Error amqpError = GenerateAmqpError(edgeHubAmqpException);
            return new AmqpException(amqpError);
        }

19 View Source File : AmqpProtocolHead.cs
License : MIT License
Project Creator : Azure

async Task OpenAmqpConnectionAsync(AmqpConnection amqpConnection, TimeSpan defaultTimeout)
        {
            if (await SafeOpenConnectionAsync())
            {
                try
                {
                    if (this.incomingConnectionMap.TryAdd(amqpConnection.Identifier.Value, amqpConnection))
                    {
                        amqpConnection.SafeAddClosed((s, e) => this.incomingConnectionMap.TryRemove(amqpConnection.Identifier.Value, out AmqpConnection _));
                    }
                    else
                    {
                        Events.ConnectionContextAddFailed(amqpConnection.Identifier.Value);
                    }
                }
                catch (Exception e) when (!e.IsFatal())
                {
                    Events.OpenConnectionError(e);
                    amqpConnection.SafeClose(e);
                }
            }

            async Task<bool> SafeOpenConnectionAsync()
            {
                try
                {
                    await amqpConnection.OpenAsync(defaultTimeout);
                    return true;
                }
                catch (Exception e) when (!e.IsFatal())
                {
                    Events.AmqpConnectionOpenAsyncFailed(e);

                    switch (e)
                    {
                        case OperationCanceledException _:
                            amqpConnection.SafeClose(new EdgeHubConnectionException("Operation Canceled Exception"));
                            break;

                        case TimeoutException _:
                            amqpConnection.SafeClose(new EdgeHubConnectionException("Timeout Exception"));
                            break;

                        case IOException _:
                            amqpConnection.SafeClose(new EdgeHubConnectionException("IO Exception"));
                            break;

                        case SocketException _:
                            amqpConnection.SafeClose(new EdgeHubConnectionException("Socket Exception"));
                            break;

                        case AmqpException ae when ae.Error.Condition.Equals(AmqpErrorCode.ConnectionForced):
                            amqpConnection.SafeClose(new EdgeHubConnectionException("AMQP connection forced exception"));
                            break;

                        default:
                            amqpConnection.SafeClose(e);
                            break;
                    }

                    return false;
                }
            }
        }

19 View Source File : DependencyManager.cs
License : MIT License
Project Creator : Azure

Option<T> GetConfigurationValueIfExists<T>(string key)
            where T : clreplaced
        {
            var value = this.configuration.GetValue<T>(key);
            return EqualityComparer<T>.Default.Equals(value, default(T)) ? Option.None<T>() : Option.Some(value);
        }

19 View Source File : DependencyManager.cs
License : MIT License
Project Creator : Azure

Option<T> GetConfigIfExists<T>(string fieldName, IConfiguration configuration, ILogger logger = default(ILogger))
        {
            T storageParamValue = default(T);
            try
            {
                storageParamValue = configuration.GetValue<T>(fieldName);
            }
            catch
            {
                logger?.LogError($"Cannot get parameter '{fieldName}' from the config");
            }

            return EqualityComparer<T>.Default.Equals(storageParamValue, default(T)) ? Option.None<T>() : Option.Some(storageParamValue);
        }

See More Examples