Posts

Showing posts with the label .net

Await in Catch and Finally

This is just a brief note to publicize a coming improvement to the async language support. With the new compilers, changes to the C# language (e.g., async/await) are easier than they used to be. One improvement that is coming is the use of await in catch and finally blocks. This enables your error-handling/cleanup code to be asynchronous without awkward code mangling. For example, let’s say that you want to (asynchronously) log an exception in one of your async methods. The natural way to write this is: try {   await OperationThatMayThrowAsync(); } catch (Exception ex) {   await MyLogger.LogAsync(ex); } And this natural code works fine in Visual Studio “14”. However, the currently-released Visual Studio 2013 does not support await in a catch, so you would have to keep some kind of “error flag” and move the actual error handling logic outside the catch block: Exception exception = null; try {   await OperationThatMayThrowAsync(); } catch (Exception ex) {   exception = ex; } if (except

HEX to ASCII and ASCII to HEX Class - C#

This article shows you how to convert string to hexadecimal and vice versa. HEX TO ASCII Class using System.Collections.Generic; using System.Text; using Microsoft.VisualBasic; // I'm using  this class for Hex Converion namespace Hex_Converter {     public class HexConverter     {         public string Data_Hex_Asc(ref string Data)         {             string Data1 = "";             string sData = "";             while (Data.Length > 0)             //first take two hex value using substring.             //then  convert Hex value into ascii.             //then convert ascii value into character.             {                 Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();                 sData = sData + Data1;                 Data = Data.Substring(2, Data.Length - 2);             }             return sData;         }         public string Data_Asc_Hex(ref string Data)         {             //first take each charct

Message Box Class - Confirm,Error, Warning and Info - C#

A C# Snippet for creating Message Box with various type of message (Confirm,Error, Warning and Info). Message Box Class using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace messageBox {     public static class MsgBox     {         // Displays a Confirm type message box             // parameter name="sMsg" is The message you want to display         public static bool Confirm(string sMsg)         {             return Confirm("Confirm :", sMsg);         }         public static bool Confirm(string sTitle, string sMsg)         {             DialogResult ret = MessageBox.Show(sMsg, sTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question);             return (ret == DialogResult.Yes);         }         //---------------------------------------------------------------------         // Displays a Error type message box               // parameter name="sMsg" is The message you want to display         public stati

Convert Hex / Css String color to .NET Colour (RGB)

Image
Have you facing problem to convert "#CCCCCC" to .NET Colour.? Here is a solution to convert the CSS / Hex String to .NET Colour (RGB). Conversion Class using System; using System.Collections.Generic; using System.Text; using System; using System.Drawing; using System.Text.RegularExpressions; namespace Convert_Hex_String_to.NET_Color {     public class ConversionClass     {               /// <summary>         /// Convert a hex string to a .NET Color object.         /// </summary>         /// <param name="hexColor">a hex string: "FFFFFF", "#000000"</param>         public static Color HexStringToColor(string hexColor)         {             string hc = ExtractHexDigits(hexColor);             if (hc.Length != 6)             {                 // you can choose whether to throw an exception                 //throw new ArgumentException("hexColor is not exactly 6 digits.");                 return Color.Empty;          

Register winform app HotKeys - C#

Image
Hotkey is a very useful shortcut for complex application. Sometimes we build application with much feature include in it hence will result of bad experience of end user because the feature dont have the shortcut keys. Here is a sample to add shortcut keys or hotkeys for winform app in C# code. GlobalHotkeys.cs using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Hotkeys {     public class GlobalHotkey     {         private int modifier;         private int key;         private IntPtr hWnd;         private int id;         public GlobalHotkey(int modifier, Keys key, Form form)         {             this.modifier = modifier;             this.key = (int)key;             this.hWnd = form.Handle;             id = this.GetHashCode();         }         public bool Register()         {             return RegisterHotKey(hWnd, id, modifier, key);         }         public bool Unregiser()         {             return UnregisterHotKey(hWnd, id);         }      

How to "PUT" and "GET" queue item IBM WebSphere Queue - C#

This is example C# code how to insert value into IBM WebSphere  Queue, and Get The Queue value back. You can use Queue to store some information to processed later without involve database. You can read more about IBM WebSphere queue in here Put Message C# Code MQQueueManager queueManager;             MQQueue queue;             MQMessage queueMessage;             MQPutMessageOptions queuePutMessageOptions;             MQGetMessageOptions queueGetMessageOptions;             string ChannelInfo;             string channelName;             string transportType;             string connectionName;             //get channel info             char[] separator = { '/' };             string[] ChannelParams;             ChannelInfo = "CHANNEL3/TCP/172.19.37.2";             ChannelParams = ChannelInfo.Split(separator);             channelName = ChannelParams[0];             transportType = ChannelParams[1];             connectionName = ChannelParams[2];             //g

How to get user name of logon windows user.

This Code shows how to get user name of log on windows user. Here is the code : C# Code  string a; a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); MessageBox.Show(a.ToString()); By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Who is connected to database - Sample Application C#

Image
This is a sample application just to show who is currently connected into database MSSQL. The application actually just execute MSSQL command " sp_who " and show the data into datagrid. Below is a screen shoot of the sample application. Code Behind View Who Is Connected Form          public Form1()         {             InitializeComponent();         }         private void button2_Click(object sender, EventArgs e)         {             this.Close();         }         private void button1_Click(object sender, EventArgs e)         {             string ipaddress = textBox1.Text;             string username = textBox2.Text;             string password = textBox3.Text;             string dbNAme = textBox4.Text;             ViewUserActive form = new ViewUserActive();             form.popupInformation(ipaddress, username, password, dbNAme);                }         private void Form1_Load(object sender, EventArgs e)         {                  } Code Behind ViewUserActive Form      

C# - How to open form in full screen

This example shows how to make open windows form full screen of computer. In this example, i will use F11 as a shortcut key to turn form to full screen. Step By Step : Create one windows form project Add Form 2 in the solution. Add method to event Key Up in Form 1 Copy code below in Key Up  event method Form 1 The Code private bool _bFullScreenMode = false; : : : private void Form1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if ( e.KeyData == Keys.F11) { if (_bFullScreenMode == false) { Form2 f = new Form2(); this.Owner = f; this.FormBorderStyle = FormBorderStyle.None; this.Left = (Screen.PrimaryScreen.Bounds.Width/2 - this.Width/2); this.Top = (Screen.PrimaryScreen.Bounds.Height/2 - this.Height/2); f.Show(); _bFullScreenMode = true; f.KeyUp +=new KeyEventHandler(Form1_KeyUp); } else { Form f = this.Owner; this.Owner = null; f.Close(); this.FormBorderStyle = FormBorderStyle.Sizable;

Moving text example in C#

Image
This is a example of creating moving text in C#. In order to do the moving text, you just need timer and label controller/component . Steps by Step: Create one windows form project add one label in the form. copy and paste code below. Hit "CTRL + F5" and see what will happen. The code : public partial class Form1 : Form     {         private string[] words = new string[3];         private int i, j;         public Form1()         {             InitializeComponent();         }         private void timer1_Tick(object sender, EventArgs e)         {             if(i.Equals(words[j].Length))             {                               label1.Text = "";                 if (j < words.Length - 1)                 {                     j = j + 1;                     label1.Text = words[j];                 }                 else                 {                     j = 0;                 }                 i = 0;             }             label1.Text = words[j].Substring

CSV Splitter example in VB.NET

Image
Hye guys, this is a example of CSV Splitter created from VB.NET language. Since i dont have enough time to explained each code, so i just copy the code here and feel free to ask me in the comment. Basically this example will split huge .csv file into several file. So that you can open the csv file faster rather than open the huge one. The Code Imports System.IO Imports System.Text Public Class Form1     Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code "     <STAThread()> _     Public Shared Sub Main()         Application.EnableVisualStyles()         Application.Run(New Form1)     End Sub     Public Sub New()         MyBase.New()         'This call is required by the Windows Form Designer.         InitializeComponent()         'Add any initialization after the InitializeComponent() call     End Sub     'Form overrides dispose to clean up the component list.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boole

CSV Splitter example in C#

Image
Hye guys, this is a example of CSV Splitter created from C# language. Since i dont have enough time to explained each code, so i just copy the code here and feel free to ask me in the comment. Basically this example will split huge .csv file into several file. So that you can open the csv file faster rather than open the huge one. The Code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.VisualBasic; using System.Collections; using System.Diagnostics; using System.IO; using System.Threading; namespace CSV_Splitter {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         public delegate void UpdateProgressSub(int CurrentLine);         private bool _IsAbort;         public void SplitCSV(string FilePath,int lineStart, int lineEnd, int LineCount, int MaxOutputFile, Up

What you need to know about Static class

Static Class Properties A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator.  A static class is a sealed class. That means you cannot inherit any class from a static class.  A static class can have static members only. Having non-static member will generate a compiler error. A static class is less resource consuming and faster to compile and execute.  Static Class Example Public static class MyStaticClass  {      Private static int myStaticVariable;      Public static int StaticVariable;      {         Get        {            return myStaticVariable;        }         Set        {            myStaticVariable = value;        }     }    Public static void Function()    {    }  }  Note : The static class can directly called out from the other class for example you create class ClassA , and you can directly type in ClassA to call Function method in class MyStaticClass like this. MyStaticClass.Function(); By Mohd Zul

Nullable Types in .Net C#

Image
Since .NET version 2.0, the new feature introduce which is nullable types.  In the basic programming, how do you assign null to the promitive type such as int, long, and bool. Its is impossible. The following code shows how to define an integer as nullable type and checks if the value of the integer is null or not. Example  /// <summary> /// Nullable types /// </summary> public static void TestNullableTypes() { // Syntax to define nullable types int? counter; counter = 100; if (counter != null) { // Assign null to an integer type counter = null; Console.WriteLine("Counter assigned null."); } else { Console.WriteLine("Counter cannot be assigned null."); Console.ReadLine(); } } If you remove the "?" from int? counter, you will see a warning as following: By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social

How to enable GZip or Deflate on ASP.NET(HTTP Compression)

HTTP compression is a capability that can be built into web servers and web clients to make better use of available bandwidth, and provide greater transmission speeds between both. HTTP data is compressed before it is sent from the server: compliant browsers will announce what methods are supported to the server before downloading the correct format; browsers that do not support compliant compression method will download uncompressed data. Compression as defined in RFC 2616 can be applied to the response data from the server (but not to the request data from the client) The most common compression schemas include gzip and deflate. So how do we gonna achieve this  HTTP Compression on asp.net application.? Here is the Step : Open Global.asax file. Add the method IsCompressionAllowed() to check if compression is allowed. Add code in Application_Start event. Global.asax File void Application_Start(object sender, EventArgs e)         {             //check if request is aspx page.. if java

Basics of .NET Programs and Memory Management

Image
.NET has made a lot of improvements in its core to enhance the performance of an application. It is the first solid-core environment that really connects to all parts of the technology for developers. Inorder to make solid footsteps in the .NET environment, it would be great to know about the basic advantages and also the architecture of the .NET environment that you are going to start working on. The most important infrastructural component of the .NET framework is Common Language Runtime (CLR) . The code that you write inside the framework is called the managed code , which benefits from cross-language integration, cross-language exception handling, enhanced security,  versioning, and easy deployment support. Every component in a managed environment conveys some specific rule sets. When you write your code in a managed environment, the code gets compiled into the common intermediate language (CIL) . This language remains constant or equivalent to a code that might be compiled from an