Posts

Showing posts with the label C#

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

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

Decimal Manipulation in C#

This post will  show manipulation on the Data Type Decimal. //This is the hard code value for decimal   //without suffic m or M, the compiler thread the object as a double hence will cause error   decimal price = 10.1654M;   //Convert decimal to double   double priceInDouble = Convert.ToDouble(price); //output : 10.1654   priceInDouble = (double)price;//output : 10.1654   //convert to double with 2 decimal point,           priceInDouble = Math.Round((double)price, 2); // output : 10.17   //convert back to decimal   price = Convert.ToDecimal(priceInDouble);//output : 10.17   price = (decimal)priceInDouble;//output : 10.17   //convert decimal to currency. The currency format will depend on the region,   //like myself in malaysia compiler will automatically give "RM" as a currency format   string currency = String.Format("Order Total: {0:C}", price); //output :RM10.17   currency = String.Format("Order Total: {0:C2}", price); //output :RM10.17 ,2 decimal poi

How to send email in ASP.NET- C# example

Image
This is example how to send email from asp,net web application. Refer this post if you want to send email in java code . This example will use google smtp email server. The aspx Page <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <asp:Label ID="LErrorMessage" runat="server" ></asp:Label>     <asp:Button ID="Button1" runat="server" Text="Send Email" OnClick="Button1_Click" /> </asp:Content> The Code Behind  protected void Page_Load(object sender, EventArgs e)         {         }         protected void Button1_Click(object sender, EventArgs e)         {                        string emailContent = "This mail is created and send through the c# code,"                     + "\n\n if you are developers, visit http://www.developersnote.com!",                     subject = "Developersnote update - Mail Send Using AS

Multiple select button in one gridview

Image
GridView Multiple Select Buttons this is the keyword when i used to searching in Mr. Google and end up with several link to solve this problem. This was my solution to have a multiple select button in one GridView Controller The ASPX Page   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Font-Names="Arial" Font-Size="12px" OnRowCommand="ActionCommand"> <Columns> <asp:BoundField DataField="ID" HeaderText="NO." /> <asp:BoundField DataField="CustomerName" HeaderText="Customer Name" /> <asp:ButtonField CommandName="showName" Text="Show Name" /> <

C#: Check if an application is already running

This is the snippet code to check if application running or not in C# using System.Diagnostics; bool IsApplicationAlreadyRunning(string processName) { Process[] processes = Process.GetProcessesByName(processName); if (processes.Length >= 1) return true; else return false; } 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 =)

RegisterForEventValidation can only be called during Render()[SOLVED]

Today i do my routine by developing / testing / and debuggig and found error on my web page : RegisterForEventValidation can only be called during Render(); The code actually for get html code from server side inside panel ...  var sb = new StringBuilder();  Panel1.RenderControl(new HtmlTextWriter(new StringWriter(sb)));  string htmlToConvert = sb.ToString(); So i do some googling and found the causes of this error occur.. The Causes occurs when you try to render a control to Response. Generally some people got this when I exported GridView to Excel, Word, PDF or CSV formats. The ASP.Net compiler issues the above Exception since it feels the Event is invalid. Solution The solution is quite simple you need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to FALSE You can set it in the Web.Config in the following way <pages enableEventValidation="false"></pages> This will apply to all the pages in your website. Else yo

C# coalesce operator : Question Mark In C# and Double Question Mark

A not so common, but very useful operator is the double question mark operator (??). This can be very useful while working with null able types. Lets say you have two nullable int: int? numOne = null; int? numTwo = 23; Note : int? (data type with question mark used to declare variable with null able type) Scenario: If numOne has a value, you want it, if not you want the value from numTwo , and if both are null you want the number ten (10). Old solution: if (numOne != null)     return numOne; if (numTwo != null)     return numTwo; return 10; Or another solution with a single question mark : return (numOne != null ? numOne : (numTwo != null ? numTwo : 10)); But with the double question mark operator we can do this: return ((numOne ?? numTwo) ?? 10); Output : return numOne if have value, else return numTwo else return 10; As you can see, the double question mark operator returns the first value that is not null. By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will a

Pinging in ASP.NET Example

Image
This tutorial will show you how to ping a hostname/ip using the .NET System.Net class, ASP.NET 2.0 and C#.NET. The .NET Framework offers a number of types that makes accessing resources on the network easy to use. To perform a simple ping, we will need to use the System.Net, System.Net.Network.Information, System.Text namespaces. using System.Net; using System.Net.NetworkInformation; using System.Text; ASPX Page  <asp:ScriptManager ID="ScriptManager1" runat="server">     </asp:ScriptManager>     <asp:UpdatePanel ID="UpdatePanel1" runat="server">         <ContentTemplate>             <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc">                 <tr>                     <td width="100" align="right" bgcolor="#eeeeee" class="header1">                         Ho

Constants VS ReadOnly

Constants are similar to read-only fields. You can’t change a constant value once it’s assigned. The const keyword precedes the field to define it as a constant. Assigning value to a constant would give a compilation error. For example: const int num3 = 34; num3 = 54; // Compilation error: the left-hand side of an assignment must  // be a variable, property or indexer Although constant are similar to read-only fields, some differences exist. Constants are always static, even though you don’t use the static keyword explicitly, so they’re shared by all instances of the class. The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Example Constant public class ConstTest {     class SampleClass     {         public int x;         public int y;         p