Monday, December 29, 2008

Check if the Internet Connection State is active inC#

A small application which uploads Images of new products and therefore I had to check if the Internet Connection State is active, otherwise it would crash. There are actually two ways (and probably more) of doing this, depending on your system. You could go with a direct api call:
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

//Creating a function that uses the API function...
public static bool IsConnectedToInternet()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
The Description can be found on MSDN, depending on the Connection the proper Value has to be entered.

Another way would be resolving some host of which you are sure it is online all the time. That could be microsoft.com, your company’s website or something else. Here we go:

public static bool IsConnected()
{
System.Uri Url = new System.Uri("http://www.microsoft.com");

System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);

try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
return true;
}

catch
{
WebReq = null;
return false;
}
}


Read more!!!

How to resize Workarea of desktop in C#

public struct Rect
{
public Int32 Left, Top, Right, Bottom;
}

The code below is that the workarea is reduced by the height of Form and the Form is placed bottom of the workarea. It is like application of Cash Fiesta6

private void button1_Click(object sender, EventArgs e)
{
Rect DeskArea = new Rect();
SystemParametersInfo(48/*SPI_GETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
this.Left = 0;
this.Width = DeskArea.Right;
this.Top = DeskArea.Bottom - this.Height - 4;
DeskArea.Bottom = DeskArea.Bottom - 150;
SystemParametersInfo(47/*SPI_SETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
}

And now you need to replace the orkarea to its original size.

private void button2_Click(object sender, EventArgs e)
{
Rect DeskArea = new Rect();
SystemParametersInfo(48/*SPI_GETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
DeskArea.Bottom = DeskArea.Bottom + 150;
SystemParametersInfo(47/*SPI_SETWORKAREA*/, 0, ref DeskArea, 2/*SPIF_SENDCHANGE*/);
}


Read more!!!

Friday, December 26, 2008

Hiding application from taskbar in C#

public class Taskbar
{
[DllImport( "user32.dll" )]
private static extern int FindWindow( string className, string windowText );
[DllImport( "user32.dll" )]
private static extern int ShowWindow( int hwnd, int command );

private const int SW_HIDE = 0;
private const int SW_SHOW = 1;

protected static int Handle
{
get
{
return FindWindow( "Shell_TrayWnd", "" );
}
}

private Taskbar()
{
// hide ctor
}

public static void Show()
{
ShowWindow( Handle, SW_SHOW );
}

public static void Hide()
{
ShowWindow( Handle, SW_HIDE );
}
}
Another very easy way:
this.ShowInTaskbar = false;


Read more!!!

Hiding titlebar /caption/ of Form in C#

It is very easy as below

this.Text = String.Empty;
this.ControlBox = false;


Read more!!!

Saturday, December 20, 2008

Another resource for Multithreading in C#

Introduction:

In this article let us see about multithreading. Multithreaded applications provide the illusion that numerous activities are happening at more or less the same time. In C# the System.Threading namespace provides a number of types that enable multithreaded programming.

Threading in C#

System.Threading Namespace

The System.Threading Namespace provides a number of types that enable multi-threading programming. In addition to providing types that represent a particular thread, this namespace also describe types that can handle a collection of threads (Thread Pool), a simple (Non -GUI based) Timer class and several types to provide synchronized access to shared data.

The most primitive of all types in the System.Threading namespace is Thread. Thread:

Represents a thread that executes with in the CLR. Using this type, one can able to spawn additional threads in the owning AppDomain.This type defines a number of methods (both static and shared) that allow us to create new threads from a current thread, as well as suspend, stop, and destroy a given thread.

The following example will demonstrate Spawning of Secondary threads using C#.

internal class EmployeeClass
{
public void Performjob()
{

// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i=0;i<10;i++)
{
Console.write(i +",");
}
console.writeline();
}
}
The above code simply prints out a series of numbers by way of the performjob() member function.

Now assume that a class (Main class) creates a new instance of EmployeeClass. In order for the Main class to continue processing its workflow, it creates and starts a new thread that is used by the job. In the code below, notice that Thread type requests a new Threadstart delegate type:

Public class Mainclass
{
public static int Main (string[] args)
{
Console.Writeline("ID of primary thread is {0}",
Thread.CurrentTHread.GetHashCode() );

// Make Employee class.

EmployeeClass j = new EmployeeClass();

// Now make and start the background thread.

Thread backgroundThread =
new Thread(new ThreadStart(j.Performjob));
backgroundThread.Start();
return 0;
}
}
If we run the application we would find the following result.
ID of primary thread is: 2
ID of Employee thread is: 11
Employee says: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Press any key to continue
From the above example one can easily know how to spawning the secondary Threads.

Let us see another example regarding two active threads.

internal class EmployeeClass
{
public void Performjob()
{
// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i = 0; i < 20000 ; i++)
{
Console.write(i +",");
}
console.writeline();
}
}

Public class Mainclass
{
public static int Main (string[] args)
{
// Make Employee class
............
//Now make the thread.
............
//Now while background thread is working
//do some additional work.
MessageBox.show("BUSY");
return(0);
}
}
If we run this application we would see that the message box is displayed and it can be moved around the desktop, while the background Employee thread is busy pumping numbers to the console.

Thread Synchronization:

A multithreaded application usually has resources that can be accessed from multiple threads; for example, a global variable that is incremented or decremented by multiple threads. It is sometimes desirable to prevent multiple threads from concurrently altering the state of a resource. The .NET Framework includes several classes and data types that we can use to synchronize actions performed by two threads.

The simplest case is if we have a shared variable that we need to update from different threads. To do this, we can use the System.Threading.Interlocked class. For example, to increment or decrement the shared variable called num, we'd write Interlocked.Increment(num) or Interlocked.Decrement(num). we can also use Interlocked to set the variables to a specific value or to check the equality of two variables.

If there's a section of code in an object's method that should not be accessed concurrently by multiple threads, we can use the Monitor class to acquire a lock on that object by calling Monitor.Enter(object). Any other thread wanting to execute the same code would need to acquire the same lock and will be paused until the first thread releases the lock by calling Monitor. Exit(object).

For more control over thread synchronization or for cross-process synchronization, use the Mutex class, which is a named synchronization object that can be obtained from any thread in any process. Once we create or obtain the mutex, we use its GetHandle method to (as we'd expect) get a handle that we can use with the WaitHandle.WaitAny or WaitHandle.WaitAll methods. These two methods are blocking and will return only if the specified handle is signaled (that is, the mutex is not being used by another thread) or if the specified timeout expires. After we obtain the mutex, we perform the necessary synchronized processing and then call Mutex.ReleaseMutex to release it.

Sometimes we need a mechanism for one thread to notify other threads of some interesting event that occurred. In those cases we can use the .NET synchronization event classes, ManualResetEvent and AutoResetEvent. In the world of thread synchronization, an event is an object that has two states: signaled and nonsignaled. An event has a handle and can be used with WaitHandle just like a mutex. A thread that waits for an event will be blocked until another thread signals the event by calling ManualResetEvent.Set or AutoResetEvent.Set. If we are using a ManualResetEvent, we must call its Reset method to put it back to the nonsignaled state. An AutoResetEvent will automatically go back to nonsignaled as soon as a waiting thread is notified that the event became signaled.

Conclusion:

That's all it takes to create a multi-threaded application in C#.The System.Threading namespace in .NET SDK makes multi-threading easy.The System.Threading Namespace provides a number of types that enable multi-threading programming easily in C#. The Thread class in the System.Threading namespace exposes the properties and methods to allow the free threading.


Read more!!!

Multithreading in C#

Any Windows application must have one or more processes. A Process is structural unit with a memory block and using some set of resources. For each executable, the Windows operating system creates some isolated memory block. This C# .Net Tutorial tries to explain the basics of Multithreading in C# .Net.

Every process must have at least one thread. The first thread is created with a process and is known as primary thread. This Primary Thread is entry point of application. In traditional Windows applications it is the method WinMain() and in console applications it is named main().

Main goal of creating multithreading application is performance improvement. As an example, imagine a situation where in a user starts a long process (e.g. copying), he can?t use a single threaded application and wait for an infinite time for the operation to get completed. But if he uses multi?threading application he can set copying process in the background and interact with application without any problems.

At first, if one wants to create a multi-threaded application an important point to be remembered is, a global variable, which is being accessed by different threads, can try to modify the same variable. This is a generic problem, which is solved using a mechanism called Synchronization of threads. Synchronization is nothing but the process of creating some set of rules to operate data or resources.

The C# .Net language has a powerful namespace which can be used for programming with Threads as well as Thread Synchronization in C# .Net programming. The name of the namespace is Sytem.Threading. The most important class inside this namespace for manipulating the threads is the C# .Net class Thread. It can run other thread in our application process.

Sample program on C# Multithreading - C# Tutorial:

The example it creates an additional C# .Net class Launcher. It has only one method, which output countdown in the console.

//Sample for C# tutorial on Multithreading using lock

public void Coundown()
{

lock(this)
{

for(int i=4;i>=0;i--)
{

Console.WriteLine("{0} seconds to start",i);

}

Console.WriteLine("GO!!!!!");

}

}

There is a new keyword lock inside the above chunk of .Net C# tutorial code. This provides a mechanism for synchronizing the thread operation. It means at the same point of time only one thread can access to this method of created object. Unless the lock is released after completion of the code, the next routine or iteration cannot enter the block.

To understand it more clearly please have a look at the piece of main method?s code:

Launcher la = new Launcher();

Thread firstThread = new Thread(new ThreadStart(la.Coundown));
Thread secondThread =new Thread(new ThreadStart(la.Coundown));
Thread thirdThread = new Thread(new ThreadStart(la.Coundown));

firstThread.Start();
secondThread.Start();
thirdThread.Start();

As you see there were created three additional threads. These threads start a method of object that has Launcher type. The above program is a very simple example of using multi-threading in C#. Net. But C# .Net allows us to create more powerful applications with any level of complexity.

At last a few words about attached example. It can be compiled using Microsoft .NET command line. Just type csc filename.cs. After it CSC compiler creates an executable version of your code, since it can be run as standard exe file.


Read more!!!

Saturday, November 1, 2008

Setting up Red Hat Linux as a Router

There are several different ways to set up routing from your LAN to the Internet. You can have a dedicated router or you can have a computer already connected to your LAN that will act as a router. This section describes how to use your Red Hat Linux computer as a router.

A computer may have several network interfaces, such as a loopback, an Ethernet LAN, a direct line to another computer, or a dial-up interface. For a client computer to use a router to reach the Internet, it may have private IP addresses assigned to computers on the LAN, while the connection to a routing computer would act as the gateway to all other addresses.

Here's an example of Red Hat Linux being used as a router between a LAN and the Internet:

  • The Red Hat Linux system has at least two network interfaces: one to the office LAN and one to the Internet. The interface to the Internet may be a dial-up PPP connection or a higher-speed DSL or cable modem connection.

  • Packets on the LAN that are not addressed to a known computer on the LAN are forwarded to the router (that is, the Red Hat Linux system acting as a router). So, each client identifies that Red Hat Linux system as the gateway system.

  • The Red Hat Linux "router" firewall is set up to receive packets from the local LAN, then forwards those packets to its other interface (possibly a PPP connection to the Internet). If the LAN uses private IP addresses, the firewall is also configured to use IP masquerading or Network Address Translation.

The following sections describe how to set up the Red Hat Linux router, as well as the client computers from your LAN (Red Hat Linux and MS Windows clients) that will use this router. Using Red Hat Linux as a router also provides an excellent opportunity to improve the security of your Internet connection by setting up a firewall to filter traffic and hide the identity of the computers on your LAN (IP masquerading).

Configuring the Red Hat Linux router

To configure your Red Hat Linux computer as a router, you need to have a few things in place. Here's what you need to do before you set up routing:

  • Connect to your LAN. Add a network card and optionally set up the addresses in /etc/hosts to the computers on your LAN or using DHCP.

  • Connect to the Internet. Set up a dial-up or other type of connection from your Red Hat Linux computer to your ISP. This is described earlier in this chapter in the section on setting up outgoing PPP connections.

  • Configure your Red Hat Linux computer as a router. See the rest of this section.

The type of IP addresses you are using on your LAN will have an impact on a couple of steps in this procedure. Here are the differences:

  • Private IP addresses — If the computers on your LAN use private IP addresses, you need to set up Linux as a firewall to do IP masquerading or NAT. Because those numbers are private, they must be hidden from the Internet when the Red Hat Linux router forwards their requests. Packets forwarded with masquerading or NAT look to the outside world as though they came from the Red Hat Linux computer forwarding the packets.

  • Valid IP addresses — If your LAN uses addresses that were officially assigned by your ISP or other registration authority, you don't need to do IP masquerading or NAT.

Enable forwarding and masquerading

With your Red Hat Linux computer's LAN and Internet interfaces in place, follow the procedure below to set up Red Hat Linux as a router. Once this procedure is completed, any client computer on your LAN can identify your Red Hat Linux computer as its gateway so it can use Red Hat Linux to get to the Internet.

  1. Open the /etc/sysconfig/network file in a text editor as the root user. Then add either a default gateway or default gateway device as described below.

    Your default gateway is where IP addresses are sought that are not on any of your local interfaces. This is where you would identify your Internet connection. Here is how you choose which one to enter:

    • Default Gateway — If there is a static IP address you use to reach the Internet, enter that IP address here. For example, if your Internet connection went through a DSL modem connected to your NIC card at address 192.168.0.1, you would enter that address as follows:

      GATEWAY=192.168.0.1
    • Default Gateway Device — If you reach the Internet using a dynamic address that is assigned when you connect to a particular interface, you would enter that interface here. For example, if you had a dial-up interface to the Internet on the first PPP device, you would enter ppp0 as the default gateway device as follows:

      GATEWAYDEV=ppp0

    When you are done, the contents of this file should look similar to the following:

    NETWORKING=yes
    HOSTNAME='maple.handsonhistory.com'
    DOMAINNAME='handsonhistory.com'
    #GATEWAY=
    GATEWAYDEV=ppp0

    In this case, the computer is configured to route packets over a dial-up connection to the Internet (ppp0).

  2. Turn on IP packet forwarding. One way to do this is to change the value of net.ipv4.ip_forward to 1 in the /etc/sysctl.conf file. Open that file as root user with any text editor and change the line to appear as follows:

    net.ipv4.ip_forward = 1
  3. If the computers on your LAN have valid IP addresses, skip ahead to the section on configuring Red Hat Linux routing clients. If your computers have private IP addresses, continue with this procedure.


    Caution

    The lines shown below for configuring your iptables or ipchains firewall to do IP masquerading should be used in addition to your other firewall rules. They do not, in themselves, represent a secure firewall, but merely describe how to add masquerading to your firewall.

  4. To get IP masquerading going on your Red Hat Linux router, you need to define which addresses will be masqueraded and forwarded. The procedure is different, depending on whether you are using ipchains or iptables for your firewall.


    Tip

    If you are not sure which, if any, firewall is configured for your computer, type iptables -L and ipchains -L. The resulting output will display firewall rules for the one that is working and an "Incompatible with this kernel" message for the one that is not. In the current Red Hat Linux version, iptables is the default firewall.

    The following examples assume that you are masquerading all computers on your private LAN 10.0.0 (i.e. 10.0.0.1, 10.0.0.2, etc.) and routing packets from that LAN to the Internet over your dial-up (ppp0) interface.

    • For iptables, type the following as root user:

      # iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
      # iptables -A FORWARD -s 10.0.0.0/24 -j ACCEPT
      # iptables -A FORWARD -d 10.0.0.0/24 -j ACCEPT
      # iptables -A FORWARD -s ! 10.0.0.0/24 -j DROP

      The previous commands turn on masquerading in the NAT table by appending a POSTROUTING rule (-A POSTROUTING) for all outgoing packets on the first dial-up PPP interface (-o ppp0). The next two lines accept forwarding for all packets from (-s) and to (-d) the 10.0.0 network (10.0.0.0/24). The last line drops packets that don't come from the 10.0.0 network.

      The above lines add rules to your running iptables firewall in the Linux kernel. To make the current rules permanent, save the current rules as follows:

      # cp /etc/sysconfig/iptables /etc/sysconfig/iptables.old
      # iptables-save > /etc/sysconfig/iptables

      This copies all the current rules to the iptables file, from which the rules are read each time you reboot your system. If the new rules don't work, just copy the iptables.old file back to the original iptables file.

    • For ipchains, add these lines to /etc/sysconfig/ipchains file (key lines in bold):

      :input ACCEPT
      :forward ACCEPT
      -P forward DENY
      -A forward -i ppp0 -s 10.0.0.0/255.255.255.0 -j MASQ
      :output ACCEPT
  5. At this point, you may want to restart your network as follows:

    # /etc/init.d/network restart
  6. Then, depending on which type of firewall you are using, type one of the following:

    # /etc/init.d/iptables restart

    or

    # /etc/init.d/ipchains restart
  7. To see if your new rules have gone into effect, type iptables -L or ipchains -L (again, depending on which firewall you are using). All current rules are displayed.

If the route to the Internet from Linux is being provided by a dial-up connection, you probably want to turn on on-demand dialing (as described earlier in this chapter).

Configuring network clients

In this example, there are a variety of Red Hat Linux and Windows operating system clients on a LAN. One Red Hat Linux computer has a connection to the Internet and is set up to act as a router between the Internet and the other computers on the LAN (as described previously). To be able to reach computers on the Internet, each client must be able to do the following:

  • Resolve the names it requests (for example,) into IP addresses.

  • Find a route from the local system to the remote system, using its network interfaces.

Each Red Hat Linux client computer knows how to find another computer's address based on the contents of the /etc/host.conf, /etc/hosts, and /etc/resolv.conf files. The contents of the host.conf file, by default, is the following:

order hosts,bind

This tells your system to check for any host names (hosts) that you request by first checking the contents of the /etc/hosts file and then checking with name servers that are identified in the /etc/resolv.conf file. In our case, we will put the addresses of the few hosts we know about on our private network (whether on the LAN, direct connection, or other network interface) in the /etc/hosts file. Then, the system knows to resolve addresses using a DNS server (bind) based on addresses of name servers we add to the /etc/resolv.conf file.

Next, each client machine must know how to get to the Internet. Do this by adding a default route (sometimes called a gateway) to each client. To permanently add a default route on the client Red Hat Linux system, do the following:

  1. Set the default route to point to the router. This entails setting the GATEWAY or GATEWAYDEV value in the /etc/sysconfig/network file as described in the previous procedure. (This time, the address will point to the LAN interface of the router.)

  2. Restart your network interfaces by typing the following as root user:

    # /etc/init.d/network restart
  3. When the computer comes back up, type the following:

    # netstat -r
    Kernel IP routing table
    Destination Gateway Genmask Flags MSS Window irtt Iface
    10.0.0.0 * 255.255.255.0 U 0 0 0 eth0
    127.0.0.0 * 255.0.0.0 U 0 0 0 lo
    default 10.0.0.1 0.0.0.0 UG 0 0 0 eth0

You can see that the default gateway was set to the host at the IP address 10.0.0.1 on the eth0 Ethernet interface. Assuming that router is ready to route your packets to the Internet, your Red Hat Linux client is now ready to use that router to find all IP addresses that you request that you do not already know where to find. (The netstat -r command provides the same output as the /sbin/route command.)

Configuring Windows network clients

If you have some Microsoft systems on your LAN, you need to configure them so that they can connect to the Internet through your router. To set up the Windows operating system computers on your private network to access the Internet through your routing computer, you can either set up a DHCP server or add a few pieces of information to each Windows system. Here's how to do this from Windows ME and most other Windows systems:

  1. Choose Start ® Settings ® Control Panel.

  2. Open the Network icon in the Control Panel.

  3. Double-click the interface shown that supports connecting to the Linux router. (For a LAN, it may look like this: TCP/IP ® 3Com EtherLink III.)

  4. Click the IP address tab, and then either leave the "Obtain an IP address automatically" button selected (if you are using DHCP to get the IP address, or select the "Specify an IP address" button (if you intend to add a static IP address). In the second case, you then need to type in the IP address and subnet mask for the host computer.

  5. Click the Gateway tab, type the IP address of your Linux router, and then click Add.

  6. Click the DNS Configuration tab, type in the number of the DNS server that you use to resolve addresses on the Internet, and then click Add. Repeat this step if you have multiple DNS servers.

  7. Click OK.

  8. You may need to reboot your computer at this point, if Windows requires you to do so.

At this point, try accessing a Web site from your Internet browser on the Windows computer. If the Internet connection is up on your Red Hat Linux computer, you should be able to connect to the Internet through your LAN connection to the Red Hat Linux computer.

resource from Redhat Linux Bible


Read more!!!

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