Code Simplified – Viral Sarvaiya

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

Posts Tagged ‘ASP.NET’

Arithmetic Captcha in asp.net

Posted by Viral Sarvaiya on November 22, 2010


Hi,
We know the captcha control, but now a day so many captcha code is available, most of the captcha is only for the text, but here I explain the new captcha that want human in intelligence as like arithmetic expression.
Create the new project,

Add a new file for create the captcha control named “captcha.aspx”.

In the page load of the captcha.aspx page.


protected void Page_Load(object sender, EventArgs e)
 {
 returnNumer();
 }

 void returnNumer()
 {
 Random num1 = new Random();
 Random num2 = new Random();
 int numQ1, numQ2;
 string QString;
 numQ1 = num1.Next(10, 15);
 numQ2 = num1.Next(17, 31);
 QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
 Session["answer"] = numQ1 + numQ2;

 Bitmap bitmap = new Bitmap(85,25);

 Graphics Grfx = Graphics.FromImage(bitmap);
 Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);
 Rectangle Rect = new Rectangle(100, 0, 0, 0);

 Grfx.FillRectangle(Brushes.Brown, Rect);
 Grfx.DrawRectangle(Pens.PeachPuff, Rect);
 // Border
 Grfx.DrawString(QString, font, Brushes.Azure, 0, 0);

 Response.ContentType = "Image/jpeg";
 bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

 bitmap.Dispose();
 Grfx.Dispose();
 }

Now in the default.aspx page take some control and 1 image control for the display captcha.


<body>
 <form id="form1" runat="server">
 <div>
 Are You Human?  <asp:image ID="Image1" runat="server" ImageUrl="Capcha.aspx" />
 <asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
 <br /><br />
 <asp:Button ID="Btnsubmit" runat="server" Text="Submit"  onclick="Btnsubmit_Click" /><br /><br />
 <asp:Label ID="lblValidate" runat="server"></asp:Label>
 </div>
 </form>
</body>

To check the input is valid or not, check the session value for the arithmetic expression.
So in default.aspx.cs file


protected void Page_Load(object sender, EventArgs e)
 {

 }
 protected void Btnsubmit_Click(object sender, EventArgs e)
 {
 if (Session["answer"] != null)
 {
 if (Session["answer"].ToString() == txtInput.Text)
 {
 lblValidate.Text = "Current Answer";
 }
 else
 {
 lblValidate.Text = "Incurrent Answer, Please input Valid Answer.";
 }
 }
 }

Now run the page

inter the result and click the button

if result is currect then


and if answer id not currect then,

Hope this will help you…

Thanks.

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

File Drag and Drop in Silverlight4

Posted by Viral Sarvaiya on November 2, 2010


Silverlight 4 have drag and drop functionality. here i demostrate that functionality.
first create new project named “DragAndDropImage”.
You have to add references “Microsoft.Expression.Interactions”, “system.windows.interactivity” and “system.windows.browser”

Silverlight is too fun, when coding gets this simple. So the image can now be dragged around. Now lets add the drop feature.

For making everything very simple, I will just now add AllowDrop=”True” and then add a drop handler to handle any file that is being dropped.

Now, lets move to the code behind. For demonstration purpose, I will use images from deviantArt gallery.

In DragAndDropImageTest.xaml file


<UserControl x:Class="SilverLightTest.DragAndDropImageTest"
 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"
 mc:Ignorable="d"
 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
 d:DesignHeight="300" d:DesignWidth="400">

 <Grid x:Name="LayoutRoot" AllowDrop="True" Drop="LayoutRoot_Drop" Background="Black">
 <StackPanel x:Name="DropCollection" Height="100" Margin="10,30,10,10" VerticalAlignment="Top" HorizontalAlignment="Center" Orientation="Horizontal">
 </StackPanel>
 <Image x:Name="DropImage" Margin="0,100,0,0" Width="400" Cursor="Hand">
 <i:Interaction.Behaviors>
 <ei:MouseDragElementBehavior ConstrainToParentBounds="True"></ei:MouseDragElementBehavior>
 </i:Interaction.Behaviors>
 </Image>
 </Grid>
</UserControl>

In DragAndDropImageTest.xaml.cs file


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 System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Windows.Browser;
using System.IO;

namespace SilverLightTest
{
 public partial class DragAndDropImageTest : UserControl
 {
 public DragAndDropImageTest()
 {
 InitializeComponent();
 }

 private void LayoutRoot_Drop(object sender, DragEventArgs e)
 {
 if (e.Data != null)
 {
 //reading the drop file
 FileInfo file = ((FileInfo[])e.Data.GetData(DataFormats.FileDrop)).FirstOrDefault();

 //creating a bitmapImage
 BitmapImage img = new BitmapImage();

 using (Stream s = file.OpenRead())
 {
 img.SetSource(s);
 }

 //setting the image in xaml
 DropImage.Source = img;

 Image newImage = new Image { Source = img };
 newImage.MouseLeftButtonDown += (a, b) =>
 {
 DropImage.Source = newImage.Source;
 };

 DropCollection.Children.Add(newImage);
 }
 }
 }
}

Run the application and check with dropping the image file in browser.

 

Enjoy Coding…..

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

Beginners Guide to Visual Studio LightSwitch

Posted by Viral Sarvaiya on October 26, 2010


SIMPLEST WAY TO BUILD BUSINESS APPLICATIONS FOR THE DESKTOP, WEB AND CLOUD

Microsoft Visual Studio LightSwitch gives you a simpler and faster way to create professional-quality business applications for the desktop, the web, and the cloud. LightSwitch is a new addition to the Visual Studio family. Visit this page often to learn more about this exciting product.

Visual Studio LightSwitch is a new tool for building data-driven Silverlight Application using Visual Studio IDE. It automatically generates the User Interface for a DataSource without writing any code. You can write a small amount of code also to meet your requirement.

Fore More Details :

http://www.microsoft.com/visualstudio/en-us/lightswitch

http://msdn.microsoft.com/hi-in/lightswitch/default%28en-us%29.aspx

Make a simple application demo…

http://www.silverlightshow.net/items/Beginners-Guide-to-Visual-Studio-LightSwitch-Part-1.aspx

http://www.silverlightshow.net/items/Beginners-Guide-to-Visual-Studio-LightSwitch-Part-2.aspx

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

Simple Data Binding in Silverlight

Posted by Viral Sarvaiya on October 1, 2010


Simple Data Binding in Silverlight
To help explain data binding in Silverlight, let’s build a very simple application. The application will include a Book object that contains two properties: Title and ISBN. These properties will be bound to two TextBox controls.

1.  Create a new Silverlight application in Visual Studio 2010. Name the project BasicDataBinding, and allow Visual Studio to create a Web application project to host your application.

2. Edit the MainPage.xaml file to define two columns and six grid rows. Place a TextBlock in each row in column 1 and a TextBox in each row in column 2. Also add some margins and some alignment assignments to improve the layout.

The code for the page follows:


<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Book Title"
VerticalAlignment="Center"
Margin="5" />
<TextBlock Text="ISBN-13"
VerticalAlignment="Center"
Margin="5"
Grid.Row="1" />
<TextBox Text="{Binding Title}"
Height="24"
Margin="5"
Grid.Column="1" />
<TextBox Text="{Binding ISBN}"
Height="24"
Margin="5"
Grid.Column="1" Grid.Row="1" />
<TextBlock Text="Book Title"
VerticalAlignment="Center"
Margin="5"
Grid.Row="2" />
<TextBlock Text="ISBN-13"
VerticalAlignment="Center"
Margin="5"
Grid.Row="3" />

<TextBox Text="{Binding Title}"
Height="24"
Margin="5"
Grid.Column="1" Grid.Row="2" />
<TextBox Text="{Binding ISBN}"
Height="24"
Margin="5"
Grid.Column="1" Grid.Row="3" />

</Grid>

3. Next, edit the code behind, MainPage.xaml.cs. Add a Loaded event handler for the application, which will fire when the application is loaded by the client. This is accomplished with the following source code:


public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}

void Page_Loaded(object sender, RoutedEventArgs e)
{

}
}

Now you need to add a class to define a Book object. Below the MainPage class, add the following class definition:


namespace BasicDataBinding
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
}
}
public class Book
{
public string Title { get; set; }
public string ISBN { get; set; }
}
}

4. Now that you have Book defined, you need to create an instance of Book and set it to the LayoutRoot’s DataContext, as follows:


void Page_Loaded(object sender, RoutedEventArgs e)
{
Book b = new Book()
{
Title = "Beginning Silverlight 4: From Novice to Professional",
ISBN = "978-1430229889"
};
this.LayoutRoot.DataContext = b;
}

When you set up binding definitions for different controls, the controls do not know where they are going to get their data. The DataContext property sets the data context for a control that is participating in data binding.The  DataContext property can be set directly on the control. If a given control does not have a DataContext property specified, it will look to its parent for its data context. The nice thing about this model is that if you look above in the XAML for the page, you will see little indication of where the controls are getting their data. This provides an extreme level of code separation, allowing designers to design XAML UIs and developers to work alongside the designers, defining the specifics of how the controls are bound to their data sources.

5. At this point, you can go ahead and start debugging the application. If all goes well, you will see the four text boxes populated with the data from the Book’s instance

6.  With the application running, change the book title in the first text box to just “Beginning Silverlight,” by removing the “From Novice to Professional.” You might expect that, since the third text box is bound to the same data, it will automatically update to reflect this change. However, a couple of things need to be done to get this type of two-way binding to work. One problem is that, currently, the Book class does not support notifying bound clients of changes to its properties. In other words, when a property changes in Book, the class will not notify the TextBox instances that are bound to the class of the change. You could take care of this by creating a change event for each property. This is far from ideal; fortunately, there is an interface that a class can implement that handles this for you. This interface is known as INotifyPropertyChanged. Let’s use it.

7.  Modify the Book class definition to inherit from INotifyPropertyChanged. Notice that when you inherit from INotifyPropertyChanged, you need to add using System.ComponentModel. Luckily, Visual Studio will help you with this.

Next, you can let Visual Studio do some more work for you. After adding the using System.ComponentModel statement, right-click INotifyPropertyChanged and select Implement Interface ➤ Implement Interface from the pop-up menu

Now Visual Studio has added a new public event to your class:


public class Book : INotifyPropertyChanged
{
public string Title { get; set; }
public string ISBN { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}

8. Next, you need to create a convenience method that will fire the PropertyChanged event. Call it FirePropertyChanged, as shown in the following code:


public class Book : INotifyPropertyChanged
{
public string Title { get; set; }
public string ISBN { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
void FirePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(property));
}
}
}

9. Now you need to extend the simplified properties by adding private members and full get/set definitions to define the get and set operations, as shown in the following code. The get is just like a normal get operation, where you simply return the internal member value. For the set, you first set the internal member value, and then call the FirePropertyChanged method, passing it the name of the property.


public class Book : INotifyPropertyChanged
{
private string _title;
private string _isbn;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
FirePropertyChanged("Title");
}
}
public string ISBN
{
get
{
return _isbn;
}
set
{
_isbn = value;
FirePropertyChanged("ISBN");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void FirePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(property));
}
}
}

With this completed, your class is set up to notify bound clients of changes to the Title and ISBN properties. But you still need to take one more step. By default, when you bind a source to a target, the BindingMode is set to OneWay binding, which means that the source will send the data to the target, but the target will not send data changes back to the source. In order to get the target to update the source, you need to implement two-way (TwoWay) binding.

10. To change to two-way binding, add the Mode=TwoWay parameter when defining the {Binding} on a control, as follows:


<TextBlock Text="Book Title"
VerticalAlignment="Center"
Margin="5" />
<TextBlock Text="ISBN-13"
VerticalAlignment="Center"
Margin="5"
Grid.Row="1" />
<TextBox Text="{Binding Title, Mode=TwoWay}"
Height="24"
Margin="5"
Grid.Column="1" />
<TextBox Text="{Binding ISBN, Mode=TwoWay}"
Height="24"
Margin="5"
Grid.Column="1" Grid.Row="1" />
<TextBlock Text="Book Title"
VerticalAlignment="Center"
Margin="5"
Grid.Row="2" />
<TextBlock Text="ISBN-13"
VerticalAlignment="Center"
Margin="5"
Grid.Row="3" />
<TextBox Text="{Binding Title, Mode=TwoWay}"
Height="24"
Margin="5"
Grid.Column="1" Grid.Row="2" />
<TextBox Text="{Binding ISBN, Mode=TwoWay}"
Height="24"
Margin="5"
Grid.Column="1" Grid.Row="3" />

11.  Rebuild and run your application. Update any of the fields, and leave the focus on the control. You’ll see that the two-way binding is triggered, and the corresponding field is also updated,

Congratulations! You have just created a Silverlight application that allows for two-way data binding.

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

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

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 »

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 »

    Cookies in silverlight

    Posted by Viral Sarvaiya on August 27, 2010


    hello friends…

    here i demonstrate how to set the cookies and get the values of the cookies and set the values of the cookies in the silverlight. for that i am making 2 function named GetCookie() and SetCookie().

    in my project i have 2 textbox for the key and the value of the cookies then 1 button that set the value of the cookies by the key and then one button that show the cookies value by the key.

    Note : For using the cookie, you have to add namespance “System.Windows.Browser”.

    Step 1 : Create new silverlight project.

    Step 2 : in mainpage.xaml file

    
    <UserControl x:Class="SilverlightCookies.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"
     mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
     <Grid x:Name="LayoutRoot" ShowGridLines="True">
     <Grid.ColumnDefinitions>
     <ColumnDefinition Width="400"></ColumnDefinition>
     <ColumnDefinition Width="200"></ColumnDefinition>
     </Grid.ColumnDefinitions>
     <Grid.RowDefinitions>
     <RowDefinition Height="200"></RowDefinition>
     <RowDefinition Height="200"></RowDefinition>
     <RowDefinition Height="200"></RowDefinition>
     </Grid.RowDefinitions>
    
     <TextBlock Name="lblKey" Text="Key : " Grid.Column="0" Height="30" Grid.Row="0"></TextBlock>
     <TextBox Name="txtCookieskey" Grid.Column="0" Grid.Row="0" Width="200" Height="30" Margin="0,0,0,0"></TextBox>
     <TextBlock Name="lblValue" Text="Value : " Grid.Column="0" Height="30" Grid.Row="0" Margin="0,70,0,0"></TextBlock>
     <TextBox Name="txtCookiesValue" Grid.Column="0" Grid.Row="0" Width="200" Height="30" Margin="0,70,0,0"></TextBox>
     <Button Name="btnSetCookies" Grid.Column="0" Grid.Row="1" Content="Set Cookies" Width="100" Height="30" Click="Button_Click"></Button>
     <TextBlock Name="LblCookies" Grid.Column="0" Grid.Row="2"></TextBlock>
    
     <Button Name="btnGetCookies" Grid.Column="1" Grid.Row="0" Content="Get Cookies" Width="100" Height="30" Click="Button_Click_1"></Button>
     <TextBlock Name="LblDisplayCookies" Grid.Column="1" Grid.Row="1" Width="auto" Height="auto"></TextBlock>
    
     </Grid>
    </UserControl>
    
    

    Step 3 : my mainpage.xaml.cs file

    
    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 System.Windows.Browser;
    namespace SilverlightCookies
    {
     public partial class MainPage : UserControl
     {
     public MainPage()
     {
     InitializeComponent();
     }
    
     private void SetCookie(string key, string value)
     {
    
     DateTime expireDate = DateTime.Now + TimeSpan.FromHours(1);
     string newCookie = key + "=" + value + ";expires=" + expireDate.ToString("R");
     HtmlPage.Document.SetProperty("cookie", newCookie);
     }
    
     private string GetCookie(string key)
     {
     string[] cookies = HtmlPage.Document.Cookies.Split(';');
     foreach (string cookie in cookies)
     {
     string[] keyValue = cookie.Split('=');
     if (keyValue.Length == 2)
     {
     if (keyValue[0].ToString().Trim() == key.Trim())
     return keyValue[1];
     }
     }
     return null;
     }
    
     private void Button_Click(object sender, RoutedEventArgs e)
     {
     SetCookie(txtCookieskey.Text.Trim(), txtCookiesValue.Text.Trim());
     LblCookies.Text = "Cookes has been Created";
     }
    
     private void Button_Click_1(object sender, RoutedEventArgs e)
     {
     LblDisplayCookies.Text = GetCookie(txtCookieskey.Text.Trim());
     LblCookies.Text = "Display Cookies of " + txtCookieskey.Text;
     }
     }
    }
    
    

    Step 4 : Run the application…

    for this you get 2 textbox and 2 button.

    when i input the key and value in the textbox and press button of “Set Cookies”, it set the key of cookies by that value and when i click on “get Cookies” by typing key value in key textbox, it show me the value of the key in cookie.

    Enjoy Coding……..

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

    Use of WCF Service in Silverlight

    Posted by Viral Sarvaiya on August 26, 2010


    hello friends….

    what is WCF? see the link – https://viralsarvaiya.wordpress.com/2009/11/18/windows-communication-foundation/

    Here i demonstrate the use of the WCF Service in silverlight.

    what is WCF so refer this

    please confirm that silverlight 3 or 4 and silverlight tool kit is installed in your PC.

    Step 1: Create New Silverlight Project.

    In Visual Studio2008 or 2010, file menu -> New -> project.

    Select Silverlight application, give name of project as “SilverlightTesingService” and open the project.

    then check the checkbox true of the host the silverlight application in web site.

    Now you have 2 projects in your soluion.

    Step 2 : Create Wcf Service

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

    choose silverlight in left panel and choose Silverlight-enable WCF Service. then give name “TestService.svc”.

    so Service has been added to project

    in the TestService.svc.cs file write the following

    
    using System;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.Collections.Generic;
    using System.Text;
    
    namespace SilverlightTesingService.Web
    {
     [ServiceContract(Namespace = "")]
     interface IService1
     {
     [OperationContract]
     Users GetUsers(int id);
     }
    
     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     public class TestService : IService1
     {
     #region IService1 Members
    
     Users IService1.GetUsers(int id)
     {
     if (id == 1)
     return new Users() { IsMember = true, Name = "Viral", age = 27 };
     else if (id == 2)
     return new Users() { IsMember = true, Name = "Malhar", age = 24 };
     else
     return new Users() { IsMember = false, Name = "There is no user there", age = 0 };
     }
    
     #endregion
     }
    
     public class Users
     {
     public bool IsMember { get; set; }
     public string Name { get; set; }
     public int age { get; set; }
     }
    }
    
    

    Step 3 : clientaccesspolicy.xml File

    Now for the allowing cross domain access we have to put the clientaccesspolicy.xml file to the SilverlightTesingService.web folder.

    For more information of this file click to http://msdn.microsoft.com/en-us/library/cc197955%28VS.95%29.aspx

    clientaccesspolicy.xml as below

    
    <?xml version="1.0" encoding="utf-8" ?>
    <access-policy>
     <cross-domain-access>
     <policy>
     <allow-from http-request-headers="*">
     <domain uri="*"/>
     </allow-from>
     <grant-to>
     <resource path="/" include-subpaths="true"/>
     </grant-to>
     </policy>
     </cross-domain-access>
    </access-policy>
    
    

    Step 4: Web.config file change

    Now we have to consider that web.config file have defined end point

    put this in between  configuration tag

    
    <system.serviceModel>
     <behaviors>
     <serviceBehaviors>
     <behavior name="SilverlightTesingService.Web.TestServiceBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
     </behavior>
     </serviceBehaviors>
     </behaviors>
     <bindings>
     <customBinding>
     <binding name="customBinding0">
     <binaryMessageEncoding />
     <httpTransport />
     </binding>
     </customBinding>
     </bindings>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
     <services>
     <service behaviorConfiguration="SilverlightTesingService.Web.TestServiceBehavior" name="SilverlightTesingService.Web.TestService">
     <endpoint address="" binding="basicHttpBinding" contract="SilverlightTesingService.Web.IService1" />
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
     </service>
     </services>
     </system.serviceModel>
    
    

    Step 5 : Add Service to Silverlight Application

    To add the service you require first build the SilverlightTesingService.web project.

    Now in the SilverlightTesingService project

    right click to project -> add the Service References

    New dialog box open . click to discover button. and select the TestService.svc

    and give name of the service and click ok.

    Service Reference folder has been added and the service has been added to this folder.

    Step 6: Use of the WCF Service

    in the mainpage.xaml take 2 textbox and 1 button as follow

    
    <UserControl x:Class="SilverlightTesingService.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"
     mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
     <Grid x:Name="LayoutRoot">
     <TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
     <TextBox Height="23" HorizontalAlignment="Left" Margin="12,86,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
     <Button Content="Button" Height="23" HorizontalAlignment="Left" Click="button1_Click" Margin="12,49,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
     </Grid>
    </UserControl>
    
    

    now in mainpage.xaml.cs file make the object of the service client.

    after that make the completed event when that service call that function will call

    and last when this service call is written

    see the mainpage.xaml.cs file

    
    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;
    
    namespace SilverlightTesingService
    {
     public partial class MainPage : UserControl
     {
     TestService.Service1Client ObjClient; //make the object of the service
     public MainPage()
     {
     InitializeComponent();
     ObjClient = new SilverlightTesingService.TestService.Service1Client();  //mamory allocation of the service object
     ObjClient.GetUsersCompleted += new EventHandler<SilverlightTesingService.TestService.GetUsersCompletedEventArgs>(ObjClient_GetUsersCompleted);  //make the completed event of the service
     }
    
     void ObjClient_GetUsersCompleted(object sender, SilverlightTesingService.TestService.GetUsersCompletedEventArgs e)
     {
     textBox2.Text = e.Result.Name.ToString();
     }
    
     protected void button1_Click(object sender, EventArgs e)
     {
     ObjClient.GetUsersAsync(Convert.ToInt32(textBox1.Text)); // calling the service's function with the parameter
     }
     }
    }
    
    

    Step 7 : Run the application

    when you add integer 1 in the first textbox and click to button the service will call……

    Enjoy the WCF service……

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

    Background Image in PDF File with ItextSharp in Asp.Net

    Posted by Viral Sarvaiya on May 11, 2010


    my past post https://viralsarvaiya.wordpress.com/2009/07/08/make-a-pdf-file-from-asp-net/ is demonstrate how to develop the pdf file, but when i search in web that have less example for the image in background.

    here i demonstrate how to set image in background in pdf file.

    step 1 :

    follow the link to create the pdf : https://viralsarvaiya.wordpress.com/2009/07/08/make-a-pdf-file-from-asp-net/

    stpe 2 :

    here i put the whole code for the image in background.

    dont forget to download and put the itextsharp.dll file in bin folder.

    
    void makePDF()
     {
     Response.ContentType = "application/pdf";
    
     Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
    
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
     string imageFilePath = Server.MapPath(".") + "/images/test.jpg";
    
     iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
    
     // Page site and margin left, right, top, bottom is defined
     Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    
     //Resize image depend upon your need
     //For give the size to image
     jpg.ScaleToFit(3000, 770);
    
     //If you want to choose image as background then,
    
     jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
    
     //If you want to give absolute/specified fix position to image.
     jpg.SetAbsolutePosition(7, 69);
    
     PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    
     pdfDoc.Open();
    
     pdfDoc.NewPage();
    
     Paragraph paragraph = new Paragraph("this is the testing text for demonstrate the image is in background \n\n\n this is the testing text for demonstrate the image is in background");
    
     pdfDoc.Add(jpg);
    
     pdfDoc.Add(paragraph);
    
     pdfDoc.Close();
    
     Response.Write(pdfDoc);
    
     Response.End();
     }
    

    for more knowledge of itextsharp :
    http://somewebguy.wordpress.com/2009/05/08/itextsharp-simplify-your-html-to-pdf-creation/

    http://xpode.com/ShowArticle.aspx?ArticleId=134

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

     
    %d bloggers like this: