Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, August 7, 2017

New Features of C# 7.0

Introduction


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.
Deconstruction
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;
    }
 
    Console.WriteLine(LocalFunction(100));
}

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;
    }
 
    Console.WriteLine(LocalFunction(100));
}

**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 }
    else
    return; 
}

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
        break;
    case Substract(int a, int b):
        //code goes here
        break;
    case Multiply(int a, int b, int c):
        //code goes here
        break;
    default:
        //default case
        break;
}

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

Monday, August 11, 2014

Protect word file using C# : Word automation step by step

Security:
     Security is the Most heard and most important 'keyword' in IT industry, Everyone want their documents play a secure travel, should not attack by spam or any intruder. Really, security is the main concern in now world, we can make word file secure by using password protection.
word security


What is our aim:
       protect word file using C# word automation

What we need:
      C#, Interop libraries

What are the different security can be assigned to word file:
         There are multiple types security we can assign to word file
1. Read-only protection
2. Comment only protection
3. Track revision protection



Read Only protection:
It Allow read-only access to the document.

Comment only protection:
It allows Allow only comments to be added to the document.

Track revision protection:
It Allow only revisions to be made to existing content.

Lets code it, (Protect word file):
To protect word file programmatically we need to add reference of interop assemblies in our code, I have explained it in my previous article you can check here
checkout below code snippet to protect file as 'ReadOnly'
 
         object objMiss = System.Reflection.Missing.Value;  
         object fileToOpen = Application.StartupPath + "\\test.doc";  
         object szPassword = "Pass";  
         object bFalse = false;  
         object bTrue = true;  
         //Start Word and create a new document.  
         objApp = new Word.Application();  
         objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);  
         if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)  
         {  
           objDoc.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref bFalse, ref szPassword, ref bFalse, ref bTrue);  
           objDoc.Save();  
           MessageBox.Show("Word document Protected successfully (for Read only)!", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);  
         }  
         else  
         {  
           MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);  
         }  

In above code snippet we have used method  Protect of document class and pass 'wdAllowOnlyReading' enumeration and just save document with password. it is enough to accomplish the task. so simple.
like wise we can protect document with  'Comment ' and 'TrackRevision' protection

Unprotect word file:
Now after protection we can unprotect word file using Unprotect method of document class
see below snippet
 
         object objMiss = System.Reflection.Missing.Value;  
         object fileToOpen = Application.StartupPath + "\\test.doc";  
         object szPassword = "Pass";  
         object bFalse = false;  
         object bTrue = true;  
         //Start Word and create a new document.  
         objApp = new Word.Application();  
         objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);  
         if (objDoc.ProtectionType != Word.WdProtectionType.wdNoProtection)  
         {  
           objDoc.Unprotect(ref szPassword);  
           objDoc.Save();  
         }  

So, with the above example we can say it is easy to protect and unprotect document programmatically.
You can get full source code here

Note:
    As we know word is heavy object so do not forget to close and dispose it, I have explained it in my previous blog

Summary:
Someone said, there is always scope for improvement. so I think its a on going think for programming too. Finally we have ready with our code, it is very simple to protect a file with customized password, still many things to discover with word and C#, we can them one by one in near future till then enjoy this stuff and be happy with C# and Word

Suggestions and comments/doubts are always welcome

Happy Programming
- Prasad

Wednesday, July 23, 2014

Create a word table using C# : Word Automation step by step

Our Aim: Create a word file programmatically and create a table in it


Things we need : C#, Word interop object


Word Automation


Getting started

Many times in real world scenario, we need to create our reports in word file, Means we need to export 'things' to word file. In such cases we need to create and write word file programmatically and to accomplish the task .NET will help you, COM winword interop library will play a role for you.

follow the steps below to know how to do it
1. Create a simple windows/web/wpf application (You may take console application or class library too, here I have used windows application in C# with Visual studio 2010)
2. Now just right click on solution explorer, click on Add reference and select COM tab
3. Select Word com library (If you have word 2007 installed you will see 12.0 object library, if you have word 2010 installed you will see 14.0 object library and for word 2013 you will see 16.0 object library)
see below snap

4. Add reference, Now in reference folder of solution explorer you will see 'Microsoft.Office.Interop.word' library added.
5. Now we are ready to code, first we need to create a new word document using C#
6. Import word namespace and create word object
see below snap
 
   Word._Application objApp;  
   Word._Document objDoc;  
   objApp = new Word.Application();  
   objApp.Visible = true;  
   objDoc = objApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);  

With the help of above code we can able to create a new word file. (Note: Do not ever create new object of word document.) .Visible property will open a new word file.
7. Now to add a new table in word document, we need to define bookmark first (which is the range of word document from which we need to start writing the things)
see below snap to define default bookmark of word document

 object objMiss = System.Reflection.Missing.Value;  
 object objEndOfDocFlag = "\\endofdoc"; /* \endofdoc is a predefined bookmark */  

8. Yes, we have successfully defined 'end of doc' flag, now we can first add some caption to table with the help of Paragraph object (Paragraph object is a object which used to write some text in word document)
see below snap

 Word.Paragraph objPara1; //define paragraph object  
 object oRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of the page  
 objPara1 = objDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document  
 objPara1.Range.Text = "Test Table Caption"; //add some text in paragraph  
 objPara1.Format.SpaceAfter = 10; //defind some style  
 objPara1.Range.InsertParagraphAfter(); //insert paragraph  

Here we have define a paragraph and insert that paragraph to end of the document.
9. Now we need to define a rows and columns for table that we need to draw. Here I have draw a table with 2 rows and 2 columns
In code, Simply go to the end of the document and create 2X2 table, see below snippet

  Word.Table objTab1;  
       Word.Range objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objTab1 = objDoc.Tables.Add(objWordRng, 2, 2, ref objMiss, ref objMiss);  
       objTab1.Range.ParagraphFormat.SpaceAfter = 6;  
       int iRow, iCols;  
       string strText;  
       for (iRow = 1; iRow <= 2; iRow++)  
         for (iCols = 1; iCols <= 2; iCols++)  
         {  
           strText = "r" + iRow + "c" + iCols;  
           objTab1.Cell(iRow, iCols).Range.Text = strText;  
         }  
       objTab1.Rows[1].Range.Font.Bold = 1;  
       objTab1.Rows[1].Range.Font.Italic = 1;  

 Here we have create a 'word.table' object and add some text with the help of Range object
 
  //Add text after the chart.  
       objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objWordRng.InsertParagraphAfter();  
       objWordRng.InsertAfter("THE END.");  

We have done with the task. lets checkout the final code as Whole
C#

checkout here,
       object objMiss = System.Reflection.Missing.Value;  
       object objEndOfDocFlag = "\\endofdoc"; /* \endofdoc is a predefined bookmark */  
       //Start Word and create a new document.  
       Word._Application objApp;  
       Word._Document objDoc;  
       objApp = new Word.Application();  
       objApp.Visible = true;  
       objDoc = objApp.Documents.Add(ref objMiss, ref objMiss,  
         ref objMiss, ref objMiss);  
       //Insert a paragraph at the end of the document.  
       Word.Paragraph objPara2; //define paragraph object  
       object oRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of the page  
       objPara2 = objDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document  
       objPara2.Range.Text = "Test Table Caption"; //add some text in paragraph  
       objPara2.Format.SpaceAfter = 10; //defind some style  
       objPara2.Range.InsertParagraphAfter(); //insert paragraph  
       //Insert a 2 x 2 table, (table with 2 row and 2 column)  
       Word.Table objTab1; //create table object  
       Word.Range objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of document  
       objTab1 = objDoc.Tables.Add(objWordRng, 2, 2, ref objMiss, ref objMiss); //add table object in word document  
       objTab1.Range.ParagraphFormat.SpaceAfter = 6;  
       int iRow, iCols;  
       string strText;  
       for (iRow = 1; iRow <= 2; iRow++)  
         for (iCols = 1; iCols <= 2; iCols++)  
         {  
           strText = "row:" + iRow + "col:" + iCols;  
           objTab1.Cell(iRow, iCols).Range.Text = strText; //add some text to cell  
         }  
       objTab1.Rows[1].Range.Font.Bold = 1; //make first row of table BOLD  
       objTab1.Columns[1].Width = objApp.InchesToPoints(3); //increase first column width  
       //Add some text after table  
       objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objWordRng.InsertParagraphAfter(); //put enter in document  
       objWordRng.InsertAfter("THIS IS THE SIMPLE WORD DEMO : THANKS YOU.");  
       object szPath = "test.docx";  
       objDoc.SaveAs(ref szPath);  

Summing Up
So, we have seen with the help of bit code, we can develop a nice word table application.
If you want to download source code then you may follow the link
Click here to download Source Code

Finally
COM interop is not a single cup of tea, There are thousands of things needs to discuss, we can cover them one by one in later article
Suggestions and Doubts are welcome.

Thanking You
-Prasad
 

Tuesday, June 17, 2014

Simple encryption in .NET using XOR technique

Passwords are essential thing in virtual world, it is the thing which keeps you safe, If someone else gains access to your account, they may cause you a great deal of trouble - perhaps deleting your files,  hack other systems or may stolen crucial data from your system.
so while development a big/small and web/windows application you need to keep password for your account. A password with a plain text is always a danger since it can be easily Move stealthily by someone so, we need to make our plain text password to some tricky thing and thus here we need some type of 'ENCRYPTION'.
         
Encryption

Many times we need to encrypt the string in our application, it may be used for login password, transaction password, secret key etc.
In this post, I will explain how to encrypt a string using C# with XOR encryption technique
.NET provide inbuilt encryption technique using 'System.Cryptography' namespace and various in-built encryption algorithms like,
1.AES
2.Blowfish
3.DES
4.Triple DES
5.Serpent
6.Twofish
7.Camellia
8.CAST-128
9.IDEA,RC2,RC5,SEED,Skipjack,TEA,XTEA etc

Here we go for some different technique apart from above algorithms

XOR encryption (exclusive disjunction (XOR) operation):
The XOR operator is extremely common and execute with the help of binary operations.
One of the cool things about XOR encryption is that when you apply it twice, you get back the original string
In this encryption we convert our Plain text and key to 8-bit ASCII format and then apply X-OR operation on them and same thing is done for decryption.

Let's Cook:
Things we need : C# windows/web application
Write a function in C# which accept a plain text and a key to encrypt the text
see below snippet
 
     public string EncryptDecrypt(string szPlainText, int szEncryptionKey)  
     {  
       StringBuilder szInputStringBuild = new StringBuilder(szPlainText);  
       StringBuilder szOutStringBuild = new StringBuilder(szPlainText.Length);  
       char Textch;  
       for (int iCount = 0; iCount < szPlainText.Length; iCount++)  
       {  
         Textch = szInputStringBuild[iCount];  
         Textch = (char)(Textch ^ szEncryptionKey);  
         szOutStringBuild.Append(Textch);  
       }  
       return szOutStringBuild.ToString();  
     }  

Now we have ready with the code in which we have accept the plain text and key to encrypt the text. Finally we have apply XOR operation on plain text
Above function will give you Encrypted string and Same function with same key will return your Decrypted string
I have call above function and pass plain text and a key to it.

 txtEncryptedText.Text = EncryptDecrypt(txtPlainText.Text, 200);  

I got following result, see below snaps

Excryption

Now to Decrypt the encrypted string just call same function and pass the encrypted string to it (Do not change encryption key)
Now this simple encryption is ready to use anywhere you want.
 
4107687

Thursday, May 15, 2014

Convert string to DateTime object

Many times we need to convert a sting variable to datetime, and we use 'Convert.ToDateTime' method but it results throws a FormatException
See below snap
Convert.ToDateTime

in above case I have a date string and I was trying to convert it to date time but it fails and gives me exception "String was not recognized as valid Date Time" (this is one of the famous exception)

Tips to avoid error:
          When we use  'Convert.ToDateTime' method compiler assumes given date string in month,  day, and year respectively, If value contains only a date and no time, this method assumes a time of midnight (which may not right every time)
 To avoid this error you should know exact dateTime format of input string in order to convert it to dateTime object, Use DateTime.ParseExact Method resolve the issue
 see below snippet

string dt = "24/12/2010";
DateTime dt1;
//always use InvariantCulture for dateformat provider as it support large number of customized datetime formats
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
dt1 = DateTime.ParseExact(dt, "dd/MM/yyyy", provider);
MessageBox.Show("String successfully converted to DateTime" + dt1.Year); 

DateTime.ParseExact  method will, Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

The function can be used widely supported in following frames
- .NET Framework(1.1 to 4.5)
- .NET Framework Client Profile
- Portable Class Library
- .NET for Windows Store apps
- .NET for Windows Phone apps

This basic conversion snippet will help you get rid of error 'String was not recognized as valid Date Time'