Friday, March 23, 2018

How Search Engine works ? How SEO works ?


Last year my friend has deployed his own website on internet and tries to search on Google/yahoo and other search engines but they are unable to enlist the website in it, even Google failed to show the name of his website in auto complete/suggestion textbox too. Everyone wants to see their website name on first search page of Google/yahoo/other search engines when they search.
But it needs some technique that should be apply and used for each webpage that we have deployed on internet.
This technique is known as Search Engine Optimisation. (in simple words, Help search engine to search the things quickly by applying some simple rules on your web pages)


Search engines are the heart of the internet. we know there are zillions websites available on internet and still increasing day by day, In such a case search engine plays a very important role to search any content/pages on this ocean.
SEO optimization is not a single cup of tea, it needs a optimization of WebPages and follow different rules while generating them. In my previous article i have explain some of the SEO tips, you may check this article on this link
By following SEO tips it will improve sites' interaction of both users and search engines. This article does not give a magic pill that can show your website always on top page of search engine, but this article tell you about the best practices
that outlined below and will make it easier for search engines to crawl, index and understand your content.

Start with Optimization tips

Every year search make changes in their way of working and try to optimize the search patterns, your site needs to update as well to persist in this race. 
Contents are the most important of your web-page, the contents are the things that collects new users/visitors for you, that make your site/web-page popular, while following SEO tips modifying content with good keywords is most essential

PageTitle- The start of search engine life

The most important part of search engine is Page-title. Search engine begin the search from here only. Your application/website should have good accurate page title. By using title user and search engine should know "what the topic of a particular page is"

         Many times i have seen there is no page title for many Web-pages. Avoid doing that, add Page title to each pages, the Page title should be present under 'HEAD' section of page. When user search any 'term' in Google then if the searched 'term' is exist in title then it will displayed as BOLD in Google search result. Most of the time the Google suggestion list is picked from Page title itself.
see below snap


Points to Note

- Search engine optimization affects only organic search results, not paid or "sponsored" results such as Google Ad Words.
Now the question is, what is Paid/sponsored ad words and what is organic search
The search result highlighted with some light color and appear at the top the search page is called as 'Paid/sponsored ad words', and the rest of search result is come under 'Organic Search' result
Below snap will clear your idea


How search engine works

When search engine find the pages in whole web ocean, Search engine works with the help of the page elements itself, it consider following things while searching.
  • Proper Title of the page which helps people to know more about your article without opening it, we have seen if your title is proper and useful then search engine like Google show them in BOLD in top of the page
  • Keywords that are used in page. The keywords are the words that are put by the user in search engine criteria for searching, so our website should contain proper and popular keywords. Frequency and location of keywords is most important in Web page.
  • Do not try to include 'FAKE' keywords in your website that are not related to your web content otherwise your website may be BLACK listed by search engine. If the keyword only appears once within the body of a page, it will receive a low score for that keyword.
  • You should use your main keyword for each page in the file name, preferably at the beginning of the first sentence. 
  • Links used in page are played important role in searching. Search engine uses 'crawing and indexing' like algorithms for link search, it follows the link and check for the rating of linked page.
  • Broken link, spam link may decrease your website ratings, Google like search engine looks at how many Web pages link to a particular site to determine its relevance
  • Uniqueness of the content is also a noticed by search engine and proper use of Meta tags is also important.
  • One of the noticeable aspect is "How long the Web page has existed on web?", The age of the page is also considered while searching. People create new Web pages every day, and not all of them stick around for long, Google link search engines places more value on pages with an established history.
  • Below snap show you how Google locate a title in possible list

Google like search engine take use of automated robots for searching like "crawlers" or "spiders", with the help of them it can reach to many billions of interconnected documents. Currently, the major engines typically interpret importance as popularity.
The more popular a site, page or document, the more your rating is. Here in this case search engines have continued to increase users’ satisfaction by using metrics that interpret popularity.

Make our pages popular

  • While designing content of the page you should keep a thing in mind that, pages should primarily designed for users, not for search engines
  • Don't be dishonest with your users or present them different content that are used for search optimization, this is commonly referred to as cloaking.
  • While you make website you should make a clear hierarchy of text and links. Every page should be reachable from at least one static text link.
  • Create a useful, information-rich site, and write pages that clearly and accurately describe your content. 
  • Make sure that your "TITLE" elements and "ALT" attributes are descriptive and accurate.
  • Give rel='nofollows' attributes to every link that you used in your websites, it will stop the search engines to follow the link, it will improve performance.
  • First you need to understand the Use of keywords, it is the pathfinder for websites, You should create descriptive, human friendly URLs. 
  • Bing like search engines recommend the following things to get better rankings in their search engine:
  • You should develop a clean and keyword rich URL structure is in place
  • Make sure that your content is not buried inside rich media like (Adobe Flash Player, JavaScript, Ajax) and you should need to take are that rich media doesn't hide links from crawlers.
  • Create keyword-rich content based on research to match what users are searching for.
  • Always update your website to produce fresh content regularly.
  • Don’t put the text that you want indexed inside images. For example, if you want your company name or address to be indexed, make sure it is not displayed inside a company logo.

Finally, internet is the big ocean and search engines always try to search for golden fishes in it, lets help it to make a better outcome.

-Happy Searching

Friday, March 9, 2018

When to use ASP.NET Webforms and ASP.NET MVC

In this article I have explained, When to use ASP.NET Webforms and ASP.NET MVC. We know what is ASP.NET and what is ASP.NET MVC, but we are confused when to favor which technology


Last week my friend has started a new web based project in .NET, he asked me In which technology he should go ASP.NET or ASP.NET MVC ? 

Now a days everyone talk about ASP.NET and ASP.NET MVC but if we asked them, when to favor which technology ? all goes confused. There is no clear-cut answer, and rightly so. This article will help you to choose between ASP.NET and MVC depend upon your requirement and tell you Advantages / Disadvantages of ASP.NET MVC. Lets start with it.


Basically ASP.NET was developed to improve the speed and performance of classic ASP, Microsoft's ASP.NET, one of the most successful web application development frameworks ever.You can use ASP.NET to fast develop and deploy highly scalable, high-performance web applications in a managed environment

When to use ASP.NET

1. RAD – Rapid Application Development

RAD is the strong point of ASP.NET, ASP.NET does not deal with HTML markup directly, rather it gives set of powerful tools to developer to design and develop web application, compiler then convert it to Markup and show it on web application, so developer does have to take care of internal architecture and can develop application rapidly.

2. Cost

When Cost is matter ASP.NET is really helpful to you. As it is bit old technology and start of the web development phase, maximum developer community is aware of it and develop using ASP.NET, where as MVC is newer than comparing with ASP.NET, so there is cost incurred to development with ASP.NET MVC

3. Stable implementation

ASP.NET Web Forms implementation is now a stable and robust with many years of deployment experience. over the year ASP.NET is upgraded and is now more firm and dependable.

Drawbacks/Limitation of ASP.NET

  • Customization is not possible and easy with built in ASP.NET control set.
  • As ASP.NET create its own markup tags while rendering on browsers which is very much different than actual HTML tags so flexibility among cross browser compatibility and devices are less
  • The generation of each control ID is vary framework to framework, which needs to make changes in scripting as well.
  • maintaining data between post back is additional task for ASP.NET, as it's page life cycle is depend upon ViewState
  • Final web page render size is also an issue for ASP.NET as view state increase each page size.
  • ASPX pages has fixed URL render pattern which will slow down SEO and search engine crawling.
  • ASPX page does not render without its code behind, so there is additional load on web page each time


I have read somewhere, "MVC framework is not efficient unless you're willing to roll up your sleeves and build your own project specific infrastructure ", I think it is really true, MVC is complex for Oldies and Simple for New projects, ASP.NET MVC is support Test-driven development (TDD) . I have discuss some points about ASP.NET MVC below. which includes When to favor, Advantages and limitations.

 When to use ASP.NET MVC

ASP.NET MVC has very scatter structure so code separation is strong point, No doubt ASP.NET MVC has many great features like Bundling, minification, Parallel Development, Test-driven development ( It actually leads to very short development life cycle), Web API (for building HTTP service), URL Routing Scaffolding.
But there are some facts and things that we need to consider before using ASP.NET MVC, so lets consider some priorities while going with ASP.NET MVC

1. Complex form structure

ASP.NET MVC has more hold on HTML so When you want to develop a complex form structure, you can use it, MVC allows for any number of forms on the page

2. Purpose of website is for public

If you are build website or web application targeting to public like banking or reservation then you need to go for MVC as it has very SEO friendly and lightweight.

3. Separation of concerns

When your concern is code separation you can go for MVC as it has very scattered structure with Model, View and controller, here is very less chances of getting things more complex.

4. Different view device wise

If you are targeting you development towards multiple render devices then go for MVC it offer design flexibility so that same web page can be easily render on desktop browser, mobile and smart phone devices in simple render mode

5. Easy Unit testing

As with the help of MVC we can developed loosely coupled application, it is very easy to test each module independently, Dependency Injection is more useful in such cases

6. Easily blend with other technology

ASP.NET MVC has capacity to easily blend with other technology, jQuery and other JavaScript frameworks can be simply add in ASP.NET MVC

7. Automatic Unit Testing

If you want to go for automatic unit testing then ASP.NET MVC is good for you.

Drawbacks and limitation of ASP.NET MVC

- It is not easy to understand and code, within limited time frame
- ASP.NET structure is very much different from MVC it is Difficult to convert an existing site from ASP.NET to ASP.NET MVC.

Facts of life
  • More often practical conditions are not same as hypothec conditions the choice between ASP.NET and ASP.NET MVC is not a single cup of tea, it is vary from project to project and team to team 
  • If you have very large ASP.NET project then do not go for MVC as it is like to build your project from scratch, it may be leads to time and cost wasting
  • If you want to deploy project targeting more user volume and devices then go with MVC 
  • Friendly URL's for SEO with no viewstate and cleaner HTML is the powerful point which leads MVC to perform faster
Finally, There are Pros and Cons for both ASP.NET and ASP.NET MVC, This article is small attempt to put focus on features point. It helps you to take decision easy between these two. But the final Answer is remain same "it depends".

Suggestion and Queries are always welcome


Tuesday, February 13, 2018

Find out who Delete your data from SQL table

Find out who Delete your data from SQL table

Have you lost your data from SQL table ? Have you lost your SQL table ? want to know who ran DELETE or DROP Query on your database ? Then go through this step by step article, it will help you to find the culprit


Last month my friend has called me and said, some has delete his important data from SQL table and now no one confess it. He asked me to search a way to find culprit. After couple of here and there i got a way and now want to share with you. So, let's enjoy this article.

This article will help you find the user who fire DELETE or DROP statement on your table or database

Things we need

To search culprit, we need to read transaction log entries of database. Yes...You heard is right, you can read SQL transaction log data (i.e. LDF file).  let's begin with the steps

  1.  We will create some sample table with data
  2. Delete rows from it
  3. Try to track the user who delete (soft or hard) data entries (Here Soft Delete means delete records using Query and Hard delete indicates delete data using 'DEL' button (or may be with mouse) from SQL table directly)
         (Those who don't know what is LDF) LDF is a file extension for log data files these files are exist with MDF files (which contains actual data). LDF file store all transactions with time stamp and help to recover database in case of data loss.

         Now, to read LDF file we need to use 'fn_dblog' function, (which is undocumented function of SQL), after executing this function on particular database you will able to see live transaction logs and operations executed on that database.

Let's create sample database and table, with the help of following Query

( NAME = N'Sample_dat', FILENAME = N'D:\Sample\Sample.mdf' , SIZE = 13760KB , MAXSIZE = UNLIMITED, 
( NAME = N'Sample_log', FILENAME = N'D:\Sample\Sample.ldf' , SIZE = 9216KB , MAXSIZE = UNLIMITED, 

sample table:

USE [Sample]
    [No] INT ,
    [Name] VARCHAR (50),
    [Address] VARCHAR (50)

Now let's check what has been recorded in LDF logs

run 'fn_dblog' function in Sample database

select * from fn_dblog(null,null)

If you see above result pane, there are almost 35 rows are recorded for just CREATE DATABASE and CREATE TABLE script

Let's insert some rows in table

Insert into Emp values(1,'name1', 'address1')
Insert into Emp values(2,'name2', 'address2')
Insert into Emp values(3,'name3', 'address3')
Insert into Emp values(4,'name4', 'address4') 

Track DELETE Activity

Now, just go and delete all rows from database, use below simple query

Delete from Emp

Our Emp table is now empty as, we have delete all the queries

Let's examine the log table, having operation type is 'LOP_DELETE_ROWS', fire fn_dblob function again and see what you get

select * from fn_dblog(null,null) where Operation = 'LOP_DELETE_ROWS'


Above result pane show us, all the transaction rows which are having 'DELETE' entries on specific database table, you need to search for the your 'specific' table (from where you have lost your data), check out column 'AllocUnitName', this column contains your table name on which 'DELETE' statement has fired.

In our case, Table name is 'Emp', now get the transaction ID for that particular 'table' entry record, execute below query to get record of particular table

select Operation, [Transaction ID], AllocUnitName,  * from fn_dblog(null,null) 
where Operation = 'LOP_DELETE_ROWS' and allocUnitName = 'dbo.emp'


in our case, transaction ID is same, as all entries are deleted with single 'DELETE' statement (at once) (e.g.  0000:0000079f)

with the help of above transaction ID, we will find when our entries are deleted from database. for that purpose we need to search record with operation LOP_BEGIN_XACT, fire below query on database

select  [Operation], [Transaction ID], [Begin Time], [Transaction Name], [Transaction SID]
FROM fn_dblog(NULL, NULL)
WHERE [Transaction ID] = '0000:0000079f' AND [Operation] = 'LOP_BEGIN_XACT'

above query will give you Start time of the transaction

Now we got the exact time when someone fire DELETE query on database, to know the activity End Time, you can try below query

   [Begin Time], [End Time]
    fn_dblog(NULL, NULL)
[transaction id] = '0000:000007a1' and [Operation] = 'LOP_BEGIN_XACT' or [operation] = 'LOP_COMMIT_XACT'

Here is the result of above query

Now let's find who is the culprit, we will find the real database user who fire delete query

Transaction SID column contains encrypted Hexa decimal text which is nothing but the user name who fire 'Delete' query

Fire below query to get [Transaction SID] column with the help of Transaction ID and Operation = 'DELETE'

select  [Operation], [Transaction Name], [Transaction SID]
FROM fn_dblog(NULL, NULL) where [Transaction ID] = '0000:000007a1' and [Transaction Name]='DELETE'

Output of above query is

Just you need to copy, encrypted hexadecimal contents from [Transaction SID] column and execute below query on master database, as per our result my Hexadecimal string is 0x01


**SUSER_SNAME is the inbuilt function, it just checks security identification number (SID) and back with the login name associated it.

when i run above query i got below output

Yes...we finally got real culprit who fire Delete query

Track DROP activity

Similarly, if anyone DROP your table from database we can track that activity by using following queries,
Let's Drop table with below simple query

Drop table Emp

Now track activity using Transaction Name 'DROPOBJ'
check below query

SELECT [Transaction Name], Operation, [Transaction Id], [Transaction SID],  [Begin Time] 
FROM fn_dblog (NULL, NULL) WHERE [Transaction Name] = 'DROPOBJ'

i got below result

Same as DELETE scenario execute below query on master database, as per our result Hexadecimal string is 0x01


which is the same user 'sa'

So, to conclude

SQL store all its transactions in log table, we can read transaction log file using fn_dblob function, we can do more research on each transaction with the help of this function.  All transactions are logged with different operations,  With the help of SUSER_SNAME function we can easily trace out encrypted user name.

In my next article i will cover deep dive points on 'Reading Transaction Log of SQL (LDF)', so Please stay tuned

and Enjoy this article
**DO NOT alter enties of fn_dblog or DO NOT run these command on production unless you have backup.

*Suggestions and comments are always welcome

-Happy Tracing

Tuesday, November 14, 2017

FIX : A network-related or instance-specific error occurred while establishing a connection to SQL

In this article i explained you to Fix SQL error occurred while establishing a connection to remote computer, so we can say we can resolve error "Network-related or instance-specific error occurred while establishing a connection to SQL Server [2005/2008/2012]"


Couple of years back when i was not much familier with SQL, i try to connect to my SQL Server from my client. I put servername and try to login with SQL Server authentication with user name and password and i got error "A network-related or instance-specific error occurred while establishing a connection to SQL Server...", after spending couple of hours on it i was able to get rid of it, this article is for those who got same error and still they are put their head in SQL to resolve the issue.


Many times we are trying to connect to SQL server with SQL management studio either by express version or by enterprise version and we got following error
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) "
Above error is really headache for sql users.
Here is the snap of error

Fix it

To fix the issue we might need to do some configuration changes in SQL management studio (Here i use SQL 2008 for it)

Allow remote connections 
The very first thing you want to check is, your Remote Connections are enabled on your SQL Server database, to check it go through below steps
1. Select SQL server on object explorer -> Right click and click on properties -> select 'connections' -> under Remote server connections sections -> check 'Allow Remote connections to this server'
see below snap

This is the basic and simple check it may resolve your error, if not then continue with this article

Enable TCP/IP protocol
Next step is the enable the TCP/IP, just navigate to 'the SQL Server Configuration Manager' -> in left pane Open 'SQL server network configuration' -> select protocol for SQLEXPRESS in right pane select TCP/IP and make it 'enable'
see below snap

This is one of the helpful step and resolve many users issue, if the problem still continues then continue with this article

Handle Firewall port
Many times your firewall security settings does not allow SQL to pass through, you need to handle that firewall port to work with SQL stuff. To allow in firewall there need to configure couple of settings 
1. set 1433 port in TCP/IP proerpties
2. set Inbound and Outbound rules in windows firewall settings (Applicable for window 7 and above operating system)

set TCP port 1433 in configuration window as below snap shows

Now to set Inbound and Outbound rule we need to navigate to windows firewall, Just Open the Control Panel and navigate to Windows Firewall.
Click on Advanced Settings on the left hand side and you should see the Windows Firewall with Advanced Security. Select the Inboud Rules on the left hand side and click on New Rule… on the right hand side.
go through the following snap sequence it will help you to enable and set the windows firewall settings
Open 'windows firewall with advanced security' screen, select 'Inbound Rule' and click on 'New Rule', see below snap

New Inbound wizard screen' will open, Now in left hand side of the window select 'Rule Types', in right hand side select 'Port' now click 'Next'

In protocol and ports section select 'specific local ports' and give port number as '1433' (default sql port), now click 'Next'

In action section, select 'Allow the connection', and click on Next

In Name section give name and description of the rule, which help us to identify the rule in firewall, now click on Finish

Yes, we are almost done with the settings now close SQL server and restart it again and try to connect, it will resolve your issue.

Summing up

Above error is very basic Many time occur due to different conditions, if you have database installed on SQL 2008 and if you try to connect it with SQL 2005 management console then also same error occurred, when you have install a new instance of SQL server on machine then also this error arise, above are some settings that help you to get rid of the error

Suggestion and Queries most welcome


Monday, August 7, 2017

New Features of C# 7.0


C# 7.0 is planned to release in parts, Microsoft has release Most of its features with Visual Studio “15” Preview 4, it was release in last month (Aug 2016), See Release Post
Code simplification and improve performance are the main key role of this build, Tuples, Pattern matching are some of the really good features introduced. Hope you will enjoy these features and be more productive.
 Let's see new features of C# 7.0

1. Tuples (with types and literals)

Return multiple values from a method is now a common practice, we generally use custom datatype, out parameters, Dynamic return type or a tuple object but here C# 7.0 brings tuple types and tuple literals for you it just return multiple values/ multiple type inform of tuple object. see below snippet

( string, string, string, string) getEmpInfo()
    //read EmpInfo from database or any other source and just return them
    string strFirstName = "abc";
    string strAddress = "Address";
    string strCity= "City";
    string strState= "State";
     return (strFirstName, strAddress, strCity, strState); // tuple literal

//Just call above method and it will return multiple values 
 var empInfo= getEmpInfo();
WriteLine("Emp info as  {empInfo .Item1} {empInfo .Item2} {empInfo .Item3} {empInfo .Item4}.");

In above sample we can easily retrieve multiple values from tuples, but Item1, Item2 name are bit ir-relevant so let's assign some meaningful names before return, see below sample

(string strFName, string strAdd, string strC, string strSt) getEmpInfo()
    //code goes here

//Now when you call method get values with specific name as below 
var empInfo= getEmpInfo();
WriteLine("Emp info as {empInfo.strFName} {empInfo.strAdd} {empInfo.strC} {empInfo.strSt}.");

Additionally you can return their name directly in tuple literal as below

return (strFName: strFirstName, strAdd: strAddress, strCity: strC, strState: strSt);

Tuples are very useful thing where you can replace hash table or dictionary easily, even you can return multiple values for a single key, Additionally you can use it instead of List where you store multiple values at single position.
.NET also has a Tuple type (See here) but it is a reference type and that leads to performance issue, but C# 7.0 bring a Tuple with value type which is faster in performance and a mutable type.
Most of the time we don't want to access whole tuple bundle or we just need internal values then we can use Deconstruction features of C# 7.0, we can easily de-construct a tuple and fetch values that we need, following snippet will clear your doubt

( string strFName,  string strAdd,  string strC, string strSt) = getEmpInfo(); 
Console.WriteLine($"Address: { strAdd }, Country: { strC }");

2. Record Type

C# support record type, which is nothing but a container of a properties and variables, most of the time classes are full with properties and variables, we need lot of code to just declare them but with the help of Record Type you can reduce your effort, see below snippet

class studentInfo
    string _strFName;
    string _strMName;
    string _strLName;
    studentInfo(string strFN, string strMN, string strLN){
        this._strFName = strFN;
        this._strMName = strMN;
        this._strLName = strLN;
    public string StudentFName {get{ return this._strFName;}}
    public string StudentMName {get{ return this._strMName;}}
    public string StudentLName {get{ return this._strLName;}}

In above code we have a class with property, constructor and variable, so access and declare variable i need to write more code.
To avoid it i can use  Record Type in C#, see below snippet

class studentInfo(string StudentFName, string StudentMName, string StudentLName);

That's it and we have Done !
above snippet produce same output as earlier snippet.

3. Minimizing OUT

Out parameter is very popular when we want to return multiple values from method, By nature out parameters are ref type and works as an argument, we can use it easily but the only condition is out variable should be initialized before it passed. see below snippet

class SetOut
    void AssignVal(out string strName)
        strName = "I am from OUT";
    static void Main()
        string strArgu;
        AssignVal(out strArgu);
        // here contents of strArgu is "I am from OUT"

C# 7.0 reduce your pain of writing extra code and you can just pass argument without initialize them, see below snippet

 static void Main()
        AssignVal(out string szArgu);
        // here contents of szArgu is "I am from OUT"

You can either use var as argument type instead to declare them.
Note that variable are used here, are in limited scope only, thus we can not use them outside method

Since we can define variable as argument directly, C# 7.0 gives us freedom to declare them as var also. so you don't need to worry about datatype, see below snippet

static void Main()
        AssignVal(out var szArgu);
        // here contents of szArgu is "I am from OUT"

4. Non-'NULL' able reference type

Null reference is really a headache for all programmers, it is a million dollar exception. If you don't check them you got runtime exception or if you check them for each object then your code goes long and long, To deal with this problem C# 7.0 come with non-nullable reference types
**I think syntax for it yet not fixed still they have release following syntax
'?' is for nullable value-type and '!' is for non-nullable reference type

int objNullVal;     //non-nullable value type
int? objNotNullVal;    //nullable value type
string! objNotNullRef; //non-nullable reference type
string objNullRef;  //nullable reference type

Now look at the following complier effect after we run this snippet

MyClass objNullRef;  // Nullable reference type
MyClass! objNotNullRef; // Non-nullable reference type
objNullRef = null;   // this is nullable, so no problem in assigning
objNotNullRef = null;   // Error, as objNotNullRef is non-nullable
objNotNullRef = objNullRef;      // Error, as nullable object can not be refered
WriteLine(objNotNullRef.ToString()); // Not null so can convert to tostring
WriteLine(objNullRef.ToString()); // could be null
if (objNullRef != null) { WriteLine(objNullRef.ToString); } // No error as we have already checked it
WriteLine(objNullRef!.Length); // No error

5. Local Methods/Functions

Local methods and functions is already there in current version of C# (Yes, we can achieve them using Func and Action types, see here Func  and Action), but still there are some limitations to local method, we can not have following features in it
  • Generic
  • out parameters
  • Ref
  • params
Now with C# 7.0 we can overcome this problems, see below snippet

private static void Main(string[] args)
    int local_var = 100;
    int LocalFunction(int arg1)
        return local_var * arg1;

in above snippet we have define 'LocalFunction' as local function which is inside Main Function 'Main', here we can use out or ref in it.

6. Readability Improvement with Literals

Many times we use literals in code, if they are too long then we might loose Readability,   to sort out such issues C# 7.0 comes with some improvement in Literals. Now C# allows '_' (underscore) in Literals for betterment of understand, it does not effect on its value. see below snippet

private static void Main(string[] args)
    int local_var = 100;
    int LocalFunction(int arg1)
        return local_var * arg1;

**Literals are nothing but a constant value (hard-coded value) which may be with predefined meaning. (Litearls in C#)

7. Pattern matching

C# 7.0 allows user to use pattern in IS statement and with SWITCH statement, so we can match pattern with any datatype, patterns can be constant patterns, Type patterns, Var patterns. following sample snippet will clear your concepts, let's start with IS pattern

 public  void Method1( object obj)
    //following null is constant pattern
     if (obj  is null)  return;
    //datatype pattern, string is datatype that we check directly     
     if (obj  is  string st)
    { //code goes here }

Switch pattern helps a lot as it uses any datatype for matching additionally 'case' clauses also can have its pattern so it bit flexible implementation
see below snippet

class Calculate();
class Add(int a, int b, int c) : Calculate;
class Substract(int a, int b) : Calculate;
class Multiply(int a, int b, int c) : Calculate;
Calculate objCal = new Multiply(2, 3, 4);
switch (objCal)
    case Add(int a, int b, int c):
        //code goes here
    case Substract(int a, int b):
        //code goes here
    case Multiply(int a, int b, int c):
        //code goes here
        //default case

in above sample switch case checks pattern and call 'Multiply' method

8. 'return' by Ref

Have you tried to return your variable from method/function as Ref ? Yes, C# 7.0 allows you to do that. Infect you can pass a variable with Ref return them as Ref  and also store them as Ref, isn't it amazing.
see below snippet

ref string getFromList(string strVal, string[] Values)
 foreach (string val1 in Values)
     if (strVal == val1)
        return ref val1; //return location as ref not actual value

string[] values = { "a", "b", "c", "d" };
ref string strSubstitute = ref getFromList("b", values);
strSubstitute = "K"; // replaces 7 with 9 in the array
System.Write(values[1]); // it prints "K"

In above sample we have find and replace a string, by return a Ref from method.

9. Throw Exception from Expression

You read it right, in C# 7.0 Now you can throw exception from your expression directly. see below snippet

public string getEmpInfo( string EmpName)
        string[] empArr = EmpName.Split(",");
        return (empArr.Length > 0) ? empArr[0] : throw new Exception("Emp Info Not exist");

In above snippet we can directly throw exception from return statement, isn't it really good !

Point to be Notice

All above features are expected to be a part of C# 7.0, yet Microsoft has release some of it with Visual studio 2015 Release 4.
Hope you enjoy these new features of C# 7.0

- Happy Coding

Saturday, March 25, 2017

New features of SQL 2016



SQL Server 2016 was (finally) released on June 1st, 2016 with an initial build number of 13.0.1601.5. Microsoft build SQL 2016 keeps a lot of things in mind like Cloud first, Security enhancement, JSON support, Temporal database support, Row level security, Windows server 2016 connectivity, Non-relational database connectivity (e.g. Hadoop), rich visual effects, etc.
In this article, we will take a walk-through all fresh SQL 2016 features and cover them one by one.

Always Encrypted

 As the word suggests, 'Always Encrypted' feature of SQL 2016 'Always' keeps your sensitive data 'Encrypted' either at rest (local environment) or at remote (Cloud/Azure). It will help to protect data from people who may play around it like DBAs, Cloud operators, high-privileged but unauthorized users.
How It Works
You can set Always Encrypted to individual column (where your sensitive data resides). While configuring columns, you need to specify encryption algorithm and cryptographic keys for data protection. There are basically two keys you need to define:
  1. Encryption Key for column data encryption (It will be used to encrypt data for specific column)
  2. Master Key: for Encryption of column encryption keys
So basically, it's a double encryption protection, only program can access it, client application will automatically encrypt and decrypt data before fetching data from database

JSON Support

SQL 2016 gives direct support to JSON (Java Script Object Notation), SQL has the facility to read JSON format data, load them in table, support index properties in JSON columns.
JSON data will be stored in NVARCHAR type. Due to NVARCHAR type, an application has the following benefits:
  • Already stored JSON data (as text) can be easily migrated on new feature.
  • As NVARCHAR is supported by all SQL components so is the JSON too.
You can easily fetch data FOR JSON from SQL with the below syntax:

SELECT column, expression, column as alias
FROM table1, table2, table3

It is a SELECT command so when we fire the above query, SQL will format each row/cell value and return as JSON object.
SQL has also provided in-built functions for JSON.

Dynamic Data Masking

This is again one of the security features of SQL 2016. As the name suggests, it just wraps MASK on your data, in short, it hides your confidential data that you don't want to display. It just avoids disclosure of your sensitive data.
After masking, SQL User with limited rights will not view original text, he can view only Masked Text, SQL has pre-defined masking functions you just need to apply it on different columns, see below:

Sr NoFunctionsApplied onPlain text (Input)Masking text(output)
1DefaultString, NumberABCDxxxx
4Custom StringTextRABBITRXXXX

To apply this on specific columns, you just need to ALTER column with 'MASKED WITH' function name, see below syntax:

//here I used function as Default(), you can change it to any of the above types
ALTER TABLE tablename ALTER COLUMN columnname MASKED WITH (FUNCTION=‚default()‘)

Row Level Security  

This is again one of the security features of SQL 2016. It allows you to secure your data row wise, in short you can define a row, that will be viewed by a particular SQL user only. So depending upon the SQL user access permission, we can restrict row level data, e.g., we can ensure if employees can view only their department data though department table is the same.
To implement Row level security, you need to define Security policy with a predicate and function.
Security policy:
We need to create a policy for security, here is simple syntax:


In the above syntax, FILTER and BLOCK are the predicates that will either FILTER rows and display only those that are available for read or BLOCK rows for write operation.

Function: Function is a simple user defined function, but here are some restrictions for user defined function that are used in Row Level Security syntax:
  • Database modification operations are not allowed
  • OUTPUT INTO clause is not allowed in function
  • Multiple result set should not be returned from function 

Stretch Database

As the name suggests, it gives flexibility to the user. In short, we can store portion of database to remote (Here, we can say cloud/Azure). The portion of data can be called as COLD DATA. (It is useful for those where transactional data needs to be keep for long time as industry requirement.) So we can say it's a cost-effective solution for COLD data storage, your data is available anytime for query and manage. You can access your data without changing queries either it is present on local or at stretch database.
To configure it, you need an Azure account and database instance that you need to stretch. The following snap will clear your idea.


Multiple TempDB

It is always a good practice to have a Multiple Temp data files, if you are working on a big crucial data, up till now (SQL 2014), you need to manually add temp db files to your database but SQL 2016 provides you temp DB configuration settings, in which you can configure Number of TempDB files at the time of SQL installation. Default number of files are 8 with default size of 64 MB will be given.
So you no longer need to configure/create it manually.

Query Store

Up till now, to check Query plan and execution statistics, we need dynamic management views in SQL but neither will it give you Query plan that executed by past/old queries nor will it store them anywhere so that you can review, but SQL 2016 provides you 'Query Store' that takes you through query plan, statistics and Query execution for current and past queries.
To enable it, just right click on database (obviously, you need SQL 2016 SSMS), go to properties. You will see 'Query store' at the left corner, select it and click on Enable 'true' or you can do it using Query as follows:


Temporal Table

Do you want to store history of your SQL table? So you want to review your old records after table updation? Then you can go with this features. SQL 2016 provides record version facility in which it keeps a history of changed record and maintains it for timely analysis. This feature can be useful for Audit, checking data trend, accidental update/delete data and many more.

How It Works

Basically, the system keeps pair of a table for history and adds two additional columns in it named 'SysStartTime' and 'SysEndTime' for start time and end time for row respectively. Live table contains current record of row, whereas history table contains previous record of row. We can fetch data from History table, with the following query:

BETWEEN date1 AND date2
WHERE condition; 

R Introduction

Have you stored statistical data in SQL? Want to use R to analyze it? You export data each time from SQL to R? Then your headache will now be covered in SQL 2016, because it is now with R. You can run R script on SQL. You need to install this feature at the time of SQL setup.

We cannot cover all features in details, maybe I will be planning soon to cover them one by one.
Till then, you can enjoy this article.
Suggestion and queries are always welcome.

Happy querying!

**This article is already published at CodeProject