Thursday 21 August 2014

Await in Catch and Finally

Leave a Comment
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 (exception != null)
  await MyLogger.LogAsync(exception);




This is only a simple example; in real-world code, this can get ugly rather quickly!

By
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 =)
Read More...

Wednesday 20 August 2014

HEX to ASCII and ASCII to HEX Class - C#

Leave a Comment
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 charcter using substring.
            //then  convert character into ascii.
            //then convert ascii value into Hex Format

            string sValue;
            string sHex = "";
            while (Data.Length > 0)
            {
                sValue = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()));
                Data = Data.Substring(1, Data.Length - 1);
                sHex = sHex + sValue;
            }

            return sHex;
        }
    }
}




By
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 =)
Read More...

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

Leave a Comment
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 static void Error(string sMsg)
        {
            Error("Error :", sMsg);
        }
        public static void Error(string sTitle, string sMsg)
        {
            MessageBox.Show(sMsg, sTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box      
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sMsg)
        {
            Warning("", sMsg);
        }

        //---------------------------------------------------------------------

        // Displays a Warning type message box       
        // parameter name="sCaption" is  Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Warning";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box       
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sMsg)
        {
            Info("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box      
        // parameter name="sCaption" is Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Information";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}



By
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 =)
Read More...

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

Leave a Comment
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;
            }
            string r = hc.Substring(0, 2);
            string g = hc.Substring(2, 2);
            string b = hc.Substring(4, 2);
            Color color = Color.Empty;
            try
            {
                int ri
                   = Int32.Parse(r, System.Globalization.NumberStyles.HexNumber);
                int gi
                   = Int32.Parse(g, System.Globalization.NumberStyles.HexNumber);
                int bi
                   = Int32.Parse(b, System.Globalization.NumberStyles.HexNumber);
                color = Color.FromArgb(ri, gi, bi);
            }
            catch
            {
                // you can choose whether to throw an exception
                //throw new ArgumentException("Conversion failed.");
                return Color.Empty;
            }
            return color;
        }

        /// <summary>
        /// Extract only the hex digits from a string.
        /// </summary>
        public static string ExtractHexDigits(string input)
        {
            // remove any characters that are not digits (like #)
            Regex isHexDigit
               = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
            string newnum = "";
            foreach (char c in input)
            {
                if (isHexDigit.IsMatch(c.ToString()))
                    newnum += c.ToString();
            }
            return newnum;
        }

    }  

}


MessageBox 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 static void Error(string sMsg)
        {
            Error("Error :", sMsg);
        }
        public static void Error(string sTitle, string sMsg)
        {
            MessageBox.Show(sMsg, sTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box. parameter name="sMsg" is The message you want to display
        public static void Warning(string sMsg)
        {
            Warning("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box       
        // parameter name="sCaption" is  Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Warning";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        //---------------------------------------------------------------------
        // Displays a Information type message box    
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sMsg)
        {
            Info("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box       
        // parameter name="sCaption" is Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Information";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }
}


Program Code Behind

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using messageBox;

namespace Convert_Hex_String_to.NET_Color
{
    public partial class Form1 : Form
    {
        private string msAppName = "Convert CSS String color to .Net Color Class"; // Program Name

        public Form1()
        {
            InitializeComponent();     
        }

        public void TestHexStringToColor(string hexColor)
        {
            // invent some hex colors
            string[] h = new string[1];
            h[0] = hexColor;

            // convert the hex values to colors
            Color[] colors = new Color[4];
            colors[0] = ConversionClass.HexStringToColor(h[0]);

            // print the results
            Result.Text = "";
            for (int i = 0; i < h.Length; i++)
            {
                Result.Text += "\n" + h[i] + " =  "

                   + colors[i].Name + ", Red=" + colors[i].R.ToString()
                   + ", Green=" + colors[i].G.ToString()
                   + ", Blue=" + colors[i].B.ToString();                 

            }

        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MsgBox.Info("Thank You");
            this.Close();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MsgBox.Info("Created By Mohd Zulkamal. - www.developersnote.com");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string hexColor = textBox1.Text.ToString();
            if (hexColor == "")
            {
                MsgBox.Info("Input was nothing");
                return;
            }
            else if (hexColor.Substring(0, 1) != "#")
            {
                MsgBox.Info("First Character must be \"#\"");
                return;
            }
            else
            {
                try
                {
                    TestHexStringToColor(textBox1.Text.ToString());
                }
                catch (Exception ex)
                {
                    MsgBox.Error(ex.Message.ToString());
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = this.msAppName;
        }
    }
}

Output



By
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 =)
Read More...

Saturday 16 August 2014

Register winform app HotKeys - C#

Leave a Comment
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);
        }

        public override int GetHashCode()
        {
            return modifier ^ key ^ hWnd.ToInt32();
        }

        [DllImport("user32.dll")]

        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

        [DllImport("user32.dll")]

        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    }

}


CodeBehind WinForm 

 
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 Hotkeys;

namespace HotkeyWin
{
    public partial class Form1 : Form
    {
        private Hotkeys.GlobalHotkey ghk;
        public Form1()
        {
            InitializeComponent();
            ghk = new Hotkeys.GlobalHotkey(Constants.ALT + Constants.SHIFT, Keys.O, this);
        }

        private void HandleHotkey()
        {
            WriteLine("Hotkey pressed!");
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == Hotkeys.Constants.WM_HOTKEY_MSG_ID)
                HandleHotkey();
            base.WndProc(ref m);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WriteLine("Trying to register SHIFT+ALT+O");
            if (ghk.Register())
                WriteLine("Hotkey registered.");
            else
                WriteLine("Hotkey failed to register");
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ghk.Unregiser())
                MessageBox.Show("Hotkey failed to unregister!");
        }

        private void WriteLine(string text)
        {
            textBox1.Text += text + Environment.NewLine;
        }
    }
}

Output



By
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 =)
Read More...

Monday 4 August 2014

Get each table size in mssql database

Leave a Comment
This is the snippet to get each table size in the schema/catalogue database.

MSSQL Code

  
SELECT

    t.NAME AS TableName,

    s.Name AS SchemaName,

    p.rows AS RowCounts,

    SUM(a.total_pages) * 8 AS TotalSpaceKB,

    SUM(a.used_pages) * 8 AS UsedSpaceKB,

    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB

FROM

    sys.tables t

INNER JOIN     

    sys.indexes i ON t.OBJECT_ID = i.object_id

INNER JOIN

    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id

INNER JOIN

    sys.allocation_units a ON p.partition_id = a.container_id

LEFT OUTER JOIN

    sys.schemas s ON t.schema_id = s.schema_id

WHERE

    t.NAME NOT LIKE 'dt%'

    AND t.is_ms_shipped = 0

    AND i.OBJECT_ID > 255

GROUP BY

    t.Name, s.Name, p.Rows

ORDER BY

    t.Name


By
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 =)
Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.