January 1, 2013

Distinct Rows from data table




I love the idea of keeping your data disconnected from your data source; dataset & data-table are a great way to manipulate your records and rows in memory…!!
Now let’s do this trick … getting the “Distinct” records from a data-table …Yes we can do that with one simple step …just pass the required columns to the “ToTable” method in the DefaultView …. as illustrated in the below code sample :


string[] Columns = {"IP","Country-Code"};
DataTable dtData = GetMyDataTableInfo();
DataTable distinctRecords = new DataTable();
distinctRecords = dtData.DefaultView.ToTable(true, Columns);


Please note that “GetMyDataTableInfo” is a method that will fill your data datable …but the impoatant part of these lines is “ToTable” …the second parameters “Columns” array of string contain the names of the columns that we need to accomplish the Distinct operations.


Happy programming ….


December 26, 2012

Import Excel file into Dataset …



In this simple blog I’m going to explain within few steps how we can connect to a MS Excel file and read the first sheet content in a separated dataset…

Right ..this is a very useful strategy …where we really take advantages from this in improving our software’s …


Connect to excel …

We can connect to Excel file in the same way we connect to any other data source such as MSSQLServer …in general all we need is a valid connection-string and connection instance to connect …

Below code sample illustrate a connection-string example to connect Excel file …

string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=Excel 12.0;";

Note that the variable strPath is the actually path for the excel file …now we can use the connection instance to open the connection directly to the excel file…as illustrated below ….

OleDbConnection MyConnection = new OleDbConnection(connStr);


 Import to Dataset …

Below code illustrate how we can read the first sheet in the excel file and fill it into a dataset instance …

// Declarations :
DataTable dtFullData;
OleDbDataAdapter MyAdapter;
OleDbCommand CmdSelect;

// Connect to the excel file :
OleDbConnection MyConnection = new OleDbConnection(connStr);

// Prepare Command :
CmdSelect = new OleDbCommand(@"SELECT * FROM [Sheet1$]", MyConnection);

// Fill DataSet :
dtFullData = new DataTable("ExcelSheet1");
MyAdapter.FillSchema(dtFullData, SchemaType.Source);
MyAdapter.Fill(dtFullData);


From the code above it’s a very simple …all we need is to execute the command in the excel file (such as this command or query SELECT * FROM [Sheet1$] ) and fill the dataset with the result using the adapter …


Hope this help …


March 27, 2012

WMI – Query to get Network Adapter information



It was great day when I discover WMI in .Net framework, many thanks for .Net framework J , you can find everything you need there ….

The story began when I face an issue required me to save some information related to the current machine that run my windows application. Sometimes it’s important to get some information related to the current machine such as the current IP Address, or the current Hostname …may be some processor information too …etc.

In my case it was important to get IP Addresses information to implement some business security on my Windows Application, at this moment I start searching for different techniques to do that …until I found the “WMI” …

Hey… Why don’t ask your windows about the information you need? Yes it’s really like that …or in technical word sends a Query the windows…!!
WMI stand for “Windows Management Instrumentation”, below is a definition I read it from MSD …

“   Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on remote computers but WMI also supplies management data to other parts of the operating system and products, for example System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management    “



In the below example I will show how it was easy to get some of IP information from My PC , first of all you need to the reference “system.managment” to your application since we need to include this reference on our form class ….

Now what’s required is to Query the windows about my Network Adapter Configuration, since the IP come as a part of “Network Adapter” ….

I assume you will build a windows form with listbox control to fill it with the required IP information …

We will use “ManagementObjectSearcher” class to execute our query in windows, note that   “ManagementObjectSearcher” will represent the WMI class …below method will execute a query that ask for enabled IP on the machine , taking in the consideration that the machine was windows -32.


private void ListNetworkInformation()
        {

            // Search on all network-adapters (only enabled) : 
            ManagementObjectSearcher wmiSearch = new ManagementObjectSearcher
                       ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");

            ManagementObjectCollection mgmCollection = wmiSearch.Get();


            foreach (ManagementObject mgmItem in mgmCollection)
            {
                // Get HostName :
                string HostName = mgmItem["DNSHostName"].ToString();
                this.listBox1.Items.Add("DNSHostName : " + HostName);

                // Get Description :
                string Description = mgmItem["Description"].ToString();
                this.listBox1.Items.Add("Description : " + Description);               

                // List IP Addresses :
                string[] IPAddrs = (string[])mgmItem["IPAddress"];
                foreach (string ipAdd in IPAddrs)
                    this.listBox1.Items.Add("IP-Address : [ " + ipAdd + " ]");

                // IPSubnets :
                string[] IPsub = (string[])mgmItem["IPSubnet"];
                if (IPsub != null)
                   foreach (string ipsubnet in IPsub)
                    this.listBox1.Items.Add("IPSubnet : [ " + ipsubnet + " ]");

                // Default IP Gateways
                string[] IPgateways = (string[])mgmItem["DefaultIPGateway"];
                if (IPgateways != null)
                    foreach (string defipgateway in IPgateways)
                      this.listBox1.Items.Add("Default IP Gateway : [ " + defipgateway + " ]");

                this.listBox1.Items.Add("==============================================");
            } 
        }



Calling the above method will get different information such as: HostName, IP Addresses, IP Subnets & IP-Subnets …etc.

As you see we execute this query in windows management (SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'), which a WMI instance ….looping the management collection to get the required item.

Hope this sample help in get an idea about WMI …for more information you can check the MSDN ….

August 13, 2011

Windows Communication Foundation (WCF)

What is WCF? 

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. WCF is implemented primarily as a set of classes on top of the .NET Framework’s Common Language Runtime (CLR).
Why we need WCF?
Imagine that you need to build an application that need to integrate and deal with an environment that contains different kind of applications and platforms for example: java application, .Net windows & web application.
On this case you need to choose the right distributed technology from .Net Framework , and sometimes it need to implement more than one of these technology to accomplish the required integration which will lead in hard and complex solution …
What are the distributed .Net technologies?
o    ASP.NET Web Services & Web Services Enhancements (WSE): this is a good choice to integrate through web with other platforms & technologies such as Java EE-Base.
o    .NET Remoting: Effective when we are communicating between .NET-to-.NET applications.
o    Enterprise Services: this supports only a limited set of communication protocols.
o    System.Messaging:  Allow to communicate with Windows-based partner applications that weren’t always available.
o    System.Net:  communicate with partner applications or perhaps in other ways. Using this approach, developers can create applications that use the HTTP-bas communication style known as Representational State Transfer (REST).
Why WCF?


This why WCF is important and give and optimal solution in cases like these? This because WCF will cover all the holes between these technologies…
In other word WCF can be used for any of the situation, WCF provides a declarative infrastructure for all forms of communication.
Below summarize the points that covered by WCF …




ASMX


.Net Remoting


Enterprise Services


WSE

System. Messaging

System. Net

WCF

Interoperable web service


X






X

.Net to .Net Communication


X




X

Distributed transaction



X



X

Support with WS-* Specifications




X


X

Queued messaging






X

X

RESET Communication






X
X
At the end …
WCF will make the communication process easy and flexible because it supports all the above communications types.
With WCF development time will be minimized because all the development part will lie on the code only (which mainly lead to concentrate on solving the business issues) while anything related to the implementation will be added to the configuration file.