Code Simplified – Viral Sarvaiya

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

Archive for August, 2010

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 »

Read XML in Silverlight

Posted by Viral Sarvaiya on August 25, 2010


XML is an important medium in the world of Silverlight especially where Web Services are involved.  The .NET 3.5 that comes with Silverlight omits some of the core XML objects that you will find in the full incarnation of .NET 3.5.  There is however the XML Reader and Writer classes that allow you high speed access to reading and writing XML documents.  In our sample on this page we use an XML reader to read a simple XML file and render the results to the page.

Our example XML file looks like this, as you can:

<?xml version="1.0"?>
<customers>
 <customer id="10001" first="John" last="Smith" company="Donuts plc">jsmith@mymail.com</customer>
 <customer id="10002" first="Rete" last="Bandy" company="This Is Bloggers Co.">rete@superbloggers.com</customer>
 <customer id="10003" first="James" last="Bird" company="Timestone">james.bird@timestone.co.uk</customer>
 <customer id="10004" first="Sarah" last="McCauly" company="Automated Snowmen Ltd">smccauly@automatedsnowmen.com</customer>
 <customer id="10005" first="Pete" last="Rowan" company="Cooltec Consultants">pete.rowan@cooltec.com</customer>
</customers>

Now add a Listbox to usercontrol

<UserControl x:Class="XMLTutorial.Page"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Width="400" Height="300">
 <Grid x:Name="LayoutRoot" Background="White">
 <ListBox x:Name="customersList" Width="400" Height="200" />
 </Grid>
</UserControl>
Now in usercontrol’s C# file
public partial class Page : UserControl
 {
 public Page()
 {
 InitializeComponent();

 PopulateCustomersList();
 }

 private void PopulateCustomersList()
 {
 XmlReaderSettings settings = new XmlReaderSettings();
 settings.XmlResolver = new XmlXapResolver();
 XmlReader reader = XmlReader.Create("Customers.xml");

 reader.MoveToContent();

 while (reader.Read())
 {
 if (reader.NodeType == XmlNodeType.Element && reader.Name == "customer")
 {
 customersList.Items.Add(new ListBoxItem() { Content = reader.GetAttribute("last") +
 ", " + reader.GetAttribute("first") + " (" + reader.ReadInnerXml() + ")" });
 }

 if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "customers")
 {
 break;
 }
 }

 reader.Close();
 }
 }
Enjoy Coding…….

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

Request Validation – Preventing Script Attacks – Not Allowd html tags in textbox

Posted by Viral Sarvaiya on August 20, 2010


By default, the application is prevented from processing unencoded HTML content submitted to the server (it means page validaterequest=true & it help us to prevent script attacks ).

This request validation feature can be disabled when the application has been designed to safely process HTML data. When ever you work with DotNetNuke this feature is disabled by default.

Now question comes in mind that in such cases how to “Preventing Script Attacks”.

One solution can “stop submitting input that contains such scripts or we can say html tags”.
so that we can prevent script attack.

Here is one solution using RegularExpressionValidator.

Suppose we are having textbox that takes some input text from the user & we do not want them to type any html tags than here is the code for that :

<asp:TextBox runat="server" ID="txtName"></asp:TextBox>

<asp:RegularExpressionValidator runat="server" ID="regName" ControlToValidate="txtName" Display="Dynamic" ValidationGroup="Employeevalgrp" ValidationExpression="^[^<>]+$" ErrorMessage="Html tags are not allowed."/>

<asp:Button runat="server" ID="btnSaveEmployeeInfo" ValidationGroup="Employeevalgrp"
 CausesValidation="true" OnClick="btnSaveEmployeeInfo_Click" />

Here when user press button, validator will validate the input text & submit the text only if it passes thru the validation test.

Here I must say that we are not validating request, we are just validating input that is going to be submitted to the server.

Thanks Sandeep to give a such a wonderful help……

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

Microsoft DOS tracert command

Posted by Viral Sarvaiya on August 12, 2010


About

The tracert command is used to visually see a network packet being sent and received and the amount of hops required for that packet to get to its destination.

Availability

MS-DOS 6.2
Windows 95
Windows 98
Windows ME
Windows NT
Windows 2000
Windows XP
Windows Vista
Windows 7

Sysntex

tracert    [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name

Options

-d  : Do not resolve addresses to hostnames.
-h  : maximum_hops    Maximum number of hops to search for target.
-j  : host-list    Loose source route along host-list.
-w  : timeout    Wait timeout milliseconds for each reply.

Example

C:\>tracert viralsarvaiya.wordpress.com

Tracing route to lb.wordpress.com [76.74.254.120]
over a maximum of 30 hops:

1     1 ms    <1 ms    <1 ms  192.168.2.1
2     4 ms     1 ms     1 ms  120.72.89.81
3     3 ms     2 ms     1 ms  59.145.238.93
4    10 ms    10 ms    10 ms  61.95.151.170
5    12 ms    11 ms    15 ms  61.95.151.170
6   255 ms   255 ms   255 ms  aes-static-122.36.144.59.airtel.in [59.144.36.122]
7   289 ms   255 ms   255 ms  xe-9-1-0.edge1.losangeles6.level3.net [4.26.0.61]
8   267 ms   263 ms   271 ms  ae-82-80.ebr2.losangeles1.level3.net [4.69.144.179]
9   288 ms   289 ms   287 ms  ae-3-3.ebr3.dallas1.level3.net [4.69.132.78]
10   292 ms   293 ms   291 ms  ae-1-60.edge9.dallas1.level3.net [4.69.145.16]
11   299 ms   298 ms   297 ms  peer-1-netw.edge9.dallas1.level3.net [4.59.118.6]
12   300 ms   299 ms   299 ms  10ge-ten1-3.sat-8500v-cor-2.peer1.net [216.187.124.178]
13   299 ms   300 ms   297 ms  216.187.124.110
14   296 ms   312 ms   300 ms  wordpress.com [76.74.254.120]

Trace complete.

Thanks You.

Posted in General | Tagged: , , , , | Leave a Comment »

Event Delegation in asp.net

Posted by Viral Sarvaiya on August 10, 2010


Hear i m demonstrate the Event delegation in asp.net.

I am developing a simple asp.net project that handle the event of the web user control to the aspx page.

in simple means click event of the web user control’s button is handle in aspx page.

Create new website. there are default.aspx page

Add new Web User Control named “EventControl.ascx”

in the EventControl.ascx page write the following code.

<table border="1">
 <tr>
<td>
This is the Web User Control
</td>
 </tr>
 <tr>
<td>
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClick="btn1_Click"></asp:Button>
</td>
 </tr>
</table>

in the EventControl.ascx.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class EventControl : System.Web.UI.UserControl
{
public delegate void BtnSubmitClickEventHandler(object sender, EventArgs e);
public event BtnSubmitClickEventHandler BtnSubmitClickEvent;

protected void btn1_Click(object sender, EventArgs e)
{
BtnSubmitClickEvent(sender, e);
}
}

means we have created event delegate in the EventControl.ascx.cs page now we can code it to default.aspx page.

means in the click event of the EventControl.ascx is written in the default.aspx page.

Now In the Default.aspx file


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="EventControl.ascx" TagName="EventControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <table>
 <tr>
 <td>
 Example of the Event Deligation
 </td>
 </tr>
 <tr>
 <td>
 <uc1:EventControl ID="EventControl1" runat="server" />
 </td>
 </tr>
 <tr>
 <td>
 <h3>
 this is the page 1</h3>
 </td>
 </tr>
 <tr>
 <td>
 <asp:Label ID="lblPrint" runat="server"></asp:Label>
 </td>
 </tr>
 </table>
 </div>
 </form>
</body>
</html>

now in the default.aspx.cs file. we are creating the handler of the event

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 EventControl1.BtnSubmitClickEvent += new EventControl.BtnSubmitClickEventHandler(EventControl1_BtnSubmitClickEvent);
 }

 void EventControl1_BtnSubmitClickEvent(object sender, EventArgs e)
 {
 lblPrint.Text = "This Function is call From Event Delegation.";
 }
}

For this you can create your own delegate.

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