Tuesday, October 28, 2008

New Blackfin BF51x Processor Launches

analog-devices-blackfin.jpgAnalog Devicesunveiled the new Blackfin BF51x series, the newest membzers of their convergent-processor family. Blackfin processors are very popular when building Asteris-based appliances, including the Digium Asterisk Appliance AA50 and Astfin. The Blackfin convergent-processor architecture offers reduced cost, power consumption, and software complexity. Although the processor is popular in creating Asterisk appliances, it can be used for a variety of low-cost, low-power consumption required applications.

The new Blackfin processors are the BF512, BF514, BF516 and BF518. According to Analog Devices, "All are single-core convergent processors that surpass outdated, heterogenous MCU+DSP approaches in reducing part-count, system cost, board space, and power consumption. Like traditional DSPs, the BF51x processors feature high clock rates and low power dissipation per unit of processing (MMACs/mW), and like traditional MCUs, these convergent processors are OS and compiler-friendly."

All four of the new 16-/32-bit BF51x processors are available at clock speeds up to 400 MHz (800 MMACS) and include 116 kBytes of RAM plus an optional 4 Mbits of serial (SPI) flash memory. Each also integrates Lockbox security for code and content protection.

The Blackfin processors on-chip integration assures easy connection to a variety of audio, video, imaging and communications peripherals and memory types. Integrated features include support for sixteen stereo I2S digital-audio channels, twelve peripheral DMA channels, and an advanced memory controller for glueless connection to multiple banks of external SDRAM, SRAM, Flash, or ROM. Each processor includes two dual-channel synchronous serial communication ports (SPORTs), a high-speed parallel peripheral interface (PPI), an I2C compatible two-wire interface (TWI), dual PC-compatible UARTs, and 2 SPI-compatible serial peripheral interface ports.

"System solutions ultimately determine how much power any particular application will consume," said Jerry McGuire, vice president, General Purpose DSP, Analog Devices, Inc. "It's quite intuitive that a single convergent processor with the right mix of integrated peripherals is always going to lead to lower BOM costs and power consumption than an inelegant combination of disparate processors and parts can possibly achieve. Many companies today talk about the lowest power or the highest performance. But what is important for today's applications is the highest levels of performance at low power."

All of the new Blackfin processors, delivering 8.5 MMACs/mW (100 MHz), include dynamic power management (DPM) functionality that lets developers match the processor's power consumption to processing requirements during program execution. AI pioneered the application of DPM more than seven years ago with the release of the first Blackfin processors.

The BF512 is the new low-cost entry point in the Blackfin processor family. The device balances performance, peripheral integration, and price, and is well suited for the most cost-sensitive applications including portable test equipment, embedded modems, biometrics, and consumer audio. All members of the BF51x family also include a new 3-phase PWM generation unit for inductive motor control applications and a quadrature interface for rotary encoders.
The BF514, BF516, and BF518 all extend the convergent processor family further into the portable application space with on-chip removable-storage interfaces. All three devices include Secure Digital Input Output (SDIO) for connectivity to standard flash memory and Wi-Fi cards; a power-optimized CE-ATA storage interface for small form-factor handheld and consumer electronics applications; and an embedded multimedia card (eMMC) interface for integrating mass-storage flash memory in a wide range of consumer electronics, wireless, navigation, and industrial applications.

For developers of network-connected industrial and instrumentation applications, the BF516 adds an Ethernet 10/100 MAC with Media Independent Interface (MII) and Reduced Media Independent Interface (RMII). Highly integrated for industrial, portable and VoIP applications, the BF518 Ethernet MAC supports theIEEE-1588 clock synchronization protocol for networked measurement and control systems.

An increasingly wide variety of applications are viewing the contemporary convergent-processor approach as the soundest choice for cost- and power-sensitive designs. For example, some voice-over-IP (VoIP) telephony system developers have designed in separate DSP and microcontroller chips to implement the required media and control functionality. With BF51x Blackfin processors, however, a single architecture enables full VoIP telephony functionality in a unified software development environment with faster system debugging and deployment, lower overall system cost, and the lowest possible system power demand.

"GIPS VoiceEngine media processing capabilities meet the highest requirements of VoIP equipment manufacturers and paired with Analog Devices' Blackfin processors we can assure customers a consistently high quality VoIP experience. The performance, power and functionality profile of Blackfin is a superb fit for VoIP technology," said Larry Golob, Senior Director Business Development,Global IP Solutions.

With the Global IP Solutions (GIPS) VoiceEngine package of VoIP software components available for Blackfin processors, and a VoIP reference platform available on uClinux, the feature-rich Blackfin family has driven down the price required to easily design and deploy a fully scalable range of VoIP telephony designs across multiple market spaces.

Pricing and Availability
The BF51x family includes the BF512 at $4.95, the BF514 at $7.75, the BF516 at $8.75 and the BF518 at $11.85. Processors are sampling immediately. All prices are based on 25,000-unit quantities.


Read more!!!

Friday, October 24, 2008

Media Player in C#

/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow

Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using MediaPlayer ;

namespace SMK_MediaPlayer
{
///
/// Summary description for SMKMediaPlayer.
///
public class SMKMediaPlayer : System.Windows.Forms.Form
{
///
/// Required designer variable.
///

private AxMediaPlayer.AxMediaPlayer mPlayer = null ;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.NotifyIcon notifyIcon1;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuItem6;
private System.ComponentModel.IContainer components;

public SMKMediaPlayer()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
notifyIcon1.Dispose() ;
mPlayer.Stop() ;
mPlayer.Dispose();

if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

private void streamEnded(object sender , AxMediaPlayer._MediaPlayerEvents_EndOfStreamEvent e)
{
this.Show();
notifyIcon1.Visible = false ;
mPlayer.Stop();
mPlayer.CurrentPosition= 0.0;
}

#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SMKMediaPlayer));
this.panel2 = new System.Windows.Forms.Panel();
this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// panel2
//
this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(344, 109);
this.panel2.TabIndex = 1;
//
// notifyIcon1
//
this.notifyIcon1.Text = "notifyIcon1";
this.notifyIcon1.Visible = true;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem4});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem2,
this.menuItem3});
this.menuItem1.Text = "File";
//
// menuItem2
//
this.menuItem2.Index = 0;
this.menuItem2.Text = "Open";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// menuItem3
//
this.menuItem3.Index = 1;
this.menuItem3.Text = "Exit";
this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
//
// menuItem4
//
this.menuItem4.Index = 1;
this.menuItem4.Text = "Hide";
this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem5,
this.menuItem6});
//
// menuItem5
//
this.menuItem5.Index = 0;
this.menuItem5.Text = "Show";
this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click);
//
// menuItem6
//
this.menuItem6.Index = 1;
this.menuItem6.Text = "Exit";
this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click);
//
// SMKMediaPlayer
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(344, 109);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panel2});
this.MaximizeBox = false;
this.Menu = this.mainMenu1;
this.Name = "SMKMediaPlayer";
this.Text = "ActiveX Media Player";
this.Load += new System.EventHandler(this.SMKMediaPlayer_Load);
this.ResumeLayout(false);

}
#endregion

///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new SMKMediaPlayer());
}

private void SMKMediaPlayer_Load(object sender, System.EventArgs e)
{
notifyIcon1.Icon = new Icon("EYE.ico");
notifyIcon1.Text = "SMK Media Player 1.0";
notifyIcon1.Visible = false ;
notifyIcon1.DoubleClick += new EventHandler(NotifyIconDoubleClick);
notifyIcon1.ContextMenu = contextMenu1 ;

mPlayer = new AxMediaPlayer.AxMediaPlayer();
mPlayer.BeginInit();
mPlayer.Size = new System.Drawing.Size(292, 273);
mPlayer.Location = new System.Drawing.Point(0 , 16);
mPlayer.TabIndex = 0;
mPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Controls.AddRange(new System.Windows.Forms.Control[] {this.mPlayer});

mPlayer.EndOfStream
+= new AxMediaPlayer._MediaPlayerEvents_EndOfStreamEventHandler(this.streamEnded);

mPlayer.EndInit();
}

private void menuItem2_Click(object sender, System.EventArgs e)
{
try
{
Image im = imageList1.Images[0];
OpenFileDialog fd = new OpenFileDialog();
fd.ShowDialog();
mPlayer.Open(fd.FileName);
mPlayer.Play();
}
catch(Exception eee)
{
Console.WriteLine(eee.Message);
}
}

private void menuItem4_Click(object sender, System.EventArgs e)
{
notifyIcon1.Visible = true ;
this.Hide();
}

private void menuItem3_Click(object sender, System.EventArgs e)
{
Application.Exit() ;
}

private void menuItem5_Click(object sender, System.EventArgs e)
{
notifyIcon1.Visible = false;
this.Show();
}

private void menuItem6_Click(object sender, System.EventArgs e)
{
notifyIcon1.Visible = false ;
Application.Exit() ;
}

private void NotifyIconDoubleClick(object sender, System.EventArgs e)
{
this.Visible = true ;
this.Activate() ;
this.Show() ;
this.BringToFront() ;
}

}
}

source code from http://www.java2s.com/Code/CSharpDownload/SMK_MediaPlayer.zip


Read more!!!

Thursday, October 23, 2008

Static Route on Linux RedHat 9

With the introduction of Redhat version 8 and continued into version 9, the /etc/sysconfig/static-routes file no longer seems to function correctly.

Linux static routes changed in 8.0 to a new format. Now you are to create a file in /etc/sysconfig/network-scripts for each Ethernet interface you wish to create static routes on.

Example:
touch /etc/sysconfig/network-scripts/route-eth0

The syntax for this file is different from the traditional route format used in /etc/sysconfig/static-routes . Redhat has yet to document the change on their web site as of June 2003.

Syntax based on a usenet post go to /etc/sysconfig/network-scripts, make a file called route-devicename (ex: route-eth0) and populate it with your static routes for that device so if you wanted to make a static route to the 192.168.0.0/24 network through 152.3.182.5 type:

192.168.0.0/24 via 152.3.182.5

Persistent static routes for ANY linux distribution

You may use this method to add static routes and it will work under any Linux distribution. However, it is considered by some a 'hack' or the 'ugly way'.

Edit your /etc/rc.local file and add your static routes using the route statement.

Example:
route add -net 10.10.98.0 netmask 255.255.255.0 gw 10.164.234.132 dev eth1
route add -net 10.164.234.96 netmask 255.255.255.252 gw 10.164.234.132 dev eth1
route add -net 10.164.234.112 netmask 255.255.255.240 gw 10.164.234.132 dev eth1

Force the old static-routes file to work under Redhat 9

Clear out the new /etc/sysconfig/network-scripts/ifup-routes script so that you can populate it with the original shell script from Redhat 7.x.

cat /dev/null > /etc/sysconfig/network-scripts/ifup-routes
vi /etc/sysconfig/network-scripts/ifup-routes

type in the following (or copy and paste) not including the tilde lines:

#!/bin/sh
# adds static routes which go through device $1

if [ "$1" = "" ]; then
echo "usage: $0 "
exit 1
fi

if [ ! -f /etc/sysconfig/static-routes ]; then
exit 0
fi

# note the trailing space in the grep gets rid of aliases
grep "^$1 " /etc/sysconfig/static-routes | while read device args; do
/sbin/route add -$args $device
done
grep "^any " /etc/sysconfig/static-routes | while read ignore type net netmask mask bogus dev ; do
if [ "$dev" = "$1" ]; then
/sbin/route add -$type $net $netmask $mask $dev
fi
done

Remember to use /etc/sysconfig/network for your default gateway

If you only intend to add one route, your default gateway, then you need not worry about the static routes file or using the route command. Simply add your default gateway in /etc/sysconfig/network.

Example
NETWORKING=yes
HOSTNAME="hostname.linux.org"
GATEWAY="10.164.234.1"
GATEWAYDEV="eth0"
FORWARD_IPV4="yes"


Read more!!!

Thursday, October 16, 2008

Add Object to ListBox in C#

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

public class Form1 : Form
{
private System.Windows.Forms.ListBox lstCustomers;
public Form1()
{
InitializeComponent();
lstCustomers.Items.Add(new Customer("A", "B", DateTime.Now.AddDays(-10)));
lstCustomers.Items.Add(new Customer("C", "D", DateTime.Now.AddDays(-100)));
lstCustomers.Items.Add(new Customer("F", "G", DateTime.Now.AddDays(-500)));
}
private void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
Customer cust = (Customer)lstCustomers.SelectedItem;
MessageBox.Show("Birth Date: " + cust.BirthDate.ToShortDateString());
}
private void InitializeComponent()
{
this.lstCustomers = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lstCustomers
//
this.lstCustomers.FormattingEnabled = true;
this.lstCustomers.Location = new System.Drawing.Point(12, 12);
this.lstCustomers.Name = "lstCustomers";
this.lstCustomers.Size = new System.Drawing.Size(120, 95);
this.lstCustomers.TabIndex = 0;
this.lstCustomers.SelectedIndexChanged += new System.EventHandler(this.lstCustomers_SelectedIndexChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(308, 230);
this.Controls.Add(this.lstCustomers);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}


public class Customer
{
public string FirstName;
public string LastName;
public DateTime BirthDate;

public Customer() { }

public Customer(string firstName, string lastName, DateTime birthDate)
{
FirstName = firstName;
LastName = lastName;
BirthDate = birthDate;
}

public override string ToString()
{
return FirstName + " " + LastName;
}
}


Read more!!!

Thursday, October 9, 2008

InputBox in C#

This example demonstrates how to show an InputBox in C# using simple static method.

InputBox

The following code shows the usage of an InputBox static method that simulates InputBox method known from VB and VB.NET. Our InputBox method is defined in a custom class Tmp.

string value = "Document 1";
if (Tmp.InputBox("New document", "New document name:", ref value) == DialogResult.OK)
{
myDocument.Name = value;
}

The method's imple­mentation is in the following code. The method takes three paramaters: a dialog title, a prompt text and the default textbox value. It returns a DialogResult to detect wheather the OK or the Cancel button has been clicked. The input value can be obtained from the input/output parameter value.
using System.Windows.Forms;
using System.Drawing;

public static DialogResult InputBox(string title, string promptText, ref string value)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button buttonOk = new Button();
Button buttonCancel = new Button();

form.Text = title;
label.Text = promptText;
textBox.Text = value;

buttonOk.Text = "OK";
buttonCancel.Text = "Cancel";
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;

label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);

label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;

DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
resource from http://www.csharp-examples.net/


Read more!!!

Wednesday, October 8, 2008

Combine Multiple PrintDocuments in C#

This example shows how to combine two or more PrintDocuments in­to a single PrintDocument. I created a class MultiPrintDocu­ment derived from PrintDocument. Its constructor takes an array of PrintDocument instances as a parameter.

The usage of the MultiPrintDocument class could be like this.
// suppose we need to join 3 PrintDocument instances doc1, doc2 and doc3
MultiPrintDocument multiDoc;
multiDoc = new MultiPrintDocument(new PrintDocument[] { doc1, doc2, doc3 })
MultiPrintDocument overrides protected methods OnBeginPrint, OnQueryPageSet­tings and OnPrintPage. The overridden methods call the corresponding methods of the child documents. Note that reflection must be used to call the protected methods of child documents.

OnBeginPrint method is called before the first page of the document is printed. The overridden OnBeginPrint method resets the current document index.

OnQueryPageSet­tings method is called immediately before printing each page and is used for getting the PageSettings of the printed page (e.g. to check whether the page orientation is landscape or portrait). The overridden method calls OnQueryPageSettings of the current child document.

OnPrintPage is called to print a page. The overridden method calls OnPrintPage of the current child document. If it is the last page of the document, it increments the current document index and returns a value indicating that there are still other pages to print.

This is the code of the MultiPrintDocument class.
using System.Drawing.Printing;
using System.Reflection;

public class MultiPrintDocument : PrintDocument
{
private PrintDocument[] _documents;
private int _docIndex;
private PrintEventArgs _args;
// constructors
public MultiPrintDocument(PrintDocument document1, PrintDocument document2)
{
_documents = new PrintDocument[] { document1, document2 };
}

public MultiPrintDocument(PrintDocument[] documents)
{
_documents = documents;
}
// overidden methods
protected override void OnBeginPrint(PrintEventArgs e)
{
base.OnBeginPrint(e);
if (_documents.Length == 0)
e.Cancel = true;
if (e.Cancel) return;
_args = e;
_docIndex = 0; // reset current document index
CallMethod(_documents[_docIndex], "OnBeginPrint", e);
}

protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
e.PageSettings = _documents[_docIndex].DefaultPageSettings;
CallMethod(_documents[_docIndex], "OnQueryPageSettings", e);
base.OnQueryPageSettings(e);
}

protected override void OnPrintPage(PrintPageEventArgs e)
{
CallMethod(_documents[_docIndex], "OnPrintPage", e);
base.OnPrintPage(e);
if (e.Cancel)
return;
if (!e.HasMorePages)
{
CallMethod(_documents[_docIndex], "OnEndPrint", _args);
if (_args.Cancel) return;
_docIndex++; // increments the current document index
if ( _documents.Length) > _docIndex
{
// says that it has more pages (in others documents)
e.HasMorePages = true;
CallMethod(_documents[_docIndex], "OnBeginPrint", _args);
}
}
}
// use reflection to call protected methods of child documents
private void CallMethod(PrintDocument document, string methodName, object args)
{
typeof(PrintDocument).InvokeMember(methodName,
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
null, document, new object[] { args });
}
}
resource from http://www.csharp-examples.net/


Read more!!!

Start, Stop and Restart Windows Service in C#

This example shows how to start, stop and restart a windows service programmatically in C#.

Start service
The following method tries to start a service specified by a service name. Then it waits until the service is running or a timeout occurs.
public static void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
Stop service
The following method tries to stop the specified service and it waits until the service is stopped or a timeout occurs.
public static void StopService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
Service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch
{
// ...
}
}
Restart service
This method combinates both previous methods. It tries to stop the service (and waits until it's stopped) then it begins to start the service (and waits until the service is running). The specified timeout is used for both operations together.
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
resource from http://www.csharp-examples.net/


Read more!!!

Tuesday, October 7, 2008

Get List of Windows Services in C#

This example shows how to get list of windows services installed on local computer.

Get list of installed windows services
To get list of all services (which are not device drivers) use static method ServiceContro­ller.GetServi­ces (to get list of driver services use method ServiceContro­ller.GetDevices).
ServiceController[] services = ServiceController.GetServices();
Check whether a service is installed
The following code checks whether a service is installed on local computer. It gets list of windows services and tries to find a service with the specified name.
public static bool IsServiceInstalled(string serviceName)
{
// get list of Windows services
ServiceController[] services = ServiceController.GetServices();
// try to find service name
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName)
return true;
}
return false;
}
resource from http://www.csharp-examples.net


Read more!!!

New C# 3.0 Language Features

Automatic Properties, Object Initializers, and Collection Initializers

C# 3 introduces a whole host of new time-saving features to help developers in every day scenarios - once you're using them, you really won't want to go back! We've republished a series of blog posts by Scott Guthrie here (with permission) to give you the low-down. Scott's blog is an awesome resource and well worth checking out for the latest stuff coming out of the Microsoft camp [--Ed]

New C# Language Feature: Automatic Properties

If you are a C# developer today, you are probably quite used to writing classes with basic properties like the code-snippet below:

public class Person
{

private string _firstName;
private string _lastName;
private int _age;

public string FirstName
{

get
{
return _firstName;
}
set
{
_firstName = value;
}
}

public string LastName
{

get
{
return _lastName;
}
set
{
_lastName = value;
}
}

public int Age
{

get
{
return _age;
}
set
{
_age = value;
}
}
}

Note about that we aren't actually adding any logic in the getters/setters of our properties - instead we just get/set the value directly to a field. This begs the question - then why not just use fields instead of properties? Well - there are a lot of downsides to exposing public fields. Two of the big problems are: 1) you can't easily databind against fields, and 2) if you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters) without recompiling any assemblies compiled against the old class.

The new C# compiler that ships in "Orcas" provides an elegant way to make your code more concise while still retaining the flexibility of properties using a new language feature called "automatic properties". Automatic properties allow you to avoid having to manually declare a private field and write the get/set logic -- instead the compiler can automate creating the private field and the default get/set operations for you.

For example, using automatic properties I can now re-write the code above to just be:

public class Person {
public string FirstName {
get; set;
}

public string LastName {
get; set;
}

public int Age {
get; set;
}
}

Or If I want to be really terse, I can collapse the whitespace even further like so:

public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

When the C# "Orcas" compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for you within your class, and implement a public getter and setter property implementation to it. The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our first (more verbose) implementation above. This means that -- unlike public fields -- I can in the future add validation logic within my property setter implementation without having to change any external component that references my class.

Bart De Smet has a great write-up on what happens under the covers when using automatic properties with the March CTP release of "Orcas". You can read his excellent blog post on it here.

New C# and VB Language Feature: Object Initializers

Types within the .NET Framework rely heavily on the use of properties. When instantiating and using new classes, it is very common to write code like below:

Person person = new Person();
person.FirstName = "Scott";
person.LastName = "Guthrie";
person.Age = 32;

Have you ever wanted to make this more concise (and maybe fit on one line)? With the C# and VB "Orcas" compilers you can now take advantage of a great "syntactic sugar" language feature called "object Initializers" that allows you to-do this and re-write the above code like so:

Person person = new Person { FirstName="Scott", LastName="Guthrie", Age=32 }; 

The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.

In addition to setting simple property values when initializing a type, the object initializer feature allows us to optionally set more complex nested property types. For example, assume each Person type we defined above also has a property called "Address" of type "Address". We could then write the below code to create a new "Person" object and set its properties like so:

Person person = new Person {
FirstName = "Scott",
LastName = "Guthrie"
Age = 32,
Address = new Address {
Street = "One Microsoft Way",
City = "Redmond",
State = "WA",
Zip = 98052
}
};

Bart De Smet again has a great write-up on what happens under the covers when using object initializers with the March CTP release of "Orcas". You can read his excellent post on it here.

New C# and VB Language Feature: Collection Initializers

Object Initializers are great, and make it much easier to concisely add objects to collections. For example, if I wanted to add three people to a generics-based List collection of type "Person", I could write the below code:

List people = new List();
people.Add( new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 } );
people.Add( new Person { FirstName = "Bill", LastName = "Gates", Age = 50 } );
people.Add( new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 } );

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what I'd need to type with the C# 2.0 compiler.

The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes:

List people = new List {
new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 },
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
};

When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.

Summary:

As developers we now have a much more concise way to define objects, initialize them, and add them to collections. At runtime, the semantics will be exactly the same as with today's longer syntax (so you don't need to worry about behavior changes). But now you don't need to type as much, and your code can be more crisp and concise.

You can find the original blog post here, or read on for the rest of the features.

resource from http://www.developerfusion.com/


Read more!!!

Monday, October 6, 2008

Introducing Visual Studio .NET 2008 - Top 10 Features

After a long beta period Microsoft pushed Visual Studio .NET 2008 (code named “Orcas”) out to MSDN in November - keeping their promise to deliver it by the end of the year. DevelopMentor has been using Orcas in many of our .NET classes for a while now and I for one, am pretty excited that it’s finally here. There are a ton of new features and enhancements in this release that make it almost a no-brainer to upgrade - I thought I’d take a moment and list my top ten favorites in no particular order:

#10: WPF designer (“Cider”)

I spend a lot of time on a rich-client island and compared to the embarrassing support for WPF provided for VS2005 (through an add-on) VS2008 just plain rocks. Not only does the designer just work, the XAML intellisense is full featured and driven through a real XAML parser and not an XSD file. That means custom types and namespace completion actually function as you would expect them to! The visual designer and XAML views stay synchronized and “mini” thumbnails and scaling bars are used to help you see what you are building. You can also see how the new Cider environment has borrowed from Blend - a Search box is present to filter properties down and the selection in the XAML pane is synchronized with the visual designer so if you highlight a tag, it selects the appropriate object in the visual pane.

WPF Designer

#9: WPF and Windows Forms integration (“Crossbow”)

Hand in hand with the designer view, VS2008 improves the designer experience for Windows Forms to WPF integration. Specifically, ElementHost is now present in the toolbox and you can drag and drop WPF user controls right onto your Form! You get a live preview of the control and can edit the content right in the designer.

WPF Designer

#8: ClickOnce improvements

Microsoft introduced a simplified way to deploy Windows Forms clients from the web with Visual Studio 2005 called ClickOnce. With 2008, they’ve improved the experience by allowing deployment through FireFox (previously only IE was supported), better file associations so your application can be launched by activating a data file, better support for certificate expiration and changing the deployment location without resigning the application and support for Office add-ins and WPF XAML Browser application deployment.

#7: Multi-framework targeting

This release of Visual Studio has a much-needed feature that I wish had been there before - the ability to target multiple versions of .NET. Specifically, you can select your target framework (2.0 SP1, 3.0 or 3.5) and the project types, toolbox, references, intellisense and features will be appropriately set to that version. This selection can occur during project creation - in the project templates dialog or on the project properties dialog. Be aware that selecting .NET Framework 2.0 actually means 2.0 SP1 and not the original .NET 2.0 framework released with Visual Studio 2005.

Multi-framework targeting

#6: Better Intellisense support

Web developers benefit from this release too - Visual Studio now has intellisense and code completion support for JavaScript! It’s smart enough to look at the underlying type currently assigned and correctly infer the methods which are available. So, for example if you assign a numeric type, the dropdown will be populated with the proper methods available for the type.

Visual Studio will also look at the comments applied to your methods - just like in C# and VB.NET, it will pull descriptions out of XML based comments on your JavaScript methods and display descriptions as tooltips when you are navigating the intellisen se dropdown.

Another cool feature added to intellisense is the filtering applied - now if you press a letter and start typing, it will begin to restrict your choices displayed, not just scroll to that section. This filters the output and makes it easier to find what you are looking for.

Intellisense support

#5: Organize your "using" statements

Visual Studio now has the ability to organize your using statements. As a project evolves, you often end up with a ton of using statements at the top of each file which are not really being used - either because the project template added it, or because you originally did use something from that namespace which was then removed later. Now you can right click on your using statements and sort and/or remove unused namespaces.

Using statements

#4: Refactoring enhancements

The refactoring support was a welcome addition to VS 2005 - and Microsoft has enhanced the support in 2008 to support C# 3.0 features and allow you to refactor anonymous types, extension methods and lambda expressions.

#3: C# 3.0 support

Speaking of C# 3.0, that has got to be one of the coolest features - functional programming seems to be all the rage these days and introducing these features into C# 3.0 will allow you to be the coolest programmer on your floor. Things like automatic properties, lambda expressions (which reduce your typing for anonymous delegates), partial methods, anonymous types and extension methods will radically change how you can build applications. They can seem weird at first for some people, but don’t be afraid of them! They will cut down your typing and provide for some really cool ways to enhance and evolve your projects.

#2: Visual Studio Split View

It is becoming increasingly more common to have multiple monitors on developers desks. Building on the “split” window feature of VS 2005, Visual Studio 2008 now allows you to tile the window horizontally or vertically so you can split your design and code view across monitors! This works in any of the designers (ASP.NET, WinForms, WPF, etc.)

Split view

#1: Debugging the .NET source code

There are actually several debugging enhancements (try debugging JavaScript on the client-side for example - it works great!) but I think the coolest feature by far has got to be the debugging enhancements which will allow you to actually debug into the source code of the .NET framework. Scott Guthrie announced a few weeks ago on his blog that they intend to release the source code under the Microsoft Reference License. As part of that release, VS2008 will have integrated debugging support so that you can step into the framework libraries (ever want to know why your DataBind isn’t working??). Visual Studio will automatically download the source file from Microsoft’s server and you will get full watch and breakpoint support. This isn’t quite ready yet, but it’s coming soon and promises to be one of the biggest timesavers added to Visual Studio!

There are a ton of other features that make VS 2008 a worthwhile upgrade - you can experience it yourself by downloading a copy at no cost today Scott Guthrie's Blog (Express editions have been released) or upgrading from MSDN. VS 2008 co-exists just fine with 2005 and 2003 but be aware that the project format has changed and it’s not backwards compatible, so sharing projects with your coworkers may be slightly painful for you until everyone moves to the new release as you will have to maintain two project and solution files.

resource from http://www.developerfusion.com/


Read more!!!

Database Access in C#

Comparing Database Drivers
Database drivers such as JDBC or ODBC can be used to access data in Java and C#. The Java Database Connectivity (JDBC) driver is used from a program written in Java. Open Database Connectivity (ODBC) is Microsoft's database programming interface for accessing a variety of relational databases on a number of platforms. There is also a JDBC-ODBC bridge standard on both the Solaris and Windows versions of the Java platform so you can also use ODBC from a Java program.

In C#, using the .NET Framework, you do not have to load ODBC or JDBC drivers in order to access the database. Simply set the connection string for the database connection object, as follows:
static string connectionString = "Initial Catalog=northwind;Data Source=(local);Integrated Security=SSPI;";
static SqlConnection cn = new SqlConnection(connectionString);

C# Read Database Example

In C#, using the .NET Framework, accessing data is further simplified through the set of classes provided by ADO.NET, which supports database access using ODBC drivers as well as through OLE DB providers. C# applications can interact with SQL databases for reading, writing, and searching data using.NET Framework's ADO.NET classes, and through a Microsoft Data Access Component (MDAC). The .NET Framework's System.Data.SqlClient namespace and classes make accessing SQL server databases easier.

In C#, to perform a database read operation, you can use a connection, a command, and a data table. For example, to connect to a SQL Server database using the System.Data.SqlClient namespace, you can use the following:

The .NET Framework provides the DataAdapter, which brings these three objects together, as follows:

  • The SqlConnection object is set using the DataAdapter object's connection property.

  • The query to execute is specified using the DataAdapter's SelectCommand property.

  • The DataTable object is created using the Fill method of the DataAdapter object. The DataTable object contains the result set data returned by the query. You can iterate through the DataTable object to access the data rows using rows collection.

To compile and run the code, you need the following; otherwise, the line databaseConnection.Open(); fails and throws an exception.

  • Microsoft Data Access Components (MDAC) version 2.7 or later.

    If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using Microsoft Windows 2000, you may need to upgrade the MDAC already installed on your computer. For more information, see MDAC Installation.

  • Access to the SQL Server Northwind database and integrated security privileges for the current user name running the code on a local SQL Server with the Northwind sample database installed.


// Sample C# code accessing a sample database


// You need:
// A database connection
// A command to execute
// A data adapter that understands SQL databases
// A table to hold the result set

namespace DataAccess
{
using System.Data;
using System.Data.SqlClient;

class DataAccess
{
//This is your database connection:
static string connectionString = "Initial Catalog=northwind;Data Source=(local);Integrated Security=SSPI;";
static SqlConnection cn = new SqlConnection(connectionString);

// This is your command to execute:
static string sCommand = "SELECT TOP 10 Lastname FROM Employees ORDER BY EmployeeID";

// This is your data adapter that understands SQL databases:
static SqlDataAdapter da = new SqlDataAdapter(sCommand, cn);

// This is your table to hold the result set:
static DataTable dataTable = new DataTable();

static void Main()
{
try
{
cn.Open();

// Fill the data table with select statement's query results:
int recordsAffected = da.Fill(dataTable);

if (recordsAffected > 0)
{
foreach (DataRow dr in dataTable.Rows)
{
System.Console.WriteLine(dr[0]);
}
}
}
catch (SqlException e)
{
string msg = "";
for (int i=0; i < e.Errors.Count; i++)
{
msg += "Error #" + i + " Message: " + e.Errors[i].Message + "\n";
}
System.Console.WriteLine(msg);
}
finally
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
}
}
}
}
}



Read more!!!

Sunday, October 5, 2008

Database Connectivity in C#: Sql Database

Introduction

ADO.NET deals with accessing Databases. ItÕs a new technology that runs
within the .NET environment. It uses the concept of managed code. ADO.NET provides
access to data sources such as Microsoft SQL Server, OLE DB and XML. Applications
connect to these data sources to access, manipulate or update data. Our article
deals with Microsoft SQL server.


Writing into the database
1. Prepare the connection string, say myConnStr, which would contain the relevant
information about the data store. An example would be:

String myConnStr;
myConnStr= "User ID=sa; Initial Catalog=Northwind;" +"Data Source=mySqlServer;Password=;";

Be sure to substitute your user id, Sql Server name and password appropriately.

2. Instantiate a Connection object, say myConn as

SQLConnection myConn = new SQLConnection(myConnStr);


3. Prepare the SQL string that will be used to extract necessary data from
the data store, for example:

String mySql;
// build the sql query string
mySql = "Insert into Product values(12,"wheat",20)";

4. Instantiate a Command object by passing the connection object and the SQL
string as follows:

SQLCommand myCmd = new SQLCommand(mySql, myConn);

5. Open the Connection, as myConn.Open();

6. The final step is to execute the command with:

myCmd.ExecuteNonQuery()
DataReader - Reading from the database

The ADODataReader (or its twin SQLDataReader) fetches rows of data in streams.
It provides forward-only data streams. The DataReader object cannot be instantiated
directly. In order to create a DataReader object, we need a Command object.
To execute a Command, we require a Connection object.


Creating A DataReader Object:
The following steps are necessary to create a DataReader object.

1. Prepare the connection string, say myConnStr, which would contain the relevant
information about the data store. An example would be:

String myConnStr;
myConnStr= "User ID=sa; Initial Catalog=Northwind;" + "Data Source=mySqlServer;Password=;";

Be sure to substitute your user id, Sql Server name and password appropriately.

2. Instantiate a Connection object, say myConn as

SQLConnection myConn = new SQLConnection(myConnStr);

3. Prepare the SQL string that will be used to extract necessary data from
the data store, for example:

String mySql;
// build the sql query string
mySql = "SELECT ProductId, ProductName, UnitPrice " + "FROM Products WHERE UnitPrice > 55.00";

4. Instantiate a Command object by passing the connection object and the SQL
string as follows:

SQLCommand myCmd = new SQLCommand(mySql, myConn);

5. Open the Connection, as myConn.Open();

6. Define a reference to a DataReader object, such as

DataReader myDataReader

7. Execute the command object by passing the DataReader object’s reference,
for example,

myCmd.execute(out myDataReader);


Retrieving Data From a DataReader
After step 7 is executed, the DataReader object will be instantiated. An imaginary
cursor will be located at the top of the retrieved rows (above the first row),
and we will have to apply the DataReader.Read() method to get to the first row.

Once the cursor is located on a row, we may retrieve the values of columns
of the row by their names or ordinal positions. For example, to retrieve the
first column’s data from the current row, we may use myDataReader.GetInt32(0).
Alternatively, we may also use the name of the column, such as myDataReader["productId"].
Without further delay, we will get into an example.


Example 1.
using System.Data.SQLClient;

public class CreateDataReader
{
public static void Main()
{

String mySql;
String myConnStr;
SQLDataReader myDataReader;

// build the connection string
myConnStr = "User ID=yourUserId; Initial Catalog = northwind;" + "Data Source=YouSqlServerName;Password=yourPassword";

// build the sql query string
mySql = "SELECT ProductId, ProductName, unitprice " + "FROM Products WHERE UnitPrice > 55.00";

// instantiate the Connection and Command object
SQLConnection myConn = new SQLConnection(myConnStr);
SQLCommand myCmd = new SQLCommand(mySql, myConn);

try
{

myConn.Open();
Console.WriteLine("Opened the Connection");
myCmd.Execute(out myDataReader);
Console.WriteLine("Executed the Command, DataReader Instantiated");
Console.WriteLine();

while (myDataReader.Read())
{
Console.Write(myDataReader.GetInt32(0) + " : " +
// Same as Console.Write(myDataReader["productId"] + " : "
+
myDataReader.GetString(1) + " : " +
myDataReader.GetDecimal(2).ToString());
Console.WriteLine();
}

Console.WriteLine();
myDataReader.Close();

Console.WriteLine("DataReader Closed");
myConn.Close();
Console.WriteLine("Connection closed");
}

catch(Exception myException)
{
Console.WriteLine ("The following bad thing happened");
Console.WriteLine(myException.ToString());
}
}
}

Alternate Method - Uses Dataadap

//Connecting database
con = new SqlConnection("Data Source=mysource;Initial Catalog=mydbname;uid=sa");

//create sql adapter for the "emp" table
SqlDataAdapter sqlDa = new SqlDataAdapter("select * from emp", con);

//create dataset instance
DataSet dSet = new DataSet();

//fill the dataset
sqlDa.Fill(dSet, "emp");

//bind the data grid with the data set
dataGrid1.DataSource=dSet.Tables["emp"];

//build select command
SqlCommand selCmd = new SqlCommand("select * from emp",con);
sqlDa.SelectCommand=selCmd;

//build insert command
SqlCommand insCmd = new SqlCommand("insert into emp (Name, Age) values(@Name, @Age)",con);

insCmd.Parameters.Add("@Name", SqlDbType.NChar, 10, "Name");
insCmd.Parameters.Add("@Age", SqlDbType.Int, 4, "Age");
sqlDa.InsertCommand = insCmd;

//build update command
SqlCommand upCmd = new SqlCommand("update emp set Name=@Name, Age=@Age where No=@No",con);

upCmd.Parameters.Add("@Name", SqlDbType.NChar, 10, "Name");
upCmd.Parameters.Add("@Age", SqlDbType.Int, 4, "Age");
upCmd.Parameters.Add("@No", SqlDbType.Int, 4, "No");
sqlDa.UpdateCommand = upCmd;

//build delete command
SqlCommand delCmd = new SqlCommand("delete from emp where No=@No",con);

delCmd.Parameters.Add("@No", SqlDbType.Int, 4, "No");
sqlDa.DeleteCommand = delCmd;

//now update the data adapter with dataset.
sqlDa.Update(dSet,"emp");


Read more!!!

C# example for Beginners - Hello World

The simplest C# program is, of course, Hello World. You will need a C# compiler, which comes as a part of .Net Framework SDK. In your favorite text editor enter the following code:

class Hello
//This program displays Hello World
{
static public void Main()
{
System.Console.WriteLine("Hello World");
}
}

Save this file as myhello.cs and type

csc myhello.cs

If you haven't made any typos, something like:

Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

will appear in your command prompt window. The C# compiler will have created an executable code as a binary file in the PE format named myhello.exe. By simply typing myhello you will see

Hello World

class Hello
//This program displays Hello World
{
static public void Main()
{
System.Console.WriteLine("Hello World");
}
}

What does this simple C# program look like? Java! Note that all methods end with semicolons and Main() method is a part of class Hello. Statements are enclosed in braces. Like in Java and C/C++, every program has a Main() entry point. However, in Java the name of the program should be the same as the name of the class. There is no such restriction in C#.

System.Console is a namespace that takes care of console I/O (see exercise 5). Other methods of System.Console include Write method, which does not add a carriage return at the end of the line, and ReadLine, which gets user input from the console.

As the next step in learning C#, we will write a Windows program that displays "Hello World" dialog:

using System;
using System.Windows.Forms;
class Hello
{
static void Main()
{
MessageBox.Show("Hello World");
}
}

Running this code will produce the following dialog

Hello World dialog


Read more!!!

Saturday, October 4, 2008

Separator Line on Form in C#

This example shows how to create a bevel line in Windows Forms. This line can be used as a visual separator of controls on a form.

Bevel line

To simulate the line in Windows Forms use a Label control. Set its Height to 2 pixels and BorderStyle to Fixed3D. Thats all, see the example.

// separator bevel line
label1.AutoSize = false;
label1.Height = 2;
label1.BorderStyle = BorderStyle.Fixed3D;


resource from http://www.csharp-examples.net/


Read more!!!

Hourglass Cursor in C#

This example demonstrates how to show hourglass in C#.

Hourglass cursor

Mouse cursor displayed over any control in windows forms application is determined by Control.Cursor property. If you want to change the mouse cursor at application level use static property Current of Cursor class. To show hourglass cursor assign value Cursors.WaitCur­sor. To return back the default behavior (to display control specific cursor) assign back value Cursors.Default to the Cursor.Current property. See example below.

// hourglass cursor
Cursor.Current = Cursors.WaitCursor;
try
{
Thread.Sleep(5000); // wait for a while
}
finally
{
Cursor.Current = Cursors.Default;
}

resource from http://www.csharp-examples.net/


Read more!!!

Friday, October 3, 2008

Create New Thread in C#

This example shows how to create a new thread in .NET Framework. First, create a new ThreadStart delegate. The delegate points to a method that will be executed by the new thread. Pass this delegate as a parameter when creating a new Thread instance. Finally, call the Thread.Start method to run your method (in this case WorkThreadFunction) on background.

using System.Threading;

Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();

The WorkThreadFunction could be defined as follows.

public void WorkThreadFunction()
{
try
{
// do any background work
}
catch (Exception ex)
{
// log errors
}
}


resource from http://www.csharp-examples.net/


Read more!!!

Check Local IP Address in C#

This example shows how to detect whether a host name or IP address belongs to local computer.

Get local computer name

Get local computer host name using static method Dns.GetHostName.

string localComputerName = Dns.GetHostName();

Get local IP address list

Get list of computer IP addresses using static method Dns.GetHostAd­dresses. To get list of local IP addresses pass local computer name as a parameter to the method.

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

Check whether an IP address is local

The following method checks if a given host name or IP address is local. First, it gets all IP addresses of the given host, then it gets all IP addresses of the local computer and finally it compares both lists. If any host IP equals to any of local IPs, the host is a local IP. It also checks whether the host is a loopback address (localhost / 127.0.0.1).

public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}

You can test the method for example like this:

IsLocalIpAddress("localhost");        // true (loopback name)
IsLocalIpAddress("127.0.0.1"); // true (loopback IP)
IsLocalIpAddress("MyNotebook"); // true (my computer name)
IsLocalIpAddress("192.168.0.1"); // true (my IP)
IsLocalIpAddress("NonExistingName"); // false (non existing computer name)
IsLocalIpAddress("99.0.0.1"); // false (non existing IP in my net)


resource from http://www.csharp-examples.net/


Read more!!!

Thursday, October 2, 2008

Reflection Examples in C#

This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.

Create instance from assembly that is in your project References

The following examples create instances of DateTime class from the System assembly.

// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));
// create instance of DateTime, use constructor with parameters (year, month, day)
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime), new object[] { 2008, 7, 4 });

Create instance from dynamically loaded assembly

All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.

namespace Test
{
public class Calculator
{
public Calculator() { ... }
private double _number;
public double Number { get { ... } set { ... } }
public void Clear() { ... }
private void DoClear() { ... }
public double Add(class="keyword">double number) { ... }
public static double Pi { ... }
public static double GetPi() { ... }
}
}

Examples of using reflection to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).

// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");
// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");
// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);
// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");
// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);
// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);
// get info about static property: public static double Pi
PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");
// get value of static property: public static double Pi
double piValue = (double)piPropertyInfo.GetValue(null, null);
// invoke public instance method: public void Clear()
calcType.InvokeMember("Clear",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, calcInstance, null);
// invoke private instance method: private void DoClear()
calcType.InvokeMember("DoClear",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
null, calcInstance, null)
// invoke public instance method: public double Add(double number)
double value = (double)calcType.InvokeMember("Add",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, calcInstance, new object[] { 20.0 });
// invoke public static method: public static double GetPi()
double piValue = (double)calcType.InvokeMember("GetPi",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
null, null, null);
// get value of private field: private double _number
double value = (double)calcType.InvokeMember("_number",
BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
null, calcInstance, null);

resource from http://www.csharp-examples.net/


Read more!!!

Get Application Directory in C#

Following examples show how to get application or assembly folder.

Directory of windows forms application (.exe)

Class Application in System.Window­s.Forms namespace has static property ExecutablePath. It contains path of the .exe file (that started the application) including the executable file name. To get only the folder part of the path, use static method GetDirectoryName of Path class.

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

Directory of any loaded assembly (.exe or .dll)

First get reference to the assembly. You can use static methods of Assembly class. To get assembly of currently executing code use method Assembly.GetE­xecutingAssem­bly. To get assembly in which the specified class is defined use method Assembly.GetAs­sembly (with the specified class type as a paramater). The assembly must be loaded. Next get assembly file path using Assembly.CodeBase property.

using System.IO;
using System.Reflection;

string path = Path.GetDirectoryName(
Assembly.GetAssembly(typeof(MyClass)).CodeBase);

resource from http://www.csharp-examples.net/


Read more!!!

Wednesday, October 1, 2008

Load Text from File to String in C#

This example shows how to load text file to string variable.

StreamReader

To load text from file to string you can use StreamReader.Re­adToEnd method. First create new instance of StreamReader. As a parameter in constructor you can pass string with file path or Stream instance. Default encoding is UTF-8.

using System.IO;

StreamReader streamReader = new StreamReader(filePath);
string text = streamReader.ReadToEnd();
streamReader.Close();

resource from http://www.csharp-examples.


Read more!!!