I spoke on C# 5.0 Async programming in a

C# Corner MVP Summit here is my session Recording.

YouTube – https://www.youtube.com/watch?v=J1ecBCSl1X0

Default Scope of a C# Class

May 3rd, 2013 | Posted by Vidya Vrat in C# - (0 Comments)

Read my full article on default scope of a C# class

.NET Serialization

April 30th, 2013 | Posted by Vidya Vrat in .NET | Architecture | C# | CLR - (0 Comments)

Serialization is another great feature of .NET. This article talks about overall serialization in the .NET Framework and various available types such as binary, XML and SOAP. The prime objective of serialization is to persist and retrieve the state of an object. There are various scenarios where the ability to serialize objects is handy.

Read the full article here

 

As you know Microsoft .NET is designed with cross language interoperability. I.e. two .NET compliant languages can interoperate with each other. Which simply means a function in VB .NET can be called by C# and vice-versa.  Read my full article on .NET Cross Language Interoperability at C# Corner

 

Object Oriented Programing Using C# .NET

January 28th, 2013 | Posted by Vidya Vrat in .NET | C# - (0 Comments)

Object-oriented programming (OOP) is the core ingredient of the .NET framework.  OOP is so important that, before embarking on the road to .NET, you must  understand its basic principles and terminology to write even a simple program.  The fundamental idea behind OOP is to combine into a single unit both data and  the methods that operate on that data; such units are called an object. All OOP  languages provide mechanisms that help you implement the object-oriented model.  They are encapsulation, inheritance, polymorphism and reusability. Let’s now  take a brief look at these concepts.

Read Full Article Here….

Agenda

  • OOP’s overview
  • Classes and Objects
  • Constructor and Destructor
  • Function Overloading
  • Encapsulation
  • Inheritance
  • Interface
  • Polymorphism

 

EnterpriseLibrary version- 5.0 Download url
Language used in code sample below – C#Logging is a very important feature for many applications and serves the very critical purpose in a software application’s life. Logging enables to look for monitoring data and also document what is happening in-side and out-side of the application; also known as auditing.

Most common places to log such activities, information and data are:
1- Flat files (.log/.txt)
2- Event logs (Windows event viewer) and
3- Database.

In the absence of logging application block, the logging code needs to be repeated in the application at many places. This code will also include .NET library and function calls based on type of place you want to log the information. Hence, logging application block simply de-couples the logging functionality from the application code.

Configuring the Logging Application Block

1- Open your Visual Studio project, if not already available, add an app.config file
2- Open Microsoft Enterprise Library console.
3- In the Blocks menu, choose “Add Logging Settings” option, this will appear as shown here:
 

 

4- Based on your requirements add listners (File, Event, Database etc.).

 

 

 

5- Describe “Event Log” target listner


6- Describe “Flat File” trace listner

7- Describe “Message Formatter”

 

Now save this configuraton by clicking File–> Save option. and choose your added .config file,
this will be modified and will appear as shown here.

 

 

Now you can add the code to enable the Logging from your application into the defined “Target Trace Listners” in our case “Flat File” and “Event Log”.

I have designed a Windows Form application which reads a file, from provided path location, if file is found it loads the cntent into the text box, else in case of an exception “FileNotFoundException” the error info is logged into the Log file (c:\exception.log) and Event Log.

 

 

C# Code will look like this

 

using Microsoft.Practices.EnterpriseLibrary.Logging;

 

private voidbtnReadFile_Click(object sender, EventArgs e)

{

StreamReader sr = null;

 

try

{

sr = new StreamReader(txtFilePath.Text);

 

txtFileContent.Text = sr.ReadToEnd();

}

catch (FileNotFoundException)

{

txtFileContent.Text=“Exception details logged log file
and Event Viewer”;

 

LogEntry objLog = new LogEntry();

 

objLog.Message = “Please provide valid Filename”;

objLog.Categories.Add(“File Read Error”);

 

Logger.Write(objLog);

}

 

finally

{

if (sr != null)

{

sr.Close();

}

}

}

 

 

Now if you open the C:\Exception.log you will see:

 

—————————————-
Timestamp: 10/1/2012 7:35:03 PM

Message: There is no explicit mapping for the categories ‘File Read Error’. The log entry was:
Timestamp: 10/1/2012 7:35:03 PM
Message: Please provide valid Filename
Category: File Read Error
Priority: -1
EventId: 0
Severity: Information
Title:
Machine: VIDYAVRAT-PC
App Domain: LoggingApplicationBlock.vshost.exe
ProcessId: 9164
Process Name: C:\VidyaVrat\Microsoft .NET\Application Code POCs\EnterpriseLibrary-Application Blocks\LoggingApplicationBlock\LoggingApplicationBlock\bin\Debug\LoggingApplicationBlock.vshost.exe
Thread Name:
Win32 ThreadId:13588
Extended Properties:

Category:

Priority: -1

EventId: 6352

Severity: Error

Title:

Machine: VIDYAVRAT-PC

App Domain: LoggingApplicationBlock.vshost.exe

ProcessId: 9164

Process Name: C:\VidyaVrat\Microsoft .NET\Application Code POCs\EnterpriseLibrary-Application Blocks\LoggingApplicationBlock\LoggingApplicationBlock\bin\Debug\LoggingApplicationBlock.vshost.exe

Thread Name:

Win32 ThreadId:13588

Extended Properties:
—————————————-

 

Also, if you open the EventVwr.exe then you will see:

 

This concludes that how Logging application block enables you to write small amount of code to do such a critical task of auditing.

 

 

 

 

 

 

Normally an ADO .NET connection string uses “server” or “data source” to specify the machine name \ sql server instance, your application will be connecting to.

data source = .\sql instance name
server = .\sql instance name

SqlConnection conn = newSqlConnection(@”data source = .\sql2012;
                                         integrated security = true;
                                         database = AdventureWorks”);

But there are few more ways to specify the same

address = .\ sql instance name
addr = .\ sql instance name
network address = .\ sql instance name

 

using System;
using System.IO;
namespace FileRead_ExceptionHandling
{
class Program
{
static void Main(string[] args)
{
// declaring stream-reader here so it become accessible to the
// code blocks of try { } and finally { }
StreamReader sr = null;
try
{
// this assume you will have a file on C:\ as mentioned below
sr = new StreamReader(@”c:\TestCode2.log”);
string text = sr.ReadToEnd();

Console.WriteLine(text);
}

catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message + “\n
The wrong file name or path is provided!! Try Again”);
}
catch (Exception ex)
{
Console.WriteLine(“Try again” + ex.Message);
}

finally
{
if (sr != null)
{
sr.Close();
Console.WriteLine(“Stream closed”);
}
else
{
Console.WriteLine(“Stearm is Null”);
Console.WriteLine(“Try Again”);
}

// Performing stream-write operation to the same file
StreamWriter sw = new StreamWriter(@”c:\TestCode.log”, true);
sw.WriteLine(“Line 1”);
sw.Close();

Console.ReadLine();
}
}
}
}

 

 

There is a live .NET Web Service which offers all the curreny conversion eg. USD to INR etc.

This WS is available via live URL http://www.webservicex.net/CurrencyConvertor.asmx

This WS has a class CurrecnyConvertor which exposes one Function named ConversionRate and an enum named Currency which exposed the list of all the currencies like USD, INR, AED etc.

As you know Currency conversion will depend on two parameters ConvertFrom and ConvertTo and so the same is expected to be passsed while invoking ConversionRate function.

Here is a detailed list of steps:

1- Add a Web Reference to http://www.webservicex.net/CurrencyConvertor.asmx
2- Rename the Reference name to something more friendly like CurrencyConversionWS
3- In your project create an instance of the added Web service reference
4- On the created object invoke the ConversionRate function.
5- As mentioned above there is an enum which lists all the currencies and so access it directly from the object created.
6- Save the result into a double variable and multiply with your passed amount.
7- Multiply the amount you want to convert to the received conversion rate.

Here is the code you will require to have it all working:

CurrencyConversionWS.CurrencyConvertor objWS = new CurrencyConversionWS.CurrencyConvertor();

double usdToinr = objWS.ConversionRate(CurrencyConversionWS.Currency.USD, CurrencyConversionWS.Currency.INR);

double totalAmount = usdToinr * Double.Parse(textBox1.Text);

MessageBox.Show(totalAmount.ToString(),“Total Indian Rupees”);

This is how it will look like:

 

Access modifiers are keywords (private, public, internal, protected and protected internal) which are used to specify the accessibility of a type and its members.

public class AccessModifier

{
// Available only to the container Class
private string privateVariable;

// Available in entire assembly across the classes
internal string internalVariable;

// Available in the container class and the derived class
protected string protectedVariable;

// Available to the container class, entire assembly and to outside
public string publicVariable;

// Available to the derived class and entire assembly as well
protected internal string protectedInternalVariable;

private string PrivateFunction()
{
return privateVariable;
}

internal string InternalFunction()
{
return internalVariable;
}

protected string ProtectedFunction()
{
return protectedVariable;
}

public string PublicFunction()
{
return publicVariable;
}

protected internal string ProtectedInternalFunction()
{
return protectedInternalVariable;
}
}

Now to demonstrate the behaviour how these class members are exposed to another class depending upon their scope defined via modifier/specifier and when we create an object or inherit from the above created class named “AccessModifier”
As mentioned in the above shown code and before each member variable I wrote a comment which describes the access level of each type of member varaible.

Soif we derive another class “CallAccessModifier” from the parent class “AcessModifier” then “private” type members will not be visible because its considered as outside the scope of parent class.

But “protected” members are the ones which become available only during the inheritance (when a child is derived from a parent class) as shown via image below.Showing class members availability through inheritance.

Note:- “this” is a keyword referes to the current instance of the class and used to access members. In the image above this keyword shows all the available members with the classs.

If you notice in the above shown image it clearly shows all the protected members are visible due to virtue of inheritance, along with other members with scope defined as internal, public and protected internal.

Now let’s see what happens if we decide to create an object of the class “AccessModifier” shown in the code above. As per the rule private and protected must not be visible via an object:

Showing members available when an object is created of the given class

Now as shown in the image just above we are not able to see private and protected members because they both are not exposable via an object.

Besides we are able to see protected internal member, and this is correct because its a mix of both protected and internal and so exposed in here because we are in the same assembly.

  1. What happens if we build a .dll of the “AccessModifier” code and use it in other project.
    A. The rules remain the same, once AccessModifier.dll is refered in other project its considered as outside ot the current assembly and so:
    ** private members are not exposed
    ** internal members are not exposed