Raki
Raki
CC#
Created by Raki on 8/7/2024 in #help
Is there a way I can improve this code? I feel its kind of hard to understand
c#

var plasticWay = await (from plastic in _context.plasticWays
join assetFrom in _context.Assets on plastic.plasticFrom equals assetFrom.Id
join assetTo in _context.Assets on plastic.plasticTo equals assetTo.Id
join categoryFrom in _context.AssetsCategory on assetFrom.CategoryId equals categoryFrom.Id
join categoryTo in _context.AssetsCategory on assetTo.CategoryId equals categoryTo.Id
where plastic.Id == id
select new plasticWayResponse
{
Id = plastic.Id,
plasticWayFrom = new plasticWayFrom
{
AssetName = assetFrom.AssetName,
AssetCategoryName = categoryFrom.CategoryName
},
plasticWayTo = new plasticWayTo
{
AssetName = assetTo.AssetName,
AssetCategoryName = categoryTo.CategoryName
},
Source = plastic.Source,
AvailableFrom = plastic.AvailableFrom,
AvailableTo = plastic.AvailableTo

}).FirstOrDefaultAsync();
return plasticWay ?? throw new KeyNotFoundException("plasticWayId not found");

c#

var plasticWay = await (from plastic in _context.plasticWays
join assetFrom in _context.Assets on plastic.plasticFrom equals assetFrom.Id
join assetTo in _context.Assets on plastic.plasticTo equals assetTo.Id
join categoryFrom in _context.AssetsCategory on assetFrom.CategoryId equals categoryFrom.Id
join categoryTo in _context.AssetsCategory on assetTo.CategoryId equals categoryTo.Id
where plastic.Id == id
select new plasticWayResponse
{
Id = plastic.Id,
plasticWayFrom = new plasticWayFrom
{
AssetName = assetFrom.AssetName,
AssetCategoryName = categoryFrom.CategoryName
},
plasticWayTo = new plasticWayTo
{
AssetName = assetTo.AssetName,
AssetCategoryName = categoryTo.CategoryName
},
Source = plastic.Source,
AvailableFrom = plastic.AvailableFrom,
AvailableTo = plastic.AvailableTo

}).FirstOrDefaultAsync();
return plasticWay ?? throw new KeyNotFoundException("plasticWayId not found");

3 replies
CC#
Created by Raki on 1/30/2024 in #help
Reading MSDN document what does this mean while reading local function
One of the useful features of local functions is that they can allow exceptions to surface immediately. For iterator methods, exceptions are surfaced only when the returned sequence is enumerated, and not when the iterator is retrieved. For async methods, any exceptions thrown in an async method are observed when the returned task is awaited.
I can understand with async method so while returning async only we will come to know about exceptions. Just for understanding so For iterator methods, exceptions are surfaced only when the returned sequence is enumerated, So this means when we enumerate like the collection is read like using for loop. But what this means and not when the iterator is retrieved
3 replies
CC#
Created by Raki on 1/27/2024 in #help
Can anyone explain Bulkhead policy in polly
Can anyone explain Bulkhead policy in polly I want to send API calls to an external API that only allows 10 calls per second. Therefore, I need my program to be limited to making only 10 HTTP calls per second. Additionally, if I encounter a 429 error (too many requests), I want to retry that call. I learned about the Bulkhead pattern from this article: https://medium.com/@ynskrn54/using-polly-and-the-bulkhead-pattern-in-net-f4a9639e2fcd, which helps in preventing overwhelming the external API. I have written some code based on this pattern. My understanding is that this code will manage 10 calls at a time in a queue. For instance, if I have 30 HTTP calls to make, they will be queued and processed at a rate of 10 calls per second. Is the below code serve my purpose
C#
/Setting the policy
var bulkHeadPolicy = Policy.BulkheadAsync < HttpResponseMessage > (10, 1);

//Defining it in Startup.cs
services
.AddHttpClient < IContentfulManagementService, ContentfulManagementService > ((s, c) => {
c.BaseAddress = new Uri(managementApiURL);
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", managementApiKey);
c.Timeout = timeout;
})
.AddTransientHttpErrorPolicy(ErrorPolicy) .AddPolicyHandler(timeoutPolicy).AddTransientHttpErrorPolicy(retryErrorPolicy).AddPolicyHandler(bulkHeadPolicy);

//Retry when it errors out
private static Func < PolicyBuilder < HttpResponseMessage > , IAsyncPolicy < HttpResponseMessage >> retryErrorPolicy =>
p => p.Or < BulkheadRejectedException > ().WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
C#
/Setting the policy
var bulkHeadPolicy = Policy.BulkheadAsync < HttpResponseMessage > (10, 1);

//Defining it in Startup.cs
services
.AddHttpClient < IContentfulManagementService, ContentfulManagementService > ((s, c) => {
c.BaseAddress = new Uri(managementApiURL);
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", managementApiKey);
c.Timeout = timeout;
})
.AddTransientHttpErrorPolicy(ErrorPolicy) .AddPolicyHandler(timeoutPolicy).AddTransientHttpErrorPolicy(retryErrorPolicy).AddPolicyHandler(bulkHeadPolicy);

//Retry when it errors out
private static Func < PolicyBuilder < HttpResponseMessage > , IAsyncPolicy < HttpResponseMessage >> retryErrorPolicy =>
p => p.Or < BulkheadRejectedException > ().WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
4 replies
CC#
Created by Raki on 1/25/2024 in #help
How to slow down my api call to a external service using polly
How to reduce or slow down my api to call external system. I want to call contentful cms but they have limited 10 calls per second. Now when there is a large number of changes. I believe it exceeded the limit and start to throw 429 rate limiting error. So I want to slow down my request to contentful so that only 10 calls are send to it per second. How to achieve it in .net polly.
7 replies
CC#
Created by Raki on 1/24/2024 in #help
How does option work in .net core
I have the below class here the contentfulclient base has a class called ContentfulClientBase which has a property called as contentfuloption with some property. I want to assign the value to one of the property. I have my own contentfuloption class which has some of the properties of ContentfulClientBase class contentfuloption. I want to pass my model value to contentfulclientbase class. But I don't know how to achieve it. When I use _options = options.Value; I get an error states type to type conversion is not possible. Basically I want my baseclass property should get my value which I provide. public class ContentfulManagementService : ContentfulClientBase, IContentfulManagementService { private readonly ILogger<ContentfulManagementService> _logger; private readonly Models.ContentfulOptions _contentfulOptions; public ContentfulManagementService( HttpClient httpClient, ILogger<ContentfulManagementService> logger, IOptions<Models.ContentfulOptions> options) { _httpClient = httpClient; _logger = logger; _contentfulOptions = options.Value; } }
99 replies
CC#
Created by Raki on 1/22/2024 in #help
How to write retry policy in .net
I have the below code which is called by a webhook. It does a post call to a cms which has a rate limiting policy where it allows only 10 calls per second. So how to write a retry policy the api calls fails.
c#
public async Task HandleRedirectAsync(string slug, string previousSlug, string contentTypeId, string entryId)
{
var endpoint = "entries";
if (!string.IsNullOrEmpty(slug))
{
var isPreviousSlugNotEmpty = !String.IsNullOrEmpty(previousSlug);
var isSlugAndPreviousSlugSame = slug == previousSlug;


if (isPreviousSlugNotEmpty && isSlugAndPreviousSlugSame)
{
return;
}

await DeleteRedirectLoopsAsync(slug, contentTypeId, endpoint);


if (isPreviousSlugNotEmpty && !isSlugAndPreviousSlugSame)
{
await CreateAndPublishRedirectEntryAsync(entryId, previousSlug, slug);
}
await UpdateEntryAsync(contentTypeId, entryId);
}
}
c#
public async Task HandleRedirectAsync(string slug, string previousSlug, string contentTypeId, string entryId)
{
var endpoint = "entries";
if (!string.IsNullOrEmpty(slug))
{
var isPreviousSlugNotEmpty = !String.IsNullOrEmpty(previousSlug);
var isSlugAndPreviousSlugSame = slug == previousSlug;


if (isPreviousSlugNotEmpty && isSlugAndPreviousSlugSame)
{
return;
}

await DeleteRedirectLoopsAsync(slug, contentTypeId, endpoint);


if (isPreviousSlugNotEmpty && !isSlugAndPreviousSlugSame)
{
await CreateAndPublishRedirectEntryAsync(entryId, previousSlug, slug);
}
await UpdateEntryAsync(contentTypeId, entryId);
}
}
7 replies
CC#
Created by Raki on 1/20/2024 in #help
Beginner question. what does this createhostbuilder do?
I'm learning .net core and I saw this code in program.cs. I can understand the main method calls this createhostbuilder which in turn sets some config value. But what I don't know is from where this configuration comes. where does this config.AddKeyPerfile do. Can anyone explain
c#
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddKeyPerFile(directoryPath: Path.Combine(Directory.GetCurrentDirectory(), "secrets"), optional: true);
config.AddKeyPerFile(directoryPath: Path.Combine(Directory.GetCurrentDirectory(), "platform-secrets"), optional: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
c#
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddKeyPerFile(directoryPath: Path.Combine(Directory.GetCurrentDirectory(), "secrets"), optional: true);
config.AddKeyPerFile(directoryPath: Path.Combine(Directory.GetCurrentDirectory(), "platform-secrets"), optional: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
4 replies
CC#
Created by Raki on 1/18/2024 in #help
Please help, Hi I need to write unit test for the following methods
I have my code with 3 to 4 methods I need to write unit test for them Any ideas. As you can see all are method which only calls http methods. I already wrote few to check whether they call the correct entry in xunit similar to below. Reaching to the community for your code review comments for the fiddler code and possibility of any unit testing beyond the one which I have written below. https://paste.mod.gg/wvyxvurvrzuh/0
c#
[Fact]
public async Task ContentfulManagementClient_CreateEntry_IfSlugAndPreviousSlugDifferent()
{
//// Arrange
var contentTypeId = "pagePatientProfessionalArticle";
var entryId = "test";
var slug = "/newtest1";
var previousSlug = "/newtest2";

var r = new StreamReader("../../../mockdata/RedirectEntryModel.json");
var json = r.ReadToEnd();

SetupResponseJson(HttpStatusCode.OK, json);

// act
await _sut.HandleRedirectAsync(slug, previousSlug, contentTypeId, entryId);

//act
AssertRequest(HttpMethod.Put, $"/entries/{entryId}/published");
}
c#
[Fact]
public async Task ContentfulManagementClient_CreateEntry_IfSlugAndPreviousSlugDifferent()
{
//// Arrange
var contentTypeId = "pagePatientProfessionalArticle";
var entryId = "test";
var slug = "/newtest1";
var previousSlug = "/newtest2";

var r = new StreamReader("../../../mockdata/RedirectEntryModel.json");
var json = r.ReadToEnd();

SetupResponseJson(HttpStatusCode.OK, json);

// act
await _sut.HandleRedirectAsync(slug, previousSlug, contentTypeId, entryId);

//act
AssertRequest(HttpMethod.Put, $"/entries/{entryId}/published");
}
1 replies
CC#
Created by Raki on 1/16/2024 in #help
Need help on how to write unit tests in xunit for the code
c#
public async Task UpdateEntryAsync(string contentTypeId, string entryId, int? version, string endpoint)
{
var entryRequest = await _httpClient.GetAsync($"{endpoint}/{entryId}");
var entryContent = await entryRequest.Content.ReadAsStringAsync();
dynamic getEntry = JsonConvert.DeserializeObject(entryContent);

//Update the PreviousSlug with current slug
getEntry.fields.previousSlug = getEntry.fields.slug;
var updatedEntryJson = JsonConvert.SerializeObject(getEntry);
var updatedEntryContent = new StringContent(updatedEntryJson, Encoding.UTF8, "application/json");

// Set headers for update request
updatedEntryContent.Headers.Add("X-Contentful-Content-Type", contentTypeId);
updatedEntryContent.Headers.Add("X-Contentful-Version", version.ToString());

await _httpClient.PutAsync($"{endpoint}/{entryId}", updatedEntryContent);

version++;
updatedEntryContent.Headers.Remove("X-Contentful-Version");
updatedEntryContent.Headers.Add("X-Contentful-Version", version.ToString());
await _httpClient.PutAsync($"{endpoint}/{entryId}/published", updatedEntryContent);
}
c#
public async Task UpdateEntryAsync(string contentTypeId, string entryId, int? version, string endpoint)
{
var entryRequest = await _httpClient.GetAsync($"{endpoint}/{entryId}");
var entryContent = await entryRequest.Content.ReadAsStringAsync();
dynamic getEntry = JsonConvert.DeserializeObject(entryContent);

//Update the PreviousSlug with current slug
getEntry.fields.previousSlug = getEntry.fields.slug;
var updatedEntryJson = JsonConvert.SerializeObject(getEntry);
var updatedEntryContent = new StringContent(updatedEntryJson, Encoding.UTF8, "application/json");

// Set headers for update request
updatedEntryContent.Headers.Add("X-Contentful-Content-Type", contentTypeId);
updatedEntryContent.Headers.Add("X-Contentful-Version", version.ToString());

await _httpClient.PutAsync($"{endpoint}/{entryId}", updatedEntryContent);

version++;
updatedEntryContent.Headers.Remove("X-Contentful-Version");
updatedEntryContent.Headers.Add("X-Contentful-Version", version.ToString());
await _httpClient.PutAsync($"{endpoint}/{entryId}/published", updatedEntryContent);
}
5 replies
CC#
Created by Raki on 9/21/2023 in #help
❔ How to set code expression value in web.config settings.
I want to set a c# code in web.config value like below. The value should be used by two different projects thats the reason I want it to be stored in the web.config.
<add key="ResName" value=DateTime.UtcNow.Ticks.ToString()/>
<add key="ResName" value=DateTime.UtcNow.Ticks.ToString()/>
9 replies
CC#
Created by Raki on 5/25/2023 in #help
❔ Why deconstuctor/Finalize example not working in vs 2022. Anything missing
using System;

class GCcollection
{
public GCcollection()
{
Console.WriteLine("Hey why are u creating me");
}

~GCcollection()
{
Console.WriteLine("Life is over, BYe");
}
}

class AsUsualMainClass
{
public static void Main(string[] args)
{
DoStuf();
}

public static void DoStuf()
{
var create = new GCcollection();
create = null;
GC.Collect();
Console.ReadKey();
}
}
using System;

class GCcollection
{
public GCcollection()
{
Console.WriteLine("Hey why are u creating me");
}

~GCcollection()
{
Console.WriteLine("Life is over, BYe");
}
}

class AsUsualMainClass
{
public static void Main(string[] args)
{
DoStuf();
}

public static void DoStuf()
{
var create = new GCcollection();
create = null;
GC.Collect();
Console.ReadKey();
}
}
14 replies
CC#
Created by Raki on 5/22/2023 in #help
why are thread.sleep, synchronous semaphore waits and other blocking calls harmful in async methods?
above is asked in a interview. what should be the answer. I replied that it will make the async operation useless since async will wait untill the process is executed in the mean time the thread will work on the next one
4 replies
CC#
Created by Raki on 4/12/2023 in #help
❔ Where to store the app service app settings variable so I can access them based on environment
8 replies
CC#
Created by Raki on 4/12/2023 in #help
❔ How to read configuration based on environment
I have a stored my connection string as configuration in web.config. Now I have stored the same connection string as application setting variable in app service. So now how to make my application to read from web.config while in dev environment and from app service which its deployed. Existing code to get the connectionstring:

public string GetConnectionString(string service)
{
var _tenantSettingsKey = _shellSettings.Name + ":" + service;
var _defaultSettingsKey = service;
var connectionStringSettings = ConfigurationManager.ConnectionStrings[_tenantSettingsKey] ?? ConfigurationManager.ConnectionStrings[_defaultSettingsKey];
if (connectionStringSettings == null)
{
throw new ConfigurationErrorsException("A connection string is expected for " + service);
}
return connectionStringSettings.ConnectionString;
}

public string GetConnectionString(string service)
{
var _tenantSettingsKey = _shellSettings.Name + ":" + service;
var _defaultSettingsKey = service;
var connectionStringSettings = ConfigurationManager.ConnectionStrings[_tenantSettingsKey] ?? ConfigurationManager.ConnectionStrings[_defaultSettingsKey];
if (connectionStringSettings == null)
{
throw new ConfigurationErrorsException("A connection string is expected for " + service);
}
return connectionStringSettings.ConnectionString;
}
2 replies
CC#
Created by Raki on 4/11/2023 in #help
❔ How to get azure cache for Redis connection string stored in app service as a appsetting variable
I have created a azure redis for cache and stored the connection string as application setting variable in app service using terraform. Now I want my code to access the connection string. In the existing application we explictly mentioned the connection string in web.config. So now I needed to get the azure appsetting variable via code. Any link or reference is appreciated
4 replies
CC#
Created by Raki on 12/2/2022 in #help
✅ How to check whether a given list is present in the List of list
I have a List<List<int>> candidates and before adding into it want to check whether a list is already present. The condition is true all the time. How to implement the check condition for each addition
var temp = new List<int>(tempList);
if(!candidates.Any(x => x == temp))
{
candidates.Add(temp);
}
var temp = new List<int>(tempList);
if(!candidates.Any(x => x == temp))
{
candidates.Add(temp);
}
8 replies
CC#
Created by Raki on 11/18/2022 in #help
❔ How bit wise shift operation work
I started learning bit wise operation. So i have a uint = 0101 bit which is int 5. Which is in loop to see how it works Consider n =0101 1st iteration var test = (n >> 0) // The value is 101 2nd iteration var test = (n >> 1) // The value of test is 50 How this Happens what i assumed is 0101 on 2nd iteration will become as 1010 so it will be 9. But how it becomes 50.
10 replies
CC#
Created by Raki on 11/14/2022 in #help
❔ Optional parameter throwing error
7 replies
CC#
Created by Raki on 11/8/2022 in #help
Diff between the Ilist and List
- IList<int> res = new List<int>(); - List<int> res = new List<int>(); what is the difference between the both which is considered as best practice.
3 replies
CC#
Created by Raki on 11/2/2022 in #help
Remove X-AspNetMvc-Version from the response.
1 replies