Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for September, 2010

Removing Duplicate Records from Dataset/DataTable

Posted by Viral Sarvaiya on September 27, 2010


Hello friends….

Hear i demonstrate, how to remove the rows from the dataset that have duplicate rows.

Duplicate DataTable looks like,

Name                                         Company

Viral                                          BNF Tech

Sandeep                                   Gateway Tech

Dharmik                                   Om info

Malhar                                       BNF Tech

Viral                                           BNF Tech

Dharmik                                   Om info

Viral                                           BNF Tech

Sandeep                                   Gateway Tech

now this is the function that remove the duplicate rows from the DataTable as below,

public DataTable DuplicateRowRemove(DataTable dt, string Col)
 {
 Hashtable hTable = new Hashtable();
 ArrayList ArrDupli = new ArrayList();

 foreach (DataRow r in dt.Rows)
 {
 if (HeshTbl.Contains(r[Col]))
 ArrDupli.Add(r);
 else
 HeshTbl.Add(r[Col], string.Empty);

}

 foreach (DataRow R in ArrDupli)
 dt.Rows.Remove(R);

 return dt;
 }

so, after the removing the duplicate data DataTable shows as blow,

Name                                         Company

Viral                                          BNF Tech

Sandeep                                   Gateway Tech

Dharmik                                   Om info

Malhar                                       BNF Tech

thanks you…..

Malhar                                       BNF Tech
Advertisements

Posted in ASP.NET | Tagged: , , , , | 9 Comments »

Bind Silverlight Grid view with WCF Service

Posted by Viral Sarvaiya on September 17, 2010


Hello friends….

Here I demonstrate how to bind the grid view of the Silverlight with WCF Service.

You already know what is the Silverlight and WCF. My one post that demonstrate the use of the WCF Service with Silverlight, for more info about that check https://viralsarvaiya.wordpress.com/2010/08/26/use-of-wcf-service-in-silverlight/

Setp 1 : Create New Silverlight Project( here I give name of the project is “SilverlightGridTest”)

In the Visual Studio 2008 or 2010, file menu -> New -> project.

Select Silverlight application, give name as SilverlightGridTest and open the project.

Then check the checkbox true of the host the Silverlight application in web site.

Now you have 2 project in the solution.

Step 2: Database information

CREATE TABLE person (

Name VARCHAR(256),

Phone VARCHAR(50),

City VARCHAR(50)

)

make one procedure named “GetAllPersonInfo” and write the following Statement in the procedure

Select *from person order by name;

Step 3: Create WCF Service

Right click to SilverlightGridTest.web project, select add -> new item.

Choose Silverlight in left panel and choose Silverlight-enable WCF Service. Then give name “DataService.svc”

So Service has been added to project.

Here we have interface IDataService.cs and DataService will implements that so in our IDataService.cs code is as below.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SilverlightGridTest.Web

{

[ServiceContract]

public interface IDataService

{

[OperationContract]

PersonDetails GetPersonDetails();

}

[DataContract]

public class PersonDetails

{

List<Personinfo> _PersonList = new List<Personinfo>();

[DataMember]

public List<Personinfo> PersonIndex

{

get { return _PersonList; }

set { _PersonList = value; }

}

}

[DataContract]

public class Personinfo

{

[DataMember]

public string Name { get; set; }

[DataMember]

public string Phone { get; set; }

[DataMember]

public string City { get; set; }

}

}

In the “DataService.svc.cs” file write the following.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Data;

namespace SilverlightGridTest.Web

{

public class DataService : IDataService

{

public PersonDetails GetPersonDetails()

{

DatabaseHandler dbObj = new DatabaseHandler();

DataTable dataTablePersonInfo = dbObj.GetPersonInfo();

PersonDetails PersonDataMessage = new PersonDetails();

for (int iTagCounter = 0; iTagCounter < dataTablePersonInfo.Rows.Count; iTagCounter++)

{

Personinfo PersonInfo = new Personinfo();

PersonInfo.Name = dataTablePersonInfo.Rows[iTagCounter]["Name"].ToString();

PersonInfo.Phone = dataTablePersonInfo.Rows[iTagCounter]["Phone"].ToString();

PersonInfo.City = dataTablePersonInfo.Rows[iTagCounter]["City"].ToString();

PersonDataMessage.PersonIndex.Add(PersonInfo);

}

return PersonDataMessage;

}

}

}

Now add the new class name “DatabaseHandler.cs” for the operation on the database. Means this function will get the data from the database.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections.ObjectModel;

namespace SilverlightGridTest.Web

{

public class DatabaseHandler

{

private string _gConnectionString = ConfigurationManager.ConnectionStrings["Database"].ToString();

public DataTable GetPersonInfo()

{

SqlConnection sqlConnect = new SqlConnection(_gConnectionString);

sqlConnect.Open();

DataTable dbTbl = new DataTable();

//Get data

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "GetAllPersonInfo";

cmd.Connection = sqlConnect;

cmd.CommandType = CommandType.StoredProcedure;

SqlDataAdapter oAdapter = new SqlDataAdapter(cmd);

oAdapter.Fill(dbTbl);

sqlConnect.Close();

return dbTbl;

}

}

}

Step 4: Web.Config Settings

Database Connection string


<connectionStrings>

<add connectionString="packet size=4096;server=ServerName;persist security info=False;database=DatabaseName;uid=UserName;pwd=Password;" />

</connectionStrings>

Service Settings


<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior>

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="false" />

</behavior>

</serviceBehaviors>

</behaviors>

<bindings>

<customBinding>

<binding>

<binaryMessageEncoding />

<httpTransport />

</binding>

</customBinding>

</bindings>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

<services>

<service behaviorConfiguration="SilverlightGridTest.Web.TestServiceBehavior" name="SilverlightGridTest.Web.DataService">

<endpoint address="" binding="basicHttpBinding" contract="SilverlightGridTest.Web.IDataService" />

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

</service>

</services>

</system.serviceModel>

Step 5: Add clientaccesspolicy.xml and crossDomain.xml file.

This will complete the coding in the SilverlightGridTest.Web .

Build the application.

Now move to SilverlightGridTest.

Add the service reference and add the service which we develop above.

Step 6: Mainpage.xaml file.

Now in the Mainpage.xaml file put the grid control.


<UserControl x:Class="SilverlightGridTest.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">

<sdk:DataGrid x:Name="AllPerson" GridLinesVisibility="All" AutoGenerateColumns="False" >

<sdk:DataGrid.Columns>

<sdk:DataGridTextColumn Binding="{Binding Name}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" />

<sdk:DataGridTextColumn  Binding="{Binding Phone}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="Phone"/>

<sdk:DataGridTextColumn  Binding="{Binding City}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="City"/>

</sdk:DataGrid.Columns>

</sdk:DataGrid>

</Grid>

</UserControl>

Step 7 : Mainpage.xaml.cs file

Make the object of the service client, coding as follow.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using SilverlightGridTest.DataService;

namespace SilverlightGridTest

{

public partial class MainPage : UserControl

{

public DataServiceClient objDataService;

public MainPage()

{

InitializeComponent();

objDataService = new DataServiceClient();

objDataService.GetPersonDetailsCompleted += new EventHandler<GetPersonDetailsCompletedEventArgs>(objDataService_GetPersonDetailsCompleted);

objDataService.GetPersonDetailsAsync();

}

void objDataService_GetPersonDetailsCompleted(object sender, GetPersonDetailsCompletedEventArgs e)

{

AllPerson.ItemsSource = e.Result.PersonIndex;

}

}

}

Step 8: Run the application.

You will get the data will display in the grid as below

Enjoy coding…..

Posted in ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , , , , , , | 14 Comments »

Difference between count(*) and count(column_name)

Posted by Viral Sarvaiya on September 13, 2010


what is count(*), count(column_name) and count(distinct column_name) ?

suppose we have employee table and having 100 records.

you all know what is count(*) in sql, this all function return same result if there is no record null in column.

select count(*) from employee
select count(emp_name) from employee
select count(distinct emp_name) from employee

that return the total employee from the employee table,

answer of this 3 query is 100.

but what happen if some records approx 20 of the emp_name is null?

now this 3 query give same answer?

no.

select count(*) from employee

return 100

select count(emp_name) from employee

return 80

select count(distinct emp_name) from employee

return 80

count(*) count the null records while count(column_name) omits the null value so it return 80(100 – 20) record.

hope you are clear with the count(*) count(column_name) and distinct column_name).

thank you.

Posted in Sql Server | Tagged: , , , , , | 1 Comment »

Memory Management and Garbage Collection in .NET

Posted by Viral Sarvaiya on September 10, 2010


This video describe the how .net doing memory management and garbage collection. Great video……

Watch Video : Click Here

Click Here

Posted in ASP.NET | Tagged: , , , | 2 Comments »

Benefits of Silverlight

Posted by Viral Sarvaiya on September 10, 2010


Naturally, Silverlight offers all of the same benefits of RIAs, but there are a few features that set it apart from other RIA solutions, including the following:

  • It offers cross-platform/cross-browser support.
  • It provides a cross-platform version of the .NET Framework.
  • XAML is a text-based markup language.
  • Silverlight uses familiar technologies.
  • Silverlight offers an Out of Browser and Full Trust option.
  • Silverlight is the main development platform for Windows Phone 7.
  • It’s easy to deploy the Silverlight runtime to clients.

Let’s take a closer look at each of these benefits.

Cross-Platform/Cross-Browser Support

When ASP.NET was released a number of years ago, one of the benefits touted was cross- browser support. Developers would need to have only one code base, and that code base would work in all modern browsers. For the most part, this is true. No matter which browser you are using, the application will function. However, in order to receive all of the bells and whistles offered by the ASP.NET controls, you must use the latest version of  Internet Explorer. If you are using any other browser, you actually get a downgraded version of the web site, which contains fewer features.

Validation controls are a prime example. If you are using a browser that ASP.NET recognizes as an “upscale” browser, you can take advantage of client-side validation. If you are using any other browser, the validation controls still function, but require a postback to the server to do the validation. So, although ASP.NET is cross-browser, users can get different experiences, depending on which browser they are using.

With Silverlight, this changes. Microsoft is once again pulling out the term cross-browser, and also adding cross-platform, and this time they mean it. As a developer, you can create a Silverlight application and rest assured that it will run exactly the same on all supported platforms and browsers.Currently, two platforms are supported. Naturally, the first is Windows-based platforms, and the second is Mac OS platforms. As for browser support, Internet Explorer, Firefox, Safari and Google Chrome are currently covered.

This leaves one large platform unsupported: Linux. Although Microsoft does not have plans to support Linux, others do. Moonlight is an open source implementation of Silverlight, targeted primarily at Linux based operating systems. Moonlight is part of the Mono project, an open source initiative to develop and run .NET client and server applications on Linux, Solaris, Mac OS X, Windows, and Unix. Although Moonlight brings Silverlight features to Linux, the project lags behind the aggressive Microsoft release cycles. The latest version of Moonlight is version 3 Preview 6, which comes close to compatibility with Silverlight 3.

Cross-Platform Version of the .NET Framework

Silverlight 1.0 was released by Microsoft in the summer of 2007, but this version supported only Ecma languages that are interpreted in the client. Although Silverlight 1.0 works well for developers who are already familiar with client-side scripting, many developers have their eyes on the second release of Silverlight, version 2. Silverlight 1.0 is more or less in direct competition with Flash—some have called it Microsoft’s “Flash killer.” However, things really get exciting with Silverlight 2.

Silverlight 2 and beyond contains its own cross-platform version of the .NET Framework, which means it has its own version of the common language runtime (CLR), the full type system, and a .NET Framework  programming library that you can use in Visual Studio 2010 to build rich user experiences in the browser.

Use of Familiar Technologies

Microsoft is very good at creating tools that make application development easy. The Visual Studio integrated development environment (IDE) has been around for quite some time, and although new features are continually added to the tool, the environment itself has remained remarkably consistent. Silverlight development is no different. At the core of developing Silverlight applications is Visual Studio 2010, the latest version in Visual Studio’s long history. This gives Silverlight a distinct advantage, as developers do not need to learn how to use a new development environment. In addition to Visual Studio, Microsoft has a suite of tools called Expression Studio. Included in this suite is Microsoft Expression Blend, which is used to edit and create XAML for Silverlight applications. While Expression Blend looks completely different, it still has many of the same  elements as Visual Studio. In addition, Expression Blend works off of the same project as Visual Studio. This means that as you make changes in each of the editors—opening a project in Visual Studio, and then opening the  same project in Expression Blend to edit the XAML—the edited files will request to be refreshed when opened again in the other tool.

Small Runtime and Simple Deployment

Since Silverlight requires that a client runtime be installed on the client machine, it is vital that this runtime has a small footprint and downloads quickly. Microsoft worked very hard to get the installation size as small as possible. The developers clearly succeeded with Silverlight 1.0, as the download size is a tiny 1MB. For Silverlight 2, however, they had a harder chore ahead of them, since Silverlight 2 contains its own .NET Framework and object library. Microsoft went to each .NET Framework team and allocated it a size to fit its portion. The end result is astonishing—Silverlight 2 is approximately 4MB in size. In Silverlight 4, even with the large amount of new features that have been added to the Silverlight runtime, the file size is still less than 6MB.

As for pushing the Silverlight runtime out to clients, Microsoft has provided a very easy detection mechanism. If the client does not have the proper Silverlight runtime installed, it will display a logo of the Silverlight.

Posted in ASP.NET, Silverlight | Tagged: , | Leave a Comment »

WCF Duplex client for Silverlight

Posted by Viral Sarvaiya on September 9, 2010


WCF services offer the functionality to send data down to a Silverlight client. The Silverlight client polls the service at a regular interval to check if data is available for transfer.

Here are some great examples of how to implement duplex communication between WCF web services and Silverlight clients:

http://weblogs.asp.net/dwahlin/archive/2008/06/16/pushing-data-to-a-silverlight-client-with-wcf-duplex-service-part-i.aspx

http://petermcg.wordpress.com/2008/09/03/silverlight-polling-duplex-part-1-architecture/

http://petermcg.wordpress.com/2008/09/03/silverlight-polling-duplex-part-2-the-server/

http://petermcg.wordpress.com/2008/09/03/silverlight-polling-duplex-part-3-the-client/

Posted in ASP.NET, Silverlight | Tagged: , , , , , , , , , | 1 Comment »

Configuring IIS for Silverlight Applications

Posted by Viral Sarvaiya on September 9, 2010


Microsoft® SilverlightTM is a cross-browser, cross-platform plug-in for delivering the next generation of .NET-based media experiences and rich interactive applications for the Web. Silverlight offers a flexible programming model that supports AJAX, VB, C#, Python, and Ruby, and integrates with existing Web applications. Silverlight supports fast, cost-effective delivery of high-quality video to all major browsers running on the Mac OS or Windows.

In most cases, hosters do not need to perform particular deployments to support Silverlight. However, check for the following basic items that could prevent Silverlight from functioning correctly.

MIME Types

IIS 7 in Windows Server 2008

All MIME types needed to support Silverlight are implemented by default in IIS 7 in Windows Server 2008 and Windows Vista SP1.  Windows Vista customers can add MIME types by running IIS Manager, clicking MIME Types, then clicking Add, and then adding the following MIME types:

  • .xap     application/x-silverlight-app
  • .xaml    application/xaml+xml
  • .xbap    application/x-ms-xbap

Alternatively, you can add the following MIME types to your %windir%\system32\inetsrv\config\applicationHost.config file in the <staticContent> section.

<mimeMap fileExtension=”.xaml” mimeType=”application/xaml+xml” />
<mimeMap fileExtension=”.xap” mimeType=”application/x-silverlight-app” />
<mimeMap fileExtension=”.xbap” mimeType=”application/x-ms-xbap” />

In Windows Server 2003 IIS 6.0

To enable IIS 6.0 in Windows Server 2003 or IIS 7 in Windows Vista with the appropriate MIME Types, add:

  • .xap     application/x-silverlight-app
  • .xaml    application/xaml+xml
  • .xbap    application/x-ms-xbap

Here is a VBS script you could run to enable each of these types:

Const ADS_PROPERTY_UPDATE = 2

if WScript.Arguments.Count < 2 then
WScript.Echo “Usage: ” + WScript.ScriptName + ” extension mimetype”
WScript.Quit
end if

‘Get the mimemap object.
Set MimeMapObj = GetObject(“IIS://LocalHost/MimeMap”)

‘Get the mappings from the MimeMap property.
aMimeMap = MimeMapObj.GetEx(“MimeMap”)

‘ Add a new mapping.
i = UBound(aMimeMap) + 1
Redim Preserve aMimeMap(i)
Set aMimeMap(i) = CreateObject(“MimeMap”)
aMimeMap(i).Extension = WScript.Arguments(0)
aMimeMap(i).MimeType = WScript.Arguments(1)
MimeMapObj.PutEx ADS_PROPERTY_UPDATE, “MimeMap”, aMimeMap
MimeMapObj.SetInfo

WScript.Echo “MimeMap successfully added: ”
WScript.Echo ”    Extension: ” + WScript.Arguments(0)
WScript.Echo ”    Type:      ” + WScript.Arguments(1)If you copy and paste the code above into a VBS file and save it as ADDMIMETYPE.VBS, the syntax to add each type would be:

ADDMIMETYPE.VBS  .xap  application/x-silverlight-app ADDMIMETYPE.VBS  .xaml application/xaml+xmlADDMIMETYPE.VBS  .xbap application/x-ms-xbap

Using the IIS Manager User Interface in IIS 6.0 in Windows Server 2003

1. Go to Start\Administrative Tools and run IIS Manager. See the figure below:

2. Right click on the server name and select Properties. See the figure below:

3. In the Properties dialog box, click MIME Types. See the figure below:

4. In the MIME Types dialog box, click New. See the figure below:

5. In the MIME Types dialog box, enter one of these MIME types:

  • .xap     application/x-silverlight-app
  • .xaml    application/xaml+xml
  • .xbap    application/x-ms-xbap
  • See the figure below:

    For detailed information Click to visit http://silverlight.net and http://learn.iis.net/page.aspx/262/configuring-iis-for-silverlight-applications/

    Posted in ASP.NET, Silverlight | Tagged: , , , , | 1 Comment »

    Paging with Stored Procedure

    Posted by Viral Sarvaiya on September 6, 2010


    Lets consider a simple table called employee( emp_id, name, salary). Now, suppose that we need to create a gridview with paging. One option is to bring all the data from database and do the paging in client-side and another one is to do selective fetch. In both cases we can use a stored procedure that takes some parameter and returns a resultset.

    
    CREATE PROCEDURE GetEmployees
    @Status int,
    @StartIndex int,
    @PageSize int
    AS
    
    WITH FilteredList( [emp_id],[name], [salary], [RowNumber])
    AS
    (
    SELECT
    [emp_id],
    [name],
    [salary],
    ROW_NUMBER() OVER ( ORDER BY [ID] DESC) AS [RowNumber]
    
    FROM
    Employee
    )
    
    SELECT
    *
    FROM
    FilteredList
    WHERE
    RowNumber BETWEEN (@StartIndex + 1) AND (@StartIndex + @PageSize)
    
    

    Enjoy……

    Posted in Sql Server | Tagged: , , | 1 Comment »

     
    %d bloggers like this: