Friday, December 30, 2016

Boxing and unboxing in C#

Boxing is a process to store or convert value type to an object type. In this case CLR wrap the value type to System.Object and stores it into managed heap.


     int a = 100;
     object obj = a; // boxing


Unboxing is just oposite to boxing. It extracts the value type from object.


     object obj = 123;
     int a = (int)obj; // unboxing

Boxing and unboxing are expensive processes in terms of speed or processing. When a value type is boxed, a new object must be created. And cast required for unboxing. So try to avoid boxing and unboxing and used only if the is not other better option left.

Happy coding ..!!

Wednesday, December 28, 2016

Asynchronous programming with async await

A simplified approach for asynchronous programming was introduced with Visual Studio 2012, that leverages asynchronous support in the .NET Framework 4.5 and higher as well as in the Windows Run-time. Here in this approach compiler does all the difficult work and application retains a logical structure that resembles synchronous code. As an advantage we got asynchronous programming with minimal effort.


async and await keywords are used or we can say both are heart of asynchronous programming. By these two keywords you can use .NET Framework or Windows Run-time to create an asynchronous method like you create an synchronous method.


Highlights
 

  • For declaring a method as async put async keyword in from of a method.
  • Create a task to execute some time taking method.
  • await until it finished.

Example

In a windows form application on a button click lets execute a time taking method asynchronously. 



First thing we need to put async key work in button click event.


private async void btnClick_Click(object sender, EventArgs e)

Secondly create a method which take some time to execute. Here we create a method which display a message after 5 second.


private void ShowMessage()
{
     int waitTime = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds);
     Thread.Sleep(waitTime);
     MessageBox.Show("I am an async message.","Async await demo");
}


Finally, need to create a task and call this method.

    Task task = new Task(ShowMessage);
    task.Start();


And button click must listen for this task to execute.

    await task;


So once we click the button it will execute the ShowMessage method asynchronously and not UI or main thread blocked by this operation. The keyword await will hook the the ShowMessage method with main UI thread. It is typically used if the called method(ShowMessage) return some value that need to captured in main thread.



using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestAsyncAwait
{
    public partial class frnDemo : Form
    {
        public frnDemo()
        {
            InitializeComponent();
        }

        private async void btnClick_Click(object sender, EventArgs e)
        {
            Task task = new Task(ShowMessage);
            task.Start();

            lblResult.Text = String.Format("Async process start.{0}You will get a message in 5 seconds.", Environment.NewLine);

            await task;
        }

        private void ShowMessage()
        {
            int waitTime = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds);
            Thread.Sleep(waitTime);
            MessageBox.Show("I am an async message.","Async await demo");
        }
    }
}

Happy Coding ..!!

Monday, December 26, 2016

Creating connection string in Visual Studio

To create a connection string in Visual Studio follow the below steps -

1. Go to tools
 

2. Select connect to database, A pop up window will emerge.





3. Put server name.

4. Select Windows authentication or SQL server authentication on log on to the server section. If you choose SQL Server Authentication you need to fill Username and Password.

5. Choose database name from connect to database name section

6. Click in Test Connection button. if every thing OK, a message window would
popup. Select okay.

7. Then click the Advanced button and right there is the connection string.




 

But in case of SQL Server Authentication you have to manually
type the password in the connection string.



Sample connection string-

SQL Server Authentication

"Data Source=SqlServerName;Initial Catalog=DataBaseName;User ID=YourUserName;Password=YourPassword"

Windows Authentication 

"Data Source=SqlServerName;Initial Catalog=DataBaseName;Integrated Security=True"

See video tutorial from CodesWizard from Creating connection string in Visual Studio.


Happy Coding ...!!!