Document Converter
or drag and drop file here
Techies can do programming like Joy
or drag and drop file here
Azure B2B Token auth once of best way for auth.
Way to Generate Auth Token:
public async Task<DataResponse> GenerateB2BToken()
{
List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(CLIENT_CREDENTIALS),
new KeyValuePair<string, string>(B2CClientId),
new KeyValuePair<string, string>(B2CClientSecret),
new KeyValuePair<string, string>(B2BResource)
};
using (var client = new HttpClient())
{
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
FormUrlEncodedContent content = new FormUrlEncodedContent((List<KeyValuePair<string, string>>)postData);
using HttpResponseMessage response = await client.PostAsync(urlPath, content);
{
var responsedata = await response.Content.ReadAsStringAsync();
return responsedata;
}
}
if (!string.IsNullOrEmpty(response))
{
TokenAuthData token = JsonConvert.DeserializeObject<TokenAuthData>(response);
if (token != null && !string.IsNullOrWhiteSpace(token.token_type) && !string.IsNullOrWhiteSpace(token.access_token))
{
return Json( new { Token = $"{token.token_type} {token.access_token}" });
}
}
return null;
}
Token Validation :
public async Task<bool> ValidateB2BToken(string idtoken)
{
string _token = idtoken.Replace(BEARER, "").Replace(BEARER.ToUpper(), "").Trim();
if (!string.IsNullOrEmpty(_token))
{
try
{
var token = new JwtSecurityToken(jwtEncodedString: _token);
if (token.Claims != null && token.Claims.Count() > 0)
{
var expiry = long.Parse(token.Claims.Where(x => x.Type == "exp").Select(x => x.Value).FirstOrDefault());
var aud = token.Audiences.Where(x => x == "your client id").Select(x => x).FirstOrDefault();
long epochTime = await ToUnixTime(DateTime.UtcNow);
//validate expiry and audience
if (!string.IsNullOrEmpty(aud) && epochTime <= expiry)
{
return true;
}
else
return false;
}
}
catch (Exception ex)//Token expired case
{
return false;
}
}
return false;
}
private async Task<long> ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return await Task.FromResult( Convert.ToInt64((date - epoch).TotalSeconds));
}
Above way you can validate Token auth B2b
Recently I faced issue while pushing more files to GIT, here is solution if you face similar error message which title of this blog represent,
unable to rewind rpc post data - try increasing http.postBuffer
Error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054
send-pack: unexpected disconnect while reading sideband packet
Solution:
Open command prompt and copy paste below line hit on enter,
git config http.postBuffer 524288000
Above statement will increase http write buffer size, huge number of file you can able to push then.
Recent time I've faced challenge while mysql table truncation data,
Cannot truncate a table referenced in a foreign key constraint
In above case error,
MySQL Query:
SET FOREIGN_KEY_CHECKS = 0;
truncate table mydb.TableName
SET FOREIGN_KEY_CHECKS = 1;
You could able to do truncate entire table which having foreign key as well.
Azure key vault is one of best secure place to dealing with secret exchange through azure cloud storage.
Benefits:
using Azure.Identity;using Azure.Security.KeyVault.Secrets;using System;using System.Collections.Generic;using System.Collections.Specialized;using System.Configuration;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace VaultService{public class KeyVaultHelper{private static NameValueCollection appSettings = ConfigurationManager.AppSettings;public static string AzureKeyVaultUrl; //=appSettings["AzureKeyVaultUrl"];public static string TenantId; //= appSettings["TenentId"];public static string ClientId; //= appSettings["SASClientId"];public static string Secrets; //= appSettings["SASClientSecret"];public KeyVaultHelper(){if (appSettings != null &&string.IsNullOrWhiteSpace(AzureKeyVaultUrl)|| string.IsNullOrWhiteSpace(TenantId)|| string.IsNullOrWhiteSpace(ClientId)|| string.IsNullOrWhiteSpace(Secrets)){AzureKeyVaultUrl = appSettings["AzureKeyVaultUrl"];TenantId = appSettings["SASTenantId"];ClientId = appSettings["SASClientId"];Secrets = appSettings["SASClientSecret"];}}private static async Task SetEnvVariableToKeyValut(){AzureKeyVaultUrl = appSettings["AzureKeyVaultUrl"];TenantId = appSettings["SASTenantId"];ClientId = appSettings["SASClientId"];Secrets = appSettings["SASClientSecret"];await Task.CompletedTask;}
//GET SECRET CLIENT
private static async Task<SecretClient> GetSecretClient(){SecretClientOptions options = new SecretClientOptions(){Retry ={Delay= TimeSpan.FromSeconds(2),MaxDelay = TimeSpan.FromSeconds(16),MaxRetries = 5,Mode = Azure.Core.RetryMode.Exponential},};if(string.IsNullOrEmpty(TenantId) || string.IsNullOrEmpty(ClientId) || string.IsNullOrEmpty(Secrets)){await SetEnvVariableToKeyValut();}ClientSecretCredential clientSecretCredential = new ClientSecretCredential(TenantId,ClientId, Secrets);var secretClient = new SecretClient(new Uri(AzureKeyVaultUrl), clientSecretCredential);return await Task.FromResult(secretClient);}public static async Task<string> GetKeyVaultValueAsync(string key){try{//Get ket valutvar cancelToken = new CancellationToken();SecretClient secretClient = await GetSecretClient();KeyVaultSecret keyVaultSecret = await secretClient.GetSecretAsync(key, null, cancelToken);return await Task.FromResult(keyVaultSecret?.Value);}catch (Exception ex){return string.Empty;}}public static async Task<bool> SetKeyVaultValueAsync(string key, string value, SecretClient client = null){// Create a new secret using the secret client.var cancelToken = new CancellationToken();try{if (client == null){client = await GetSecretClient();}KeyVaultSecret secret = await client.SetSecretAsync(key, value, cancelToken);return await Task.FromResult(secret != null ? true : false);}catch (Exception exx){return false;}}public static async Task<bool> DeleteVaultValueAsync(string key, SecretClient client = null){// Delete a new secret using the secret client.var cancelToken = new CancellationToken();try{if (client == null){client = await GetSecretClient();}var secret = await client.StartDeleteSecretAsync(key, cancelToken);return await Task.FromResult(secret != null ? true : false);}catch (Exception ex){return false;}}}}
Above code snippet use-ful while consuming Key vault.
Please feel free to connect in-case if you face any challenge, gjinformatic@gmail.com or comment here.
If you having issue with DELL leptop stuck at 99% , please check report with below commands.
powercfg /batteryreport /output "C:\bettery-report.html"
If still if you face challenge then upgrade BIOS drivers. and then check, or else your battery performance might be impacted.
Hello all,
Some of coolest topics , I came across, ExpandoObject in C#
dynamic dynamicObject = new ExpandoObject();
While addiing into code base, found compile time error,
Error CS0656 Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
To over come from this, You need to add a reference to the DLL Microsoft.CSharp.dll.
It will resolve your compile time error, and you can take benifitws of ExpandoObject.
Today I have observe one of error , which while we are extracting and building with node.
I was facing some challenges,
FATAL ERROR: heap limit Allocation failed - JavaScript heap out of memory.
node --max_old_space_size=8000
By using this in command line or environment variable setting we can able to extend size of allocation.
Generally Visual studio or Other tool through while running application we will face such problem.
For watch on command and extend the allocation size :
node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng build --watch
this will be same command you can use in powershall windows or cmd.
It will resolve allocation size memory issue.
- //Nicer way to understand execution
- public class Program
- {
- public static void Main(string[] args)
- {
- CreateWebHostBuilder(args).Build().Run();
- }
- public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup<TestClass>();
- }
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- ….
- ….
- services.AddSession();
- services.AddMvc();
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- ….
- ….
- app.UseSession();
- ….
- ….
- }
- }
- Example:
- //HTML Helper
- @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", placeholder = "Enter Your First Name" })
- //content with tag helper
- <input asp-for="FirstName" placeholder="Enter Your First Name" class="form-control" />
- //Equivalent HTML
- <input placeholder="Enter Your First Name" class="form-control" id="FirstName" name="FirstName" value="" type="text">
- <!span asp-validation-for="phone" class="divPhone"></!span>
- @page
- <h1> Hello, Book Reader!</h1>
- <h2> This is Razor Pages </h2>
- public class Test1Model : PageModel
- {
- [BindProperty]
- public string Name { get; set; }
- }
- public interface IHelloWorldService
- {
- string SaysHello();
- }
- public class HelloWorldService: IHelloWorldService
- {
- public string SaysHello()
- {
- return "Hello ";
- }
- }
- public void ConfigureServices(IServiceCollection services)
- {
- ….
- …
- services.AddTransient<IHelloWorldService, HelloWorldService>();
- …
- …
- }
- public class HomeController: Controller
- {
- IHelloWorldService _helloWorldService;
- public HomeController(IHelloWorldService helloWorldService)
- {
- _helloWorldService = helloWorldService;
- }
- }
- services.AddSingleton<IHelloWorldService, HelloWorldService>();
- services.AddTransient<IHelloWorldService, HelloWorldService>();
- services.AddScoped<IHelloWorldService, HelloWorldService>();