pages

Wednesday, 7 April 2021

Catching Exceptions with "when"

TLDR;
Use when with a catch block to get hold of exceptions without unwinding the stack.
You can use it to handle exception based on specific property, condition or context.


we were catching exceptions just fine before the introduction of when keyword. I must say, its a good feature released in C# 6.


catch (ExceptionType e) when (expression) 
expression should return a boolean value, if the result is true the ExceptionHandler executes. The only difference I found, it gives you provision to check the variables value in a debug session. I dont see any production value in this feature.


Exception filters (when):
The filter expression is evaluated before the stack is unwound. This means the original call stack and all local variables remain intact during filter evaluation.

  • Handling exception using specific property

    catch (IOException ex) when (ex.Message.Contains("access denied"))
    {                                                                 
        Console.WriteLine("File access denied. Check permissions.");  
        Console.WriteLine(ex.StackTrace);                             
    }                                                                 
    catch (IOException ex) when (ex.Message.Contains("not found")) { Console.WriteLine("File not found. Verify the path."); Console.WriteLine(ex.StackTrace); }
    catch (Exception ex) { Console.WriteLine("general catch all"); Console.WriteLine(ex.StackTrace); }

You wont get to see any difference in the above 3 stack traces printed in the exceptions.

It helps us in examining exception before deciding to handle them and lets us handle based on the context.


catch (IOException ex) when (filePath.contains(@"c:\users"))          
{                                                                     
    Console.WriteLine($"Network file operation failed: {ex.Message}");
}                                                                     


Why do we need multiple catch blocks? why not just use a catchall with (Exception)
  • Catching specific exceptions can help you take more granular decision based on the situation.
  • It can tell you a lot more about the error occurred using the properties specific to that Exception type. Yes they all are derived from Exception but every class has some specific properties limited to them and you can access them if you catch them. Exception handling is a feature that helps the developer to avoid getting embarrassed in front of the client. But using when clause in exception handling is a feature that helps the developer with getting to know about the error better.

Tuesday, 29 December 2020

Git - common commands [part -2]

git fetch what next, what is git pull

git pull is mix of two commands, git fetch and git merge.

git fetch: fetch gets all the changes from remote to your local, now it will be kept. you have to apply those changes on your code.

git merge: git merge origin/master (if you are on your branch) will merge those changes with yours.

git merge vs git rebase

git merge will merge your changes with remote.

git rebase will put yours on top of that.

How to add a local gitconfig

Adding a local gitconfig helps you with keeping different credentials or setting username/ authorname for the repository. You can add one for each repo.

Helpful when you are using multiple git sources(GitHub, BitBucket etc.)

<your-repository-path>\.git\config

git config --local --list to print all the settings.

When Git is not showing commit by your user as “your name”

make sure that you have correct username and email configured.

You can do this globally (for all the projects within your machine) or locally (for just one project)

use flag --global or --local accordingly.

git config --local user.email "abc@gmail.com"

git config --local user.name “abc xyz”

Editing and listing config details.

git config --global --edit

git config --global --list

Monday, 11 May 2020

Git - common commands

Below are some common git commands which help with almost anything you need to do with git day to day basis.


How to get the latest changes

  • git fetch: gets the latest changes from server, keep it in local without applying.
  • git pull: gets the latest changes from server, try to merge with your local to make sure your local is up-to date with the server. 
  • git rebase : rebase your working directory with the latest changes on the given branch 
  • git reset: reset all your local changes and moves you to latest head position available in local (if you have done git fetch before, this will be same position as server) Flags are listed below 
    • hard : lose all uncommited changes and all untracked files 
    • keep : It only resets the files which are different between the HEAD and local. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard. 
    • soft 
    • mixed 
  • Head~1 : points you to one commit before head, used with git reset.


Save your changes 

  • git stash: saves your changes in local. 
    • m : used to pass a message to stash (git stash -m "stash message") 
  • git stash pop: gets the latest stash and merge with your code. 
  • git commit: commits your changes to working directory. 
    • a : all 
    • m : used to pass a message to commit (git commit -m "commit message") 
  • git push: sends all the commits from working directory to server. 
    • u : upstream, pushes the local branch to server 

Miscellaneous 

  • git status : tell you about your working tree/directory 
  • git add : add the files to stage, ready for commit
    •  . : adds all the files 
  • git branch : tells about all the branches available 
  • git branch : creates a branch with that name 
  • git checkout : checkout the branch specified

Thursday, 23 April 2020

Override ToString in Csharp

First question that comes to mind is why should I do that. My answer is “for fun”. ;)
The code is pretty simple to write. Here is a sample.

There are two return statements. One return name and salary, while the other returns json string.

It is mostly recommended to override ToString for debugging purposes.

I was able to find a good stackoverflow answer written in 2012, talks about why we should do that.

There is an important note on msdn article on how to override ToString which is as below.

"When you decide what information to provide through this method, consider whether your class or struct will ever be used by untrusted code. Be careful to ensure that you do not provide any information that could be exploited by malicious code."

You can find the complete program here.





Tuesday, 11 February 2020

Using yield return in CSharp


I was not very sure on the use of yield return in C#, until I read completely about it in very simple manner. I will try my best to share all I learned in as simple words I can.

I know it’s a very old thing and many people online use it, but I believe there, still, are many developers like me who are avoiding it because all the books and articles explain it in very few words at very high level view.

So, let us just start with a simple premise, we need a function to return list of numbers from a very large sequence. An example can be to return the list of first 100 even numbers, assume that later on in the program we are processing our list of 100 even numbers. In your case it can be to pull the record of customers from database on certain condition.

Well there are many efficient ways to write the same program, I intentionally chose this, as this post is about keeping it simple.

If you keep the input as 100, there is no major memory allocation, but if the input is changed to 1million or more, the memory allocated for execution of the program increases drastically. Same can be checked using diagnostic tools in visual studio.


We live in the world where memory cost is always ignored against CPU, but that should not be our reason to fill the stack when we can do better.

yield return is a solution. I wrote the same program as above, the only difference is the return type. Instead of returning the List we are here returning IEnumberable.

Don’t even think of counting the elements in the sequence. This is IEnumerable, not IQueryable. IEnumberable<T> exist in System.Collections.Generic.
IQueryable exists in System.Linq. This article talks about the difference in detail.
You can find the complete program on github.

I hope this was easy. Please share your thoughts in the comments below.

Wednesday, 30 October 2019

Debugging Azure functions locally

Actually the title of this post should be "Debugging your serverless apps locally".
I found a utility while working on Azure functions which helps you debug the function locally(if you have the source code, obviously). It is called ngrok. They have a pretty awesome website and very simple docs.


Steps to proceed are as below.
  1. Make sure your Azure function is up and running in your machine and you are able to hit the breakpoint from your local.
  2. Signup on the ngrok website.
  3. Download the ngrok utility(its an exe file). double click to execute. It opens a command prompt.
  4. Connect to your account. Upon login to ngrok website you will get an auth token which you have to use to connect to your account. command to execute "ngrok authtoken <your_token_here>". This step will create a .yml file in your users directory.
  5. Create a tunnel. Use command "ngrok http 7071". 7071 is the port you want to expose. I used it because its the default port for Azure function apps.
  6. Use the url provided by the ngrok utility to hit the breakpoint on your function from the internet.
I hope this was easy. Please share your thoughts in the comments below.

Wednesday, 23 October 2019

Getting started with Azure Event Grid

As a human being, every new thing scares us. Same was the case with me when I tried started working on Azure Event Grid. No article I was able to find that works out steps by step. The learning curve looked steep almost vertical ;)
Well in this post I try to reduce those efforts for you. I will try to list out the details required to get you started with Event Grid.

Below image is taken from Microsoft Event Grid documentation website.




Azure Event Grid as its mentioned everywhere, its a way to publish/subscribe your events in an easy way. If your subscriber is down It tries in a Exponential back-off way to deliver the message for 24 hours.

First thing you should know is 'Topic'. What is a topic?
Topic is an endpoint where the source sends the event. To respond to certain types of events, subscribers decide which topics to subscribe to.


Event Grid provides below-mentioned event sources: (Topics are already available, you can subscribe to them easily)
  • Azure Subscriptions
  • Container Registry
  • Custom Topics
  • Event Hubs
  • IoT Hub
  • Media Services
  • Resource Groups (management operations)
  • Service Bus
  • Storage Blob
  • Azure Maps


Below mentioned Event Handlers are supported: (You can receive the events using any of the below mechanism)
  • Azure Automation
  • Azure Functions
  • Event Hubs
  • Hybrid Connections
  • Logic Apps
  • Microsoft Flow
  • Queue Storage
  • Service Bus (Preview)
  • WebHooks

The good thing is that you can publish an event of your own using a schema (Custom topic). what it means in real world terms is you call an api with the data in specified format and it will work as event generated and event grid will push it to all the subscribers of that event.

There are three types of schema available.
In case of inbuilt event providers you can even apply filters to the event, so you will get the event you wish to.

Retry policies can be configured. You can also expire the event after certain time.

Please share your thoughts in the comments below.

Tuesday, 8 October 2019

Azure functions, A server less compute

First thing I thought about was "What does it mean when someone says its serverless?"

Well I have found my answer serverless doesn't mean it will not run on server first of all. 😉 It means that you don't have to worry about the server resources and other stuff. You just pay for the time your function is executing. If your function executes for 20 seconds per day well then you mostly will pay for that. You  can explore more about the pricing using the links given at the end of this post.

How to get started? Usually that is the most difficult thing to do.

Create a function is as simple as working on a console app. Open Visual Studio. Create new project of Azure functions type and you are done. :)

Make sure you select:
  1. Http Trigger
  2. Authorization: Anonymous
  3. Function Runtime (2.x)
  4. Storage Account (Storage Emulator) standalone installer

You are ready to go. Press F5 to run your solution, you can see a command window firing up (which has lot of node.js work behind the scenes). Wait till it gives you the URL which mostly is http://localhost:7071/api/function1if you have not done any changes in the default out of the box app.


There is a pretty comprehensive documentation available.

Azure Functions pricing

 Please share your thoughts in the comments below.

Wednesday, 2 October 2019

Connect to your broadband using win32 api using RasDial

So yesterday my router stopped working and new one will come in mail by today. Its one day that I was like without internet (not actually). I tried putting LAN directly to my laptop and connect to broadband. It worked like charm,  but the only problem I am facing now is connecting and disconnecting the connection. So, as a person who knows how to Google I tried finding a command to connect to internet by dialing up my broadband (PPPoE connection) and make it as a batch, just double click and it should work.

I found a command line utility called RasDial which is (RemoteAccessService). If you have already a network connection setup in your computer. you can directly open command prompt and type rasdial /? which gives you all the option to connect. If you have not done the setup yet you can check this link and do it.



Usage:
  1. Connection: rasdial <YourConnectionName>
  2. Status: rasdial
  3. Disconnection: rasdial <YourConnectionName> /disconnect
Pretty simple and straight forward. Please share what you think about it in the comments below.

Tuesday, 10 September 2019

New to KQL? No problem its just like SQL

Well KQL is a query language used to query on Kusto, which is covered in the post Getting started with Kusto.




One Cluster can have multiple Databases and one Database can have multiple Tables. Before going forward let us assume we have a cluster named 'cluster1' and it has database with name 'database1' and database has tables with names 'table1', 'table2', 'table3','table4', 'table5'.

A kusto query usually comprises of  multiple operators and table or cluster name. Unlike SQL table name is not the first thing to be written in KQL. Below is a sample kusto equivalent of select top 5* from table1.
table1 | top 5

Since we are going to query on a big data source lets just add count or where clause to all our queries.

List of  5 basic operators to get started:

1. Project: To select the list of columns to show from the table.
example: table2 | project col1, col2 | take 10.

2. Count: To count the number of rows.
example: table1 | count.

3. Where: It is similar to where clause in SQL server. In KQL we use double equal, unlike SQL, for conditional check.
example: table2 | where col1 = = 'anyvalue'.

4. Take: It picks the number or rows mentioned. It takes rows in no specific order. It is suggested to sort the rows before using take. Limit can also be used for the same purpose.
example: table1 | take 5.

5. Sort (asc/desc): It is used for sorting the data in ascending or descending order, just like SQL.
example: table3 | take 5 col1 asc or table3 | top 5 col1 desc.


You can check out all the available operators/functions/entities at the Microsoft docs website.

Please share your thoughts in the comments below.

Monday, 2 September 2019

Getting started with Kusto

What is kusto?

Well that looks like a difficult question to answer and its not answered clearly (atleast I was not able to find any answer for it). There are many versions of it.Some says its a tool, some says its a query language, docs says its a service. Lets, go with the docs version. Its a service to query over Big Data.
"It is based on relational database management systems, supporting entities such as databases, tables, and columns, as well as providing complex analytics query operators (such as calculated columns, searching and filtering or rows, group by-aggregates, joins)."


What is KQL?
 
KQL is acronym for Kusto Query Language, which can be used to query Azure Application Insight data. There is an open data source available online to query, it can be located at LogAnlytics.



How to Query?

Well to query you first need to learn the basics of KQL but dont worry if you already have worked with SQL or know about T/SQL, its easy to use. The syntax is little similar but there are few new keywords which might need to learn. New way of querying, it feels like mixture of SQL and Powershell to me. All the keywords are separated with Pipes '|' and output from the first query is input to the next one.
"A Kusto query is a read-only request to process Kusto data and return the results of this processing, without modifying the Kusto data or metadata. Kusto queries can use the SQL language, or the Kusto query language."
Where to write Query?

The next part is where can you write the query? Well kusto provides many ways/channels to query the data. All of them are mentioned below. Please select the one that suits your requirement. 😊
As I have mentioned in the article before about LogAnalytics. You can use a web UI to query or you can download Query Explorer. Well you can query over the application insight of your azure subscription also.

There are client libraries available in few languages, There is also an option to connect via Rest API, Client SDK's and KustoExplorer is an available native tool.

    .NET SDK
    Python SDK
    Java SDK
    Node SDK
    PowerShell
    R 

The content for Kusto can be found under names of Azure Data Explorer, Azure Log Analytics etc.
Please share your thoughts in the comments below.

Wednesday, 1 May 2019

Microsoft is using Kestrel in Production for the new ASP.NET website

I could not help but noticed asp.net is now redirecting to a new website which is a sub-domain of Microsoft.com, so I got interested to check how many redirects actually happens when I type asp.net in browser. This is what I found out.

So as its shown in the image below there are 3 redirects post which the new website opens up.







  1. http://asp.net
  2. https://asp.net
  3. https://www.asp.net

All of these are 301/Moved Permanently.

Another interesting thing I noticed is the server used is not IIS which was used before. Its Kestrel this time. Its the same server which David Folwer (who is also an awesome speaker) and Damian Edwards (used to pairs up nicely with Scott Hanselman on standup) mentioned a lot of time during ASP.NET community stand up.

The server is developed by the Asp.net team for .net core I believe and the new website runs on same.



Serialization.

Serialization.

It used to be a very important concept but looks like everything is taken care of nowadays by the framework. Still, I feel the need to mention the same as I found a lack of resources/ blog to guide about the process. what it means, how to do it etc.

what is serialization?

As per Wikipedia,

serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored.

Serialization we do in usually is to convert our code to JSON/XML or converting JSON/XML code back to object. There is an awesome library available for handling JSON which is Json.Net. It is written by a guy named James Newton King who is from New Zealand and currently working at Microsoft on asp.net team.

I have planned a few post on same topic, out of which all deals with either converting your XML to the object of your choice or the object to the XML.

C# provides extensive support to XML, under the namespce System.Xml. More about the namespace can be explored at apisof.net

Wednesday, 24 April 2019

Build Habits which you want to continue as Lifestyle!

Today if you check any social networking site (Facebook, Instagram, etc.) there are tons of accounts which pretend to be something which they are not, and most of us gets fooled by their appearance and want to start doing some thing these people are doing for example starting a morning routine. A morning routing is a thing which a person do once after he wakes up and that time of the morning usually qualifies as the 'Self time' because there is no disturbance at that time of any kind, If you manage to wake up at 5AM then there are good chances that your neighbourhood will be asleep and you can work on something which is important to you and you like to get finished. There are lots of such videos out there which make you follow such routines and habits but the only thing is they don't last longer. The problem I see with this approach is 'Anything which doesn't comes from within you, will not be able to mould you'.

The Habits as I mentioned in the title, should be chosen wisely. Simply picking up a habit that doesn't even align with your work schedule or the goal which you have is not going to help you in any manner. you should think twice or even few more times if you feel its required before picking any habit as they have a negative impact on you when you don't follow through.

The habit should be chosen with all the awareness that you want to really change that aspect of your life to something better. There is a nice book by Author named Charles Duhigg Book is "The Power of Habit". If you really feel you have to changes something I suggest you to read that book.

Any habit worked upon seriously for a long duration throughout lifetime becomes a lifestyle. A few examples are:
  • A habit of brushing your teeth at night daily in a long run is a lifestyle you live by.
  • Waking up early to spend some time peacefully with your self is a lifestyle.
  • Reading daily before going to bed is a good habit or a lifestyle if pursued for long time.
  • Eating healthy food is a good habit but a proud lifestyle when you say I have not eaten any shit food in last 5 years.
  • Walking 10k steps everyday.
  • Going to gym 4-5-6 days a week is a habit and a lifestyle to follow. 
  • Writing a Journal.
what kind of  habit lifestyle do you care to build?

Tuesday, 2 April 2019

Scheduling meetings like a Pro!

It is a Sunday evening and a meeting reminder pops up on your mobile screen. It's damn annoying, but I have seen people doing it all the time. They schedule a recurring meeting without considering your weekend and that makes me go crazy. It's my day off, that meeting reminder popping on my mobile screen is the last thing I want to see.

This post is dedicated to those dummies who have certainly got promoted because of their hair greying but don't for sure know how to schedule a meeting.

For Office 365.

click 'New' on top left corner -> Calendar Event.





2. Fill in all the details you need. (Location, Title etc)
The title should be meaningful, something like 'Let's meet' doesn't make any sense if you are sending that invite to 5-10-20 people in your organisation. It has to make sense. Remember to cross-check your spelling because it is going to be there in the calendar for some time. You don't want to be wrong in that.
while adding people make sure you want them as an optional attendee or required one. Scheduling assistant can help you in determining whether the person you are inviting is available at that time.








Now the most important thing, making a meeting recurring without disturbing people at their weekend.




You can select 'Every workday' or select 'Other' from the dropdown if you want the meeting to occur on a specific day.






For MS Outlook.

Goto Home ->  Meeting. (Opens a popup dialogue)





Clicking on Appointment in the Meeting popup will open one more popup to help you schedule the appointment.

Recurring appointment - Daily.



Recurring Appointment - Weekly. It provides you with the option to select your weekdays.






Which Software/Application/Platform do you use to schedule meetings?

Thursday, 5 July 2018

.NET Standard: What it is and how to use


What really is dot net standard?  

Let me try to put it in simple words. We used to use different BCL's for different frameworks and remembering it is a tough job. So Microsoft once again has come up with a solution to help developers to put a little less load on on the brain to remember the API's. They have replaced all the BCL's with a common one which they are calling as .net Standard. 

.Net Standard 2.0 has around 32,000 API's. You can download the list from here or you can check it here at GitHub.

.Net Standard replaces Portable Class Libraries (PCLs) as the tool for building .NET libraries that work everywhere 


How to use it? 

If you have .net core installed on your machine you can start working on .net Standard just by creating a Class Library. Yes, the old Class library is now Class Library for .net standard. 






For those who understand pictures better or would like to read less. 


Above pictures are taken from a slide of Immo Landwerth. 

The table below can be used as the reference for writing a class library using the standard.

If you are choosing a version for writing .net standard, you should consider a trade-off which is the 
higher the version of .net standard more apis are available. Lower the version, more platforms have already implemented it.

You can follow .net standard on GitHub 

Below are the list of API's added newly in .net standard 2.0

Namespace
#APIs
Microsoft.Win32.SafeHandles 22
System 1,366
System.CodeDom.Compiler 46
System.Collections 335
System.Collections.Generic 23
System.Collections.ObjectModel 1
System.Collections.Specialized 281
System.ComponentModel 1,843
System.ComponentModel.Design 565
System.ComponentModel.Design.Serialization 155
System.Configuration.Assemblies 13
System.Data 1,587
System.Data.Common 907
System.Data.SqlTypes 971
System.Diagnostics 826
System.Diagnostics.CodeAnalysis 2
System.Diagnostics.Contracts 89
System.Diagnostics.SymbolStore 146
System.Diagnostics.Tracing 2
System.Drawing 520
System.Dynamic 226
System.Globalization 217
System.IO 309
System.IO.Compression 8
System.IO.IsolatedStorage 134
System.IO.MemoryMappedFiles 66
System.IO.Pipes 125
System.Linq 366
System.Linq.Expressions 50
System.Net 1,360
System.Net.Cache 52
System.Net.Http.Headers 20
System.Net.Mail 289
System.Net.Mime 75
System.Net.NetworkInformation 696
System.Net.Security 194
System.Net.Sockets 168
System.Net.WebSockets 188
System.Numerics 1
System.Reflection 403
System.Reflection.Emit 3
System.Resources 91
System.Runtime 12
System.Runtime.CompilerServices 190
System.Runtime.ConstrainedExecution 22
System.Runtime.ExceptionServices 6
System.Runtime.InteropServices 106
System.Runtime.InteropServices.ComTypes 15
System.Runtime.Serialization 486
System.Runtime.Serialization.Formatters 13
System.Runtime.Serialization.Formatters.Binary 23
System.Runtime.Serialization.Json 80
System.Runtime.Versioning 33
System.Security 124
System.Security.Authentication 11
System.Security.Authentication.ExtendedProtection 36
System.Security.Claims 206
System.Security.Cryptography 575
System.Security.Cryptography.X509Certificates 76
System.Security.Permissions 88
System.Security.Principal 41
System.Text 83
System.Text.RegularExpressions 31
System.Threading 330
System.Threading.Tasks 66
System.Timers 39
System.Transactions 223
System.Web 32
System.Xml 1,362
System.Xml.Linq 7
System.Xml.Resolvers 25
System.Xml.Schema 967
System.Xml.Serialization 943
System.Xml.XPath 261
System.Xml.Xsl 140