Tuesday, September 25, 2012

Comparison of Execution Time taken by LINQ, FOR loop and FOREACH loop

While developing any kind of web/windows application we come across a point where we are supposed to filter records based on some criteria from bunch of data. And to define logic we may use LINQ query or FOREACH or FOR looping structure without considering the amount of data and execution time for obtaining result set.

Let’s consider that we developing a utility application/business logic which processes data. Below is demo application to check execution time of LINQ queries, FOREACH and FOR loop.

Here I am generating ONE CRORE random numbers between 0 to 100 and adding it to list and calculating occurrences of “20” number from the random number generated list.

static void Main(string[] args)
        {
            //Generating ONE CRORE random numbers
            List<int> data = new List<int>();
            System.Random rnd = new Random();
            for (int i = 0; i <= 10000000; i++)
            {
                data.Add(rnd.Next(100));
            }

            //Filtering by different methods
            Console.WriteLine("Execution time using different methods." + Environment.NewLine);
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            int count = 0;

            //------------------------------------------------
            //Method - 1: Using LINQ Query
            sw.Start();
            
            count = (from d in data
                     where d == 20
                     select d).Count();

            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds + " milliseconds - Using LINQ query");

            sw.Reset();

            //------------------------------------------------
            //Method - 2: Using LINQ lambda expression            
            sw.Start();
            
            count = data.Where(c => c == 20).Count();

            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds + " milliseconds - Using LINQ Lambda expression");

            sw.Reset();            

            //------------------------------------------------
            //Method - 3: Using FOR loop
            count = 0;
            sw.Start();     
       
            for (int i = 0; i < data.Count; i++)            
                if (data[i] == 20)
                    count++;            
            
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds + " milliseconds - Using For loop");

            sw.Reset();  

            //------------------------------------------------
            //Method - 4: Using FOREACH loop
            count = 0;
            sw.Start();

            foreach (var item in data)
                if (item == 20)
                    count++;

            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds + " milliseconds - Using Foreach loop");           
            Console.Read();
        }


In above example we used four different methods to calculate occurrences of number “20” in random number list:
  • Method – 1: Using LINQ query 
  • Method – 2: Using LINQ lambda expression 
  • Method – 3: Using FOR loop 
  • Method – 4: Using FOREACH loop 

And from the above output we can see that LINQ query creates more overhead with compared to looping controls rather FOREACH loop.

Hence, lesser execution time more faster and optimized output.

Learn by diving in Programming Ocean...
Happy Programming!!!

Wednesday, July 18, 2012

String value to ENUM type conversion

Download sample code
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. By using enum you can clearly specify for the client code which values are valid for variable.

Also in some cases we may come across storing the enum value in form of string value, which further needs to be converted to enum type so that business logic remains consistent and error free.

While converting string to enum type we can use Enum.Parse() or Enum.TryParse()independently wherever its required. Now this kills re-usability feature of OOP.

Taking advantage of re-usability I have created generic method which will be accepting string value and expected type of enum in form of template T.

Below is an extension method used to convert string to enum type, however instance methods can be created too.
public static T ToEnum<T>(this string value)
{
      if (string.IsNullOrEmpty(value) && typeof(T).IsEnum)
      {
          bool result = false;
          Enum.TryParse(value, true, out result);

          if (result)
             return (T)Enum.Parse(typeof(T), value, true);
      }

      //This will return default value as 0
      return default(T);
}

In above code T is the template which we are expecting. For demo purpose I have declared two enum types namely Colors and Direction which can be passed as template T.
public enum Colors
{
      RED = 0,
      GREEN = 1,
      BLUE = 2
}

public enum Direction
{
      NORTH,
      EAST,
      WEST,
      SOUTH
}

Invoking enum conversion method.
//Calling ToEnum conversion extension method            
Colors selectedColor = "red".ToEnum<Colors>();

Direction selectedDirection = "North".ToEnum<Direction>();

Thus “red” will be converted to its relevant enum value and stored in the enum type of variable which can be used same as that of normal variable in logic. And if at all specified string is not found in enum, it will return default “0” value.

Here values of variables "selectedColor" and "selectedDirection" would be "Colors.RED" and "Direction.NORTH" respectively.

As per sample application and code output text will be shown in red color.

Learn by diving in Programming Ocean...
Happy Programming!!!

Tuesday, June 5, 2012

Using APPLY Operator

The Apply operator available in SQL Server 2005 onwards is used to invoke a table-valued function for each row returned by an outer table expression of a query. The table-valued function acts as the right input and the outer table expression acts as the left input. The right input is evaluated for each row from the left input and the rows produced are combined for the final output. The list of columns produced by the APPLY operator is the set of columns in the left input followed by the list of columns returned by the right input.

The Apply operator is similar to that of Joins but has no conditions in the query.

There are two forms of Apply operator:
  • Cross Apply
    The CROSS APPLY operator returns rows from the primary (outer) table only if the table-value function produces a result set. It's similar to that of Inner Join or Cross Join.
  • Outer Apply
    The OUTER APPLY, on the other hand, returns all rows from the outer table, even if the function produces no results. Thus, it generates NULL values for those records whose result set is not returned. It's similar to that of Outer Join.

Consider an example below to demonstrate Apply operator:

GO

CREATE TABLE [dbo].[Departments](
 [DepartmentId] [int] NOT NULL PRIMARY KEY,
 [DeparttmentName] [varchar](50) NULL,
);

GO

INSERT INTO [dbo].[Departments] VALUES(1, 'HR')
INSERT INTO [dbo].[Departments] VALUES(2, 'Marketing')
INSERT INTO [dbo].[Departments] VALUES(3, 'Finance')
INSERT INTO [dbo].[Departments] VALUES(4, 'R&D')
INSERT INTO [dbo].[Departments] VALUES(5, 'Training')
INSERT INTO [dbo].[Departments] VALUES(6, 'Gardening')


GO

CREATE TABLE [dbo].[Employees](
 [EmployeeId] [int] NOT NULL PRIMARY KEY,
 [EmployeeName] [varchar](50) NULL,
 [DepartmentId] [int] NULL REFERENCES [dbo].[Departments],
);

GO

INSERT INTO [dbo].[Employees] VALUES(1, 'Jeet', 1)
INSERT INTO [dbo].[Employees] VALUES(2, 'Sagar', 2)
INSERT INTO [dbo].[Employees] VALUES(3, 'Chirag', 2)
INSERT INTO [dbo].[Employees] VALUES(4, 'Jayesh', 3)
INSERT INTO [dbo].[Employees] VALUES(5, 'Ketan', 4)
INSERT INTO [dbo].[Employees] VALUES(6, 'Rikin', 4)
INSERT INTO [dbo].[Employees] VALUES(7, 'Pratik', 6)

GO

In above example we can see list of Departments and Employees related to departments (if any) in appropriate tables respectively.

As mentioned above, Apply operator works with table-values function (also known as TVF), consider the below example of it.
GO
CREATE FUNCTION [dbo].[GetEmployees]
(
 @DepartmentId int 
)
RETURNS 
@ResultSet TABLE 
(
 EmployeeId int,
 EmployeeName varchar(20)
)
AS
BEGIN
 INSERT INTO @ResultSet 
  SELECT EmployeeId,EmployeeName 
  FROM Employees 
  WHERE DepartmentId = @DepartmentId
 
 RETURN 
END

GO


Using CROSS APPLY
SELECT * FROM Departments
 CROSS APPLY GetEmployees(Departments.DepartmentId)

The above query returns the rows with employees assigned to departments, whereas the department wherein the employees are not assigned does not appear. Thus we can see the department "Training" is missing.


Using OUTER APPLY
SELECT * FROM Departments 
 OUTER APPLY GetEmployees(Departments.DepartmentId)

The above query returns all the rows with the outer table, whether or not the function returns data for a specific row. Thus we can see that employee value of "Training" department has NULL values.

Learn by diving in Programming Ocean...
Happy Programming!!!

Thursday, April 12, 2012

Customizing items of RadGrid page size combo based on total records

Telerik provides the easy to use RadGrid control with inbuilt paging feature.

By default paging combo includes 10, 20 and 50 page sizes, regardless of number of records displayed in the grid (i.e. if records counts to 11 then also page size combo displays 10, 20 and 50).

If we want to customize the page size combo items to show
  •     Records count > 10 then page size items should show 10 and 20 
  •     Records count >= 20 then page size items should show 10, 20 and 50
In order to achieve the above functionality, we will be using RadGrid ItemCreated and ItemEvent events, refer the below code
private int totalItemCount;
protected void RadGrid1_ItemEvent(object sender, GridItemEventArgs e)
        {
            if (e.EventInfo is GridInitializePagerItem)
            {
                totalItemCount = (e.EventInfo as GridInitializePagerItem).PagingManager.DataSourceCount;
            }
        }

protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem pagerItem = (GridPagerItem)e.Item;
                RadComboBox pageSizeCombo = (RadComboBox)pagerItem.FindControl("PageSizeComboBox");

                if (totalItemCount > 10 && totalItemCount < 20)
                {
                    pageSizeCombo.Items.Clear();
                    RadComboBoxItem item = new RadComboBoxItem();
                    item = new RadComboBoxItem("10", "10");
                    item.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                    pageSizeCombo.Items.Add(item);

                    item = new RadComboBoxItem("20", "20");
                    item.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                    pageSizeCombo.Items.Add(item);
                }


                if (totalItemCount >= 20)
                {
                    if (pageSizeCombo.Items.Where(i => i.Value == "50").Count() == 0)
                    {
                        RadComboBoxItem item = new RadComboBoxItem();
                        item = new RadComboBoxItem("50", "50");
                        item.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                        pageSizeCombo.Items.Add(item);
                    }
                }

            }
        }

Displaying page combo always regardless of number of records, refer below code

                         
          
                    . . . .
     


Showing "Show All" option in page size combo, refer below combo
private int totalItemCount;
protected void RadGrid1_ItemEvent(object sender, GridItemEventArgs e)
        {
            if (e.EventInfo is GridInitializePagerItem)
            {
                totalItemCount = (e.EventInfo as GridInitializePagerItem).PagingManager.DataSourceCount;
            }
        }

protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem pagerItem = (GridPagerItem)e.Item;
                RadComboBox pageSizeCombo = (RadComboBox)pagerItem.FindControl("PageSizeComboBox");

              GridPagerItem pagerItem = (GridPagerItem)e.Item;
 RadComboBox PageSizeCombo = (RadComboBox)pagerItem.FindControl("PageSizeComboBox");
             RadComboBoxItem item1 = new RadComboBoxItem();
             item1 = new RadComboBoxItem("Show All", totalItemCount.ToString());
             item1.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
            PageSizeCombo.Items.Add(item1);

            }
        }
Thus we are done...

Learn by diving in Programming Ocean...
Happy Programming!!!

Thursday, December 22, 2011

Let it snow...

Its Christmas and New Year holiday time. Both Google & Microsoft seems to be playing same "Let it snow" competition.

1. Go to google.com and search for "Let it snow". Press enter.
2. Go to URL - http://ie.microsoft.com/testdrive/performance/letitsnow/ . Also see other test drive by clicking on “Return to test drive” on right top corner.

Learn by diving in Programming Ocean...
Happy Programming!!!

Thursday, November 24, 2011

Updating configuration parameters programmatically using ASP.Net

Download sample code
Introduction
In this article, we would see the method to update the key parameters in configuration file without causing the application instance.
This article assumes that the reader is already familiar with ASP.NET programming.

Keywords
web.config: Application configuration files contain settings specific to an application. This file contains the configuration settings that the common language runtime reads (such as the assembly binding policy, remoting objects, and so on), and settings that the application can read [MSDN].

xml: Extensible Markup Language (XML) is the universal format for data on the Web. XML allows developers to easily describe and deliver rich, structured data from any application in a standard, consistent way. XML does not replace HTML; rather, it is a complementary format [MSDN].

Requirement
According to the requirement we need to modify the values of the keys found in web.config programmatically or by providing configuration screen and also without re-instantiating Application instance (i.e. Application instance is not lost). So the user can modify the values of the keys for which he is allowed to do so.

Description
We all are familiar with ASP.Net programming and also the production environment of the website under Internet Information Services (IIS).
During the application life cycle, the application raises events that you can handle and calls particular methods like Application_Start and Application_End placed in Global.asax in the root directory of your application.
The Application_Start and Application_End methods are special methods that are called once for the lifetime of the application domain.
Here are some of the conditions in which the Applicaton_Start event is invoked.
  • On restarting of IIS.
  • Application pool of the website is restarted.
  • Updating the web.config file.
Solution

Add the new xml file in your solution by selecting Add New Item > Web Configuration file from dialog box.
Name this file whatever you like. Here I named it as “DataKey.config”.

 Web.config
  
 

In the above code snippet we have used configSource attribute of the appSettings tag. ConfigSource take the path of the another config file in the solution. And during the runtime the keys from config file are replaced in the appSettings section in web.config file.

 DataKey.config (custom configuration file)

  
  

Here there is no need for XML declaration, but the document element should be same as that we provide in web.config.

C# Code
System.Configuration.ConfigurationManager.AppSettings["merchantid"] 

System.Configuration.ConfigurationManager.AppSettings["merchantkey"]
Accessing the value of the key is same way we access from web.config.

C# Code
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.Load(Server.MapPath(@"~\DataKey.config"));  
System.Xml.XmlNode node = xml.SelectSingleNode("//appSettings/add[@key='" + txtKeyName.Text + "']");
node.Attributes["value"].Value = txtKeyValue.Text.Trim();
xml.Save(Server.MapPath(@"~\DataKey.config"));
Updating DataKey.config can be done using methods of System.Xml.XmlDocument.

So here the keys can be saved in XML file and can be modified without loosing the Application instance.

Hence we are done!!!

Learn by diving in Programming Ocean...
Happy Programming!!!

Tuesday, November 8, 2011

SSRS - Report Viewer - Hide PDF Export option

SQL Server Reporting Services eases designing of reports, whereas Microsoft Report Viewer control is used to display .rdl/.rdlc report into ASP.Net website.

Moreover report viewer control provides the various options in its toolbar. Of the different options, one option provides functionality of Exporting the report in different formats (like XML, CSV, Word, Excel, PDF ...)

Now what if one wants to exclude any/all of the above options?

Say if I want to hide PDF export option from Report Viewer toolbar. Below are the steps to do so.

Step - 1
Locate the file name "RSReportDesigner.config" at
"Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\RSReportDesigner.config".

Note: Location of the file varies in different version of SQL Server.

Step - 2
Disable PDF export option - add the visible attribute with value false
<Extension Name="PDF" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PDFRenderer,Microsoft.ReportingServices.ImageRendering" Visible="false" />


Enable PDF export option - remove the visible attribute
<Extension Name="PDF" Type="Microsoft.ReportingServices.Rendering.ImageRenderer.PDFRenderer,Microsoft.ReportingServices.ImageRendering" />


Step - 3
After this you need RESTART your Report Server.

This can be applied to other exporting options too.



Learn by diving in Programming Ocean...
Happy Programming!!!

Friday, October 21, 2011

SQL Query – How to get data in Hierarchical Structure?

Download sample data with Schema
Prepare an SQL query to display the given data in “Hierarchical Structure” based on the level of the parent node. In a way that tree structure can be prepared.

I have one table:
  • Location – It contains the data with Parent – Child relationship.

The structure of the table and result set is as follows:

Location
Resultant Data

Please provide your SQL query in comment of this article.

Click here to download the sample data including schema.

Following are the solutions provided by:
Me (Chirag Vidani)
WITH LocationList (LocationId,LocationName,ParentLocationId,LocationLevel)
AS
(
    SELECT loc.Id, loc.Name,loc.ParentId, 1 AS LocationLevel
    FROM Location AS loc
    WHERE loc.ParentId IS NULL
    UNION ALL
    SELECT l.Id,l.Name,l.ParentId,list.LocationLevel + 1
    FROM Location AS l
    INNER JOIN LocationList AS list
        ON l.ParentId = list.LocationId
)
SELECT LocationId,LocationName,isnull(ParentLocationId,0) 'ParentLocationId',LocationLevel FROM LocationList


Mr. Kaushik Patel
WITH LocationLevelReports (LocationID, Locationname , ParentLocationId, LocationLevel)
AS
(
-- Anchor member definition
SELECT L.ID, L.name, ISNULL(L.ParentId,0) ParentId, 
1 AS LocationLevel
FROM Location AS L
WHERE ParentId IS NULL
UNION ALL
-- Recursive member definition
SELECT L.ID, L.name, L.ParentId, 
LocationLevel + 1 as LocationLevel
FROM Location AS L
INNER JOIN LocationLevelReports AS R
ON L.ParentId = R.LocationID

)
select * from LocationLevelReports



Learn by diving in Programming Ocean...
Happy Programming!!!

Thursday, October 13, 2011

SQL Query - How to Select top 2 highest salaried employees from each department?

Download sample data with Schema
Let us share some knowledge of SQL Query.

I have three tables mentioned below:
  • Employee – Master table
  • SalaryDetails – Reference table with salary information
  • Department – Master table

The sample data into these tables is show below:

Employee
Department
Salary Details
Now the SQL Query to be prepared should contain resultant data as ‘top 2 highest salaried employees from each department’ as below :

Resultant Data
Please provide your queries in comment of this article.

Schema with sample data is provided on download link, which will save your time for preparing sample tables and data. Click here to download.

Following are the solutions provided by:
Me (Chirag Vidani)
select 
 data.DepartmentName 'Department Name', data.EmployeeName 'Employee Name', data.Salary 'Salary/Day' 
from
 (select 
  d.Name 'DepartmentName',e.Name 'EmployeeName',sd.Salary 'Salary',dense_rank() over(partition by sd.DepartmentId order by sd.Salary desc)'SalaryRank' 
 from 
  Salarydetails sd
 join Department d 
  on sd.DepartmentId = d.Id
 join Employee e 
   on sd.EmployeeID =e.Id) as data
where 
 data.SalaryRank <= 2
order by 
 data.DepartmentName,data.Salary desc


Mr. Kaushik Patel
SELECT 
 d.* 
FROM
 (select 
  S.*,D.NAME DepartmentName,E.NAME EmployeeName ,RANK() OVER (PARTITION BY DeptID ORDER BY SALARY DESC) AS Raw_Rank 
 from 
  Salary s 
 inner join Employee e 
  on s.EmployeeId = e.id 
 inner join Department d 
  on s.DepartmentId = d.id ) d 
WHERE 
 Raw_Rank <=2



Learn by diving in Programming Ocean...
Happy Programming!!!

Thursday, October 6, 2011

How to upload/download file to/from server using WebClient method…?

Today’s business applications are working on client server architecture and on timely basis files are being uploaded to server from client or vice versa.

In ASP.Net we can upload a file to server using File-Upload control. But what-if we want to upload a file automatically or programmatically to the server using Windows application, Windows Service or Web application?

The possible ways to upload a file to server are follows:
  • FTP Upload 
  • HTTP Upload
  • ...
Here I will show how to upload/download a file using HTTP method (i.e. commonly known as Web Client method).

In Web Client method we require a virtual directory to which file is to be upload under domain name (i.e. http://www.YourDomainName.com/ClientFiles/). So we are going to upload files to “ClientFiles” directory.

Note: You need to install and configure WebDAV (Web Distributed Authoring and Versioning) in IIS. Click here for an article on Installing and Configuring WebDAV on IIS 7.

Code to upload a file on Server using WebClient method:

System.Net.WebClient webClient = new System.Net.WebClient();
string sourceFilePath = @"D:\MyDocuments\DataFile.xml" ;
string webAddress = "http://www.YourDomainName.com/ClientFiles/";
string destinationFilePath= webAddress + "DataFile.xml";
webClient.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
webClient.UploadFile(destinationFilePath, "PUT", sourceFilePath);
webClient.Dispose();


Code to download a file from Server using WebClient method:

System.Net.WebClient webClient = new System.Net.WebClient();
string webAddress = "http://www.YourDomainName.com/ClientFiles/";
string sourceFilePath = webAddress + "DataFile.xml";
string destinationFilePath = @"D:\MyDocuments\DataFile.xml";
webClient.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
webClient.DownloadFile(sourceFilePath, destinationFilePath);
webClient.Dispose();




Learn by diving in Programming Ocean...
Happy Programming!!!

Wednesday, October 5, 2011

How to RESET identity column in SQL Server

During the development of any application we input dummy data and which is stored in database. But frequently we come to the point where we want all records of the table to be deleted and also want to start the identity columns values from 0.

For this we delete the data using truncate command.
It will delete the data from table and also reset the identity column’s value to 0.
truncate table <table_name>

truncate table product


But the truncate command fails to delete the data if there is relationship given to the table and the identity column is not reset.

For this after firing the delete command execute below command.
It will reset the identity column of product table to 0.
DBCC CHECKIDENT('<table_name>', RESEED, <reset from number>)

DBCC CHECKIDENT('product', RESEED, 0)


Learn by diving in Programming Ocean...
Happy Programming!!!

Monday, September 26, 2011

Preparing “Data Dictionary” using SQL Query

Data dictionary is the required while documenting any project. So here is the query for preparing the data dictionary of any database.

SELECT [Table Name] = OBJECT_NAME(c.object_id)
,[Column Name] = c.name
,[Data Type] = t.name
,[Size] = c.max_length
,[Description] = isnull(ex.value,'') 
FROM sys.columns c 
LEFT OUTER JOIN sys.extended_properties ex ON (ex.major_id = c.object_id AND ex.minor_id = c.column_id AND ex.name = 'MS_Description') 
INNER JOIN sys.types t ON c.system_type_id = t.system_type_id 
WHERE OBJECTPROPERTY(c.object_id, 'IsMsShipped')=0 
AND OBJECT_NAME(c.object_id) in (select name from sys.tables where type= 'U') 
ORDER BY OBJECT_NAME(c.object_id), c.column_id

Just include the column of the table definition (if any other required - i.e. if you want to display whether the column is null/not null, just include the field from sys.objects table and so on).


Learn by diving in Programming Ocean...
Happy Programming!!!

Friday, September 23, 2011

Taking backup of Skype contacts

Something important thing to share with you.

If ever you are using Skype messenger, please make a habit to take backup of contacts on timely basis, because your contacts gets deleted you can easily restore/recover them back from backup file.

As today only I lost all my contacts from skype messenger, because I used old version of skype messenger and Skype suggest us not to use old version when new version is out.

So then after contacting to skype customer care, they restored my contacts.

So to overcome this situation keep a habit of taking backup of skype contacts if you are using skype for communication purpose

Learn by diving in Programming Ocean...
Happy Programming!!!

Tuesday, September 20, 2011

Serializing into JSON using .Net 4.0 classes

Lets discuss something new and interesting points related to latest technology JSON.

While returning data in ajax call of jQuery we generally convert into string and then IIS serialize the data.

But .Net 4.0 provides the DataContractJSONSerializer class which automatically converts any datatype to string datatype (i.e. generic list/any type of data can be serialized using this class and returned back in form JSON).

Learn by diving in Programming Ocean...
Happy Programming!!!

Parsing JSON using jQuery

Lets discuss something new and interesting points related to latest technology jQuery & JSON.

Many of us might have worked in it and others don't need to worry as in future they will surely work in it.

Recently I came across one thing that "While using JSON we require parse_json.js file (plugin), but according to me this file is not at all required. As parse json function is already included in default jQuery pre-requisite file (.js) only. "

To refer the complete syntax visit: http://api.jquery.com/jQuery.parseJSON/

Learn by diving in Programming Ocean...
Happy Programming!!!

Wednesday, November 25, 2009

Life lessons by Warren Buffet


There was a one hour interview on CNBC with Warren Buffet, the second richest man who has donated $31 billion to charity. Following are some very interesting aspects of his life.


  • He bought his first share at an age 11 and he now regrets that he started too late !
Moral : Things were very cheap that time. Encourage your children to invest.

  • He bought a small farm at age 14 with savings from delivering newspapers.
Moral : One could have bought many things with little savings. Encourage your children to start some kind of business.

  • He still lives in the same small 3-bed room house in mid-town Omaha, that he bought after he got married 50 years ago. He says that he has everything he need in that house. His house does not have a wall or a fence.
Moral : Don't buy more than what you "really need" and encourage your children to do and think the same.

  • He drives his own car everywhere and does not have a driver or security people around him.
Moral : You are what you are.

  • He never travels by private jet, although he owns the world's largest private jet company.
Moral : Always think how you can accomplish things economically.

  • His company, Berkshire Hathway, owns 63 companies. He writes only one letter each year to the CEOs of these companies, giving them goals for the year. He never holds meetings or calls them on a regular basis.
Moral : Assign the right people to the right jobs.

  • He has given his CEOs only two rules.
Rule Number 1 : Do not lose any of your share holder's money.
Rule Number 2 : Do not forget rule number one

Moral : Set goals and make sure people focus on them.

  • He does not socialize with the high society crowd. His past time after he gets home is to make himself some popcorn and watch television.
Moral : Don't try to show off, just be yourself and do what you enjoy doing.

  • Warren Buffet does not carry a cell phone, nor has a computer on his desk.
  • Bill Gates the world's richest man met him for the first time only 5 years ago, Bill Gates did not think he had anything in common with Warren Buffet. So he had scheduled his meeting only for half hour. But when Gates met him, the meeting lasted for 10 hours and Bill Gates became a devotee of Warren Buffet.
  • His advice to young people:
Moral : "Stay away from credit cards (bank loans) and invest in yourself and remember :
(a.) Money doesn't create man but it is the man who create money.
(b.) Live your life as simple as you are.
(c.) Don't do what others say, just listen them, but do what you feel good.
(d.) Don't go on brand name, just wear those things in which you feel comfortable.
(e.) Don't waste your money on unnecessary things, just spend on them who really need rather.
(f.) After all, it's your life then why give chance to others to rule our life.

Learn by diving in Programming Ocean...
Happy Programming!!!

Tuesday, September 22, 2009

Create a Crystal Report from ADO.NET Dataset using Visual Basic .NET

Introduction:
Crystal Report of Visual Studio .NET is the standard reporting tool for Visual Studio .NET. You can host reports on web and windows platform and can publish reports as Report Web services on the web server. It is based on framework of Crystal Report 11.0 and uses open and flexible architecture, with standards like XML, to allow porting reports over the web. Using crystal report expert you can choose report layouts, display charts, calculate summaries, subtotals as grouped data as well as conditionally format text and rotate text objects.

Although Crystal Reports for Visual Studio .NET supports variety of data source like ADO recordset, CDO recordset, DAO recordset, MS Excel workbook, this walkthrough endeavor to explain How to report off ADO.NET DataSet using Visual Basic .NET.

As you all know DataSet is the core component of distributed application and is explicitly designed for data access independent of any data source. Dataset can be created from variety of sources. Whatever the source is, before reporting off ADO.NET DataSet you must perform the following task:
  • Generate an object for the DataSet.

  • Connect report to DataSet Object.

  • Push data into DataSet Object.

  • Bind report to Windows Forms Viewer to display report with actual data at runtime.


  • Requirements:
  • Visual Studio 2005

  • .NET Framework 2.0

  • SQL Server 2005 Express Database


  • Generating an Object for the DataSet
    Object for ADO.NET is a collection of dataset classes created in memory.

    To create a dataset object from database in SQL Server, using ADO.NET DataSet Designer.

    1. In the Solution Explorer, right-click the project name, point to Add, and click Add New Item.
    2. In the Categories area of the Add New Item dialog box, expand the folder and select Data.
    3. In the Templates area, select Dataset.
    4. Accept the default name Dataset1.xsd.

    This creates a new schema file that will be used to generate a strongly typed dataset. The schema file will be displayed in ADO.NET Dataset designer.

    5. In the Solutions Explorer, click on Dataset1.xsd file, if now already the active view.
    6. From the Server Explore, on the right connect to SQL Server and drill down to Northwind Database.
    7. Highlight the Table Customers (or stored procedure if desired) and drag and drop it on the Interface of Dataset1.xsd. Dataset1.xsd should now be displayed in the Dataset tab.

    This creates a dataset object and contains only a description of the database based on the schema in Dataset1.xsd. It does not contain the actual data.

    Connecting Report to an ADO.NET Dataset Object
    From ADO.NET Dataset Object you can add tables to Crystal Report using Database Expert in Crystal Report Designer.

    To create a new report and connect it to Dataset object which contains description for Customers table

    1. In the Visual Studio Solution Explorer, right-click your project to display the shortcut menu.
    2. Point to Add and click Add New Item.
    3. In the Add New Item dialog box, select Crystal Report from the Templates area. Click Open.
    4. You will be presented with Crystal Report Gallery.
    5. You can choose from any of the options provided in Crystal Report Gallery. But for the purpose of this walkthrough choose As a Blank Report and click OK.
    6. On File menu, click Save to save the report.
    7. Right click in the Report Designer, point to Database, and click Add/Remove Database.
    8. You’ll be presented with Database Expert wizard.
    9. In the Database Expert wizard, expand the Project Data folder, expand the ADO.NET Datasets folder and select the dataset object.
    10. If you now drill down Database Fields node, in the Field Explorer, you can view Customers table and all its fields
    11. Drag and drop the fields onto the report and format them as required.

    Pushing data into DataSet object and binding report to Windows Forms Viewer
    In order to display actual data in the report, you should fill the dataset object with the data before you bind the report to Windows Forms Viewer. You should do this in the corresponding source file for Windows Form.

    1. Drag and drop CrystalReportViewer control on Form1 and set the DisplayGroupTree property to False.
    2. Accept the default name as CrystalReportViewer1.
    3. Open Form1 code editor and add the following code on Load event of Form1.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim rpt As New CrystalReport1() 'The report you created.
    Dim myConnection As SqlConnection
    Dim MyCommand As New SqlCommand()
    Dim myDA As New SqlDataAdapter()
    Dim myDS As New Dataset1() 'The DataSet you created.

    Try

    myConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;" & _
    "Initial Catalog=northwind;")
    'or
    'myConnection = New SqlConnection("server=(local)\SqlExpress;AttachDbFileName=" &_ Application.StartupPath & "\Database1.mdf;Integrated Security=true;User Instance=true")
    MyCommand.Connection = myConnection
    MyCommand.CommandText = "SELECT * FROM Customers"
    MyCommand.CommandType = CommandType.Text
    myDA.SelectCommand = MyCommand

    myDA.Fill(myDS, "Customers")
    rpt.SetDataSource(myDS)
    CrystalReportViewer1.ReportSource = rpt

    Catch Excep As Exception
    MessageBox.Show(Excep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
    End Sub

    Or the following code is also useful

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim rpt As New CrystalReport1 'The report you created.
    Dim dbConn As SqlConnection

    Dim dbAdptr As New SqlDataAdapter
    Dim dbDataset As New DataSet1 'The DataSet you created.

    Try

    dbConn = New SqlConnection("server=(local)\SqlExpress;AttachDbFileName=" & Application.StartupPath & "\Data\Database1.mdf;Integrated Security=true;User Instance=true")

    dbAdptr = New SqlDataAdapter("select * from table1", dbConn)

    dbAdptr.Fill(dbDataset, "Table1")
    rpt.SetDataSource(dbDataset)
    CrystalReportViewer1.ReportSource = rpt

    Catch Excep As Exception
    MessageBox.Show(Excep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
    End Sub

    Troubleshooting

    Add reference to SqlClient namespace. Imports System.Data.SqlClient

    Check connection to your server.

    Happy programming!!!


    Learn by diving in Programming Ocean...
    Happy Programming!!!

    Friday, September 18, 2009

    Master/Slave Configurations for PC Hardware

    Master/Slave Configurations

    The hard drive or CD-ROM drive controller’s function is to receive commands to the drive and control the action of the drive itself. The technology incorporated in IDE and ATA devices allows one controller to take over the function of more than one drive. This means that you can install up to two drives on a single ribbon cable. This setup is called a master/slave configuration because one drive’s controller directs the activities of both drives. It is important to note here that most computer systems can support a mixture of IDE and ATA drives.

    Installing Master and Slave Hard Drives

    1. Determine, which drive, will be the master. (See the “Choosing a Master” From the Classroom for more information).

    2. Locate the master/slave jumpers, which can be found on the bottom of the drive or, more commonly, on the end by the power and ribbon cable connectors. In Fig 2-1, the jumpers are located to the left of the power connector and the jumper settings are indicated by the standard settings information on the label.



    Fig 2.1 the master/slave jumper set on a typical hard drive

    3. Use the drive label information to determine which jumper settings to use for a master or a slave configuration.

    4. Set this drive as a master using the jumper(s).

    5. Using the procedure explained in Chapter 1, Exercise 1-2, physically install this drive on the end of the ribbon cable and secure it to an available drive bay.

    6. Using the proper jumper setting, configure the second drive as a slave.

    7. Install the second drive in the middle of the ribbon cable. Your hard drive setup should look similar to the one shown in Fig 2-2. Note the position of the hard drives on the ribbon cable.

    The jumpers inform the BIOS about the IDE devices if they are master, slave or cable select. If a device is jumpered as cable select and if it is put in the farthest end from the controller then that device is recognized as master and if it is put in the middle of the cable it is recognized as slave. Whereas for Master and Slave configurations wherever the device is put it is recognized as master or slave. The jumpers vary for different manufacturers and are not the same. Seagate is the only manufacturer whose hard disk when not jumpered is recognized as Slave.

    Note: The master drive must be set to the master jumper setting and be installed on the end of the ribbon cable. The slave drive must be set to the slave jumper setting and be installed in the middle of the ribbon cable

    Most newer computers will detect the presence of a master/slave configuration and name the drives appropriately: Typically, the master will be drive C, and the slave will be drive D. However, some older computers require you to perform drive detection. In this case, when you start the computer, enter the CMOS settings program, as discussed in Chapter 1. Select the Auto-Detect or Detect Hard Drive option (these options might have slightly different names on different computers). This choice forces the BIOS to search all drive controller connections for the presence and configuration of hard or CD-ROM drives.

    Fig 2.2 The finished installation of a master/slave configuration

    Devices per Channel

    Most newer computers have two hard drive controllers. That is, the motherboard has connectors for two ribbon cables (see Fig 2-3). These controllers are termed primary and secondary. If there is only one drive present, it must be attached to the primary controller. An additional drive can be added as either a primary slave or a secondary master. It is important to note that although they are often referred to as hard drive controllers, these devices are not limited to controlling hard drives; they are also used to control CD-ROM drives.

    To add a drive to the secondary controller, simply connect the drive to a ribbon cable and attach the ribbon cable to the secondary controller port on the motherboard, ensuring that the red stripe is aligned with pin 1. You will also of course need to connect a power cable to the drive. There is usually no noticeable performance advantage to configuring a second drive as a secondary master rather than as a primary slave. (See the “Choosing a Master” From the Classroom for a discussion on choosing the master or slave designation.)

    As before, the primary master receives the first available drive letter, typically C. The remaining drives are lettered according to this order of priority: primary slave, secondary master, and primary master.

    When you add or remove a drive to or from a multidrive system, the drives are automatically relettered so that no letters are skipped. For example, suppose a system includes drives C: , D:, and E:. If drive D: is removed, the E: drive will be relabeled D: the next time the computer is started. Windows operating systems also allow for a drive to be configured to hold a certain drive letter.



    FROM THE CLASSROOM


    Choosing a Master

    How do you determine which drive should be the master and which should be the slave? In many cases, it doesn’t matter which is which. That is, there is no real performance difference between master and slave drives. However, as with most computer configurations, there are some exceptions.

    Some operating systems require that the hard drive containing the OS be configured as a master. This is important to note only if you are installing drives that already contain data. If you are installing new hard drives, you don’t have to worry about this; simply load the OS on the master drive after the drives are installed.

    When using a mixture of old and new hard drives within the same system, set the newer drive as the master and the older drive as the slave. This setting is a good idea because newer drives can recognize and communicate with older drives, but the reverse isn’t true. An older drive’s controller will typically be unable to control the newer drive.

    When using a hard drive and CD-ROM drive together in a master/slave configuration, always set the hard drive as the master and the CD-ROM as the slave because the CD-ROM’s controller is unable to take control of the hard drive. Additionally, some (but not most) CD-ROM drives are designed to work as slaves, even when there is no master present, and they simply cannot be configured as master drives.



    Learn by diving in Programming Ocean...
    Happy Programming!!!

    Friday, February 27, 2009

    Winning Lessons by Mr.Barack Obama (Honourable President of US)

    • Feel good about yourself.
    • Believe in yourself and your dreams.
    • Take risk to make your dream a reality.
    • Have a clear vision and mission.
    • Share your goal with the people.
    • Be with your team and empower them.
    • Make powerful and heart moving speeches.
    • Smile and you can go a long way.
    • High confidence and enthusiasm works.
    • Be a good listener.
    • Make optimum use of technology.
    • Be open and creative in your approach.
    • Collaborate and win the competitors.
    • Have role and follow them.
    • Be proactive - Don't react under pressure.
    • What matters is what is inside you.
    • Never neglect your family.
    • Begin with the end in mind.

    Learn by diving in Programming Ocean...
    Happy Programming!!!

    Sunday, February 1, 2009

    Following Post is to sent SMS through your Way2SMS account













    Your way2sms ID :

    Your way2sms Password :

    Phone number of person to send sms :

    Message to be sent :




    Learn by diving in Programming Ocean...
    Happy Programming!!!