Wednesday, December 26, 2018

Howto convert a PFX to a seperate .key/.crt file

openssl pkcs12 -in [yourfile.pfx] -nocerts -out [keyfile-encrypted.key]
What this command does is extract the private key from the .pfx file. Once entered you need to type in the importpassword of the .pfx file.  This is the password that you used to protect your keypair when you created your .pfx file.  If you cannot remember it anymore you can just throw your .pfx file away, cause you won’t be able to import it again, anywhere!.  Once you entered the import password OpenSSL requests you to type in another password, twice!. This new password will protect your .key file.
Now let’s extract the certificate:
openssl pkcs12 -in [yourfile.pfx] -clcerts -nokeys -out [certificate.crt]
Just press enter and your certificate appears.
Now as I mentioned in the intro of this article you sometimes need to have an unencrypted .key file to import on some devices.  I probably don’t need to mention that you should be carefully. If you store your unencrypted keypair somewhere on an unsafe location anyone can have a go with it and impersonate for instance a website or a person of your company.  So always be extra careful when it comes to private keys! Just throw the unencrypted keyfile away when you’re done with it, saving just the encrypted one.
The command:
openssl rsa -in [keyfile-encrypted.key] -out [keyfile-decrypted.key]
Again you need to enter an import password. This time you need to enter the new password that you created in step 1.  After that you’re done. You decrypted your private key. In the folder you ran OpenSSL from you’ll find the certifcate (.crt) and the two private keys (encrypted and unencrypted).

Ref: https://www.markbrilman.nl/2011/08/howto-convert-a-pfx-to-a-seperate-key-crt-file/
Ref: https://aws.amazon.com/blogs/security/how-to-import-pfx-formatted-certificates-into-aws-certificate-manager-using-openssl/#:~:text=To%20import%20the%20certificates,Select%20Import%20a%20certificate.

Sunday, August 26, 2018

Self Contained ASP.NET Core Deployments

dotnet publish ProjectName.csproj --self-contained:true --runtime:win10-x64 /nologo /p:PublishProfile=Release  /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /maxcpucount:1 /p:platform="Any CPU" /p:configuration="Release" /p:DesktopBuildPackageLocation="$\project.zip"

--runtimeIdentifier: it is necessary. Also, you need to specify the supported runtime identifier in your poject file.
(https://docs.microsoft.com/en-us/dotnet/core/rid-catalog)

Commands
https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish?tabs=netcore21

Wednesday, June 27, 2018

How to take dumps for an Azure Web App from Debug Cosole - Kudu

Create the folder where you would like to take dumps and then run following command.

Get the process id from the process explorer.

d:\devtools\sysinternals\procdump -accepteula -ma {Process ID}

Monday, May 28, 2018

Git Commands

To revert local check in. 
git reset Head~1

To view the changes recently reset, 
git reflog show HEAD
or 
git reflog.

This will show you your recent resets and other history.
You can restore it again using following command.
git reset --hard <commit hash>

above command will destroy any local modifiction so better stash them.


To merge your development branch into master.  

1. Check out the branch. 

git checkout development

2.Merge your changes from master into development. (This step is necessary so that you can resolve any merge conflict locally in your development branch. )

git merge development

3.  Check out the master branch now. 

git checkout master

4. Merge the development branch into master. (Make sure to use --no-ff to persist your history.)

git merge --no-ff development. 

5. Push your changes to the master. 




Thursday, May 10, 2018

Getting all Users from AAD using Power Shell and Delete

Connect-MsolService
Get-MsolUser
#get the user principle name.
Connect-AzureAD
Remove-AzureADUser -ObjectId "xxxx.onmicrosoft.com#EXT#@yyyy.onmicrosoft.com"

UPN of the external accounts is as shown above. 

Thursday, May 3, 2018

Storing secrets using SecretManager for development in ASP.NET Core

The purpose of using this is to keep the secured values outside of the code to avoid check in by mistake.

- Modify the .csproj file and add following "Microsoft.Extensions.SecretManager.Tools"

- Save and close.
- Right click the project and select "Manage User Secrets"
- this will open JS. store your secret values in there.  This json file is stored away from the project on local machine.
- Add following into your Startup.cs file.

if (_hostingEnvironment.IsDevelopment())
            {
                builder.AddUserSecrets<Startup>();
            }

- read the secret using Configuration. like if the secret name is "MySecret", read it like Configuration["MySecret"]
-This should only be used in development.
- For production, code will read the value from appsettings.json. 

Routing Trace to Console

ConsoleTraceListener listener = new ConsoleTraceListener();
Trace.Listeners.Add(listener);

Trace.WriteLine("Trace Logs");

Trace.Listeners.Remove(listener);

Trace.Close();

Tuesday, April 10, 2018

constructor with parameter in .net core dependency injection

In .net core you register the dependency like

services.AddSingleton<IConfigsService, ConfigsService>();

If ConfigureService is taking parameter there is no way out of the box to pass the parameter value.

So in order to fix that, add the nuget parameter "Microsoft.Extensions.DependencyInjection"

services.AddTransient<IConfigsService>(c => new ConfigsService("Pass your data"));

And that should do it.

Thanks,

Tuesday, March 27, 2018

Delete a key from registry - Permission denied issue

get psexec is available from Microsoft here

And then go to the folder of psexec and run following command. 
psexec -i -d -s c:\windows\regedit.exe

It will open regedit. then set the permisison in there and then you can delete. 


Thursday, March 8, 2018

Flush IIS Logs in Real Time

Use following command to flush IIs Logs in real time without 60 seconds wait.

netsh http flush logbuffer

can run following command in background 

while true; do netsh http flush logbuffer > /dev/null; sleep 1; done &

and then tail
tail -100f u_ex130814.log

Tuesday, March 6, 2018

Trace WCF communication in Fiddler

Add following in your web.config file. makes sure that fiddler proxy port (8888) is correct. (in Tools --> Options --> Connections)

<system.net>
<defaultProxy>
<proxy bypassonlocal="False" usesystemdefault="True" proxyaddress="http://127.0.0.1:8888" />
</defaultProxy>
</system.net>

Monday, February 26, 2018

Thursday, February 22, 2018

Async Await support for Console Applications

Nito.AsyncEx is the library which can be used to add support for Console application. (not limited to console application.)
Add the nuget package - Nite.AsyncEx

And then call your function as

AsyncContext.Run(() => ExecuteMethodAsync());

private static async Task ExecuteMethodAsync()
{
//do something
}

Happy Coding!

Thursday, February 15, 2018

Sample Code to open PDF File in Browser instead of download



public HttpResponseMessage Get(int id)
{
try
{
string filename = "File.pdf";
string filepath = System.Web.HttpContext.Current.Server.MapPath("~") + "/" + filename;
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(filedata); ;
result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filepath));
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};

HttpContext.Current.Response.Headers.Add("Content-Disposition", cd.ToString());
return result;

}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}

Converting a guest user to member in Azure AD

To convert a guest user into a member in Azure Ad run the following command.


Connect-MsolService
login with Global admin of the AD in which guest user exists.

Get-MsolUser -UserPrincipalName hpatel#EXT#@yourdomain.onmicrosoft.com -UserType Member

This should convert the user to member.
hpatel#EXT#@yourdomain.onmicrosoft.com is the guest user. remember Microsoft adds #EXT# to the email. so if you get error that says that user not found, run the following command and validate the upn.
Get-MsolUser --UnlicensedUserOnly