Posts

Showing posts with the label C#

C#: Execute Two Dependant Processes

This example shows how to run 2 program in application and the second program need to run after the first program successfully start. The example will use 2 program which is Notepad and Paint . The Notepad need to run first and after Notepad successfully run, the Paint application will start to open program. Let see the code. Two Dependant Processes using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Threading; namespace TwoDependantProcesses {      class Program     {           static void Main(string[] args)          {                  Console.WriteLine("Press Enter to start Notepad (i.e. Process 1)");                  Console.ReadKey();                  Console.WriteLine("Starting Notepad...");                  Thread t1 = new Thread(new ThreadStart(StartProcess1));                   t1.Start();                   while (t1.IsAlive == true)                  {                       System.Threading.Thread.Sleep

Get Files from Directory - C#

This example shows how to get list of file names from a directory (including subdirectories). You can filter the list by specific extension. To get file names from the specified directory, use static method Directory.Get­Files . Lets have these files and subfolders in „c:\MyDir“ folder: Get files from directory Method Directory.GetFiles returns string array with files names (full paths). using System.IO; string [] filePaths = Directory .GetFiles ( @"c:\MyDir\" ); // returns: // "c:\MyDir\my-car.BMP" // "c:\MyDir\my-house.jpg" Get files from directory (with specified extension) You can specify search pattern. You can use wildcard specifiers in the search pattern, e.g. „*.bmp“ to select files with the extension or „a*“ to select files beginning with letter „a“. string [] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp"); // returns: // "c:\MyDir\my-car.BMP" Get files from directory (including all subdirectories) If you want

C# Method to Convert ASCII to EBCDIC vice versa

This example show convertion between ASCII character to EBCDIC character and EBCDIC to ASCII. ASCII To EBCDIC public string ConvertASCIItoEBCDIC(string strASCIIString) {      int[] a2e = new int[256]      {         0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15,         16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31,         64, 79,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97,         240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111,         124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,         215,216,217,226,227,228,229,230,231,232,233, 74,224, 90, 95,109,         121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150,         151,152,153,162,163,164,165,166,167,168,169,192,106,208,161, 7,         32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27,         48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62,225,         65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87,       

7 way to convert DataTable to generic List - C#

Conversion DataTable to Generic List<t>. We can do it in various way. Solution 1: DataTable dt = CreateDataTable(); List<datarow> list = new List<datarow>(); foreach (DataRow dr in dt.Rows) {      list.Add(dr); } Solution 2: DataTable table = new DataTable { Columns = { {"Foo", typeof(int)}, {"Bar", typeof(string)} } }; for (int i = 0; i < 5000; i++) {      table.Rows.Add(i, "Row " + i); } List<T> data = new List<t>(table.Rows.Count); foreach (DataRow row in table.Rows) {       data.Add(new T((int)row[0], (string)row[1])); } Solution 3: Using Linq expression. It return data in List<t>. List<string> list =dataTable.Rows.OfType<datarow>().Select(dr => dr.Field<string>(0)).ToList(); Solution 4: Using Linq/lamda expression. List<employee> list= new List<employee>(); list = (from DataRow row in dt.Rows select new Employee {      FirstName = row["ColumnName"].ToString(),      Last

How To Remove duplicate space within character - C#

This example show the method to remove duplicate space in data. You can use this method to remove duplicate space within the word. public string removeDuplicateSpace(string data) {     string _temp = data;     string reBuildData = "";     bool space = false;     foreach (char a in _temp)     {         if (a == ' ')         {             if (!space)             {                 space = true;                 reBuildData += a;             }                             }           else           {             reBuildData += a;             space = false;           }       }       return reBuildData; } Input :  Hello         World Output : Hello World  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 =)

C# Using StreamReader

You want to read a text file using StreamReader from the System.IO namespace in the C# language and base class libraries. With the using statement, which is ideal for this purpose, you can both perform actual file IO and dispose of the system resources. Tip: StreamReader is an excellent way to read text files. The using statement allows you to leave the file disposal and opening routines to the C# compiler's knowledge of scope. This statement will be compiled to opcodes that instruct the CLR to do all the error-prone and tedious cleanup work with the file handles in Windows.  StreamReader [C#] using System; using System.IO; class Program { static void Main() { // It will free resources on its own. string line; using (StreamReader reader = new StreamReader("file.txt")) { line = reader.ReadLine(); } Console.WriteLine(line); } } Note: when objects go out of scope, the garbage collector or finalization code is

Remove Whitespace From aspx pages - Performance with page speed

Some web page have a thousand line of html code and it will increase the size of the page to download to users. It is often possible to make a content of web page fewer bytes(their size) without changing the appearance or function of the page. This approach will improve download time and makes the page load faster. The question how to make this happen without extra effort to remove the space manually and without effect the development time. This is a snippet code that you need to put in your Master page so that the code will automatically override the Render Event in asp.net The Code to put in Master Page The Attribute/Field for masterpage private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled); private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled); The Override Method /// <summary>         /// Initializes the <see cref="T:System.Web.UI.HtmlTextWriter">&l

Simple Image Resizer Tools - C# Example

Image
This example will use the  Image Resizer Class from previous post . I have change a little bit on the class so that i can use it for my example image resizer tools. ImageResizer Tool Requirement ImageResizer tool will require user to choose the image to resize. Only JPG image supported. After that user can simply put the width and height to change the selected image width and height. User can choose is either to use aspect ratio. After Complete , user will prompt to open the new image after resize. The tools use .NET version 4. The GUI of ImageResizer Tool The Code Behind   private string _ImageName;         private string _ImageExtension;         public Form1()         {             InitializeComponent();             TPercentage.Text = "0";             tWidth.Text = "0";             THeight.Text = "0";         }         private void button1_Click(object sender, EventArgs e)         {             openFileDialog1.Filter = "JPEG Files (.JPG)|*.JPG

Example to disable save as certain file type in SSRS Report Viewer

Image
SQL Server Reporting Service(SSRS) is a full range of ready-to-use tools and services to help you create, deploy, and manage reports for your organization, as well as programming features that enable you to extend and customize your reporting functionality. The Report Viewer provide functionality to save the report as a pdf, word and also as a excel format. Sometime organization require this feature, sometime not. This is how to disable save as function in Report Viewer(SSRS). The example will invoke methode pre-render in Report Viewer Controller. The ASPX Page <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"     Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %> : : : <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat

How to open file using their default external viewer - C#

When write the application, some of the activity is to create file, convert file, etc . After create the file, the program should prompt user to open the created file using their respective default external viewer . Letsay you create .pdf file, so the default application to open the file is Adobe Reader . The example will ask user is either user want to open file or not, if user agreed to open the file created, then the application will open file using their respective default external viewer depend on the file extension . The code    string outFilePath = File.Create("PDFFILE.pdf");                               DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);   if (dr == DialogResult.Yes)   {       System.Diagnostics.Process.Start(outFilePath);   } By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and

How to convert List to DataTable - C#,ASP.NET

Image
Short Description This example will show how to convert List<T> where T could be any object and convert the List<T> to DataTable. The example will use two class which is System.ComponentModel; and System.Data; Note : The Convertion class extention method must be in static because System.ComponentModel.TypeDescriptor is a static method In this example i will use asp.net . The ASPX page      <h1>         How to convert List To DataTable     </h1>     <asp:GridView ID="GridView1" runat="server">     </asp:GridView> The Code Behind        protected void Page_Load(object sender, EventArgs e)         {             List<string> listOfString = new List<string>();             for (int i = 0; i < 10; i++)             {                 listOfString.Add(i.ToString());             }                        GridView1.DataSource = Convertion.ToDataTable<string>(listOfString);             GridView1.DataBind();         } The

C#: Retrieve Machine Information

Image
This is a example how to get Machine Information in C#. The example will use Class ManagementObjectSearcher --> System.Management Note: The code will only work on Window 32 bit, If you are using 64 bit Operation system, you need to comment few Method GetTotalPhysicalMemory,GetTotalVirtualMemory,and GetAvailableVirtualMemory. The MachineInfo Class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; using System.Net; using System.Diagnostics; namespace GenericErrorHandling {     class MachineInfo     {         ManagementObjectSearcher query;         ManagementObjectCollection result;         string responseString;         int responseInt;         public string GetMachineName()         {             return Environment.MachineName.ToUpper();         }         public string GetOSVersion()         {             return Environment.OSVersion.VersionString;         }         public string GetProcessorCount()         {             r

C#: use EventLog to store error message example

Image
EventLog lets you access or customize Windows event logs, which record information about important software or hardware events. Using EventLog , you can read from existing logs, write entries to logs, create or delete event sources, delete logs, and respond to log entries. You can also create new logs when creating an event source. The example will show how to use event log in your application The Code private void button1_Click(object sender, EventArgs e)  {     try     {         string[] a = new string[3];         a[4] = "test";     }     catch (Exception ex)    {         LogError(ex);     }  } public void LogError(Exception ex)  {     string EventLogSourceName = "Example Log Error";     int EventLogErrorCode = 99;     string msg = "The application encountered an unknown error:";     msg += "\r\nExecuting Method: " + new System.Diagnostics.StackFrame(1, false).GetMethod().Name;     msg += "\r\nError Message: " + ex.Message;    

How to show hide form(Desktop application) C#

Usually when programmer to hide the form from User they will use this command : this.Hide(); But the problem is..how to unhide that form..So the this is a solution to unhidden the form.. Scenario You have 2 Form, Form1 and Form2. the situation is form2 was hide and you want to show it back  foreach (Form form in Application.OpenForms) {      if (form is Form2)      {        form.Show();          break;      } } 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 =)

How to create XML file using C#

XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). Once we create an XML file in one platform it can be used in other platforms also. In order to creating a new XML file in C#, we are using XmlTextWriter Class . The class takes FileName and Encoding as argument. Also we are here passing formatting details . The following C# source code creating an XML file product.xml and add four rows in the file The Code using System; using System.Data; using System.Windows.Forms; using System.Xml; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.In

Detect Browser In Code Behind ASP.NET

Image
Certain javascript will work on certain browser only. So inorder to avoid your client from using the application which is bot supported by your application, you can filter the browser type from code behind of your web application.   Let see the example The ASPX page <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title></title> </head> <body>     <form id="form1" runat="server">     <div>         </div>     </form> </body> </html> The Code Behind  protected void Page_Load(object sender, EventArgs e)         {             System.Web.HttpBrowserCapabilities browser = Request.Browser;             string s = "Browser Capabilities &lt;br/&gt;"                 + "Type = " + browser.Type