Thursday, December 10, 2009

How to create Dynamic Gridview in ASP.NET


Many times we have the requirement where we have to create columns dynamically.
This article describes you about the dynamic loading of data using the DataTable as the datasource.


Details of the Grid


Let?s have a look at the code to understand better.



Create a gridview in the page,

Drag and drop the GridView on to the page
Or

Manually type GridView definition in the page.
public partial class _Default : System.Web.UI.Page

{

#region constants

const string NAME = "NAME";

const string ID = "ID";

Tuesday, September 8, 2009

Very important Please Do Read - Indian Economy is Going Down

Dear Friends,

U CAN MAKE A HUGE DIFFERENCE TO THE INDIAN ECONOMY BY FOLLOWING FEW SIMPLE STEPS.

Please spare a couple of minutes here... for the sake of India .... our country.

I got this article from one of my friends, but it's true, I can see this in day to day life,Small example, Before 5 months 1 US $ = IND Rs 39After 5 months.

Now it is 1 $ = IND Rs 50Do you think US Economy is booming? No, but Indian Economy is Going Down.Our Economy is in u'r handsINDIAN economy is in a crisis.

Our country like many other ASIAN countries is undergoing a severe economic crunch.

Many INDIAN industries are closing down. The INDIAN economy is in a crisis and if we do not take proper steps to control those, we will be in a critical situation. More than 30000 crore rupees of foreign exchange are being siphoned out of our country on products such as cosmetics, snacks, tea, beverages... etc which are grown, produced and consumed here.

A cold drink that costs only 70 / 80 paisa to produce is sold for NINE rupees, and a major chunk of profits from these are sent abroad. This is a serious drain on INDIAN economy. We have nothing against Multinational companies, but to protect our own interests we request everybody to use INDIAN products only for next two years.

With the rise in petrol prices, if we do not do this, the rupee will devalue further and we will end up paying much more for the same products in the near future. What you can do about it?1. Buy only products manufactured by WHOLLY INDIAN COMPANIES.

2. ENROLL as many people as possible for this cause.Each individual should become a leader for this awareness.This is the only way to save our country from severe economic crisis. You don't need to give-up your lifestyle. You just need to choose an alternate product.

All categories of products are available from WHOLLY INDIAN COMPANIES.

LIST OF PRODUCTSCOLD DRINKS: USE: -

LEMON JUICE, FRESH FRUIT JUICES, CHILLED LASSI (SWEET OR SOUR), BUTTER MILK, COCONUT WATER, JALJEERA, ENERJEE, and MASALA MILK...

INSTEAD OF: - COCA COLA, PEPSI, LIMCA, MIRINDA, SPRITE

BATHING SOAP: USE - CINTHOL & OTHER GODREJ BRANDS, SANTOOR, WIPRO SHIKAKAI, MYSORE SANDAL, MARGO, NEEM, EVITA, MEDIMIX, GANGA , NIRMA BATH & CHANDRIKA

INSTEAD OF - LUX, LIFEBOY, REXONA, LIRIL, DOVE, PEARS, HAMAM, LESANCY, CAMAY, PALMOLIVE

TOOTH PASTE: - USE - NEEM, BABOOL, PROMISE, VICO VAJRADANTI, PRUDENT, DABUR PRODUCTS, MISWAK

INSTEAD OF - COLGATE, CLOSE UP, PEPSODENT, CIBACA, FORHANS, MENTADENT.

TOOTH BRUSH: - USE – PRUDENT, AJANTA , PROMISE

INSTEAD OF - COLGATE, CLOSE UP, PEPSODENT, FORHANS, ORAL-B

SHAVING CREAM: USE - GODREJ, EMANI

INSTEAD OF - PALMOLIVE, OLD SPICE, GILLETE

BLADE:- USE - SUPERMAX, TOPAZ, LAZER, ASHOKA

INSTEAD OF - SEVEN-O -CLOCK, 365, GILLETTE

TALCUM POWDER: USE - SANTOOR, GOKUL, CINTHOL, WIPRO BABY POWDER, BOROPLUS

INSTEAD OF - PONDS, OLD SPICE, JOHNSON BABY POWDER, SHOWER TO SHOWER

MILK POWDER: USE - INDIANA, AMUL, AMULYA

INSTEAD OF - ANIKSPRAY, MILKANA, EVERYDAY MILK, MILKMAID.

SHAMPOO: USE - LAKME, NIRMA, VELVET

INSTEAD OF - HALO, ALL CLEAR, NYLE, SUNSILK, HEAD AND SHOULDERS, PANTENE

MOBILE CONNECTIONS: USE - BSNL, AIRTEL

INSTEAD OF - HUTCH

Every INDIAN product you buy makes a big difference. It saves INDIA ...

Let us take a firm decision today.

BUY INDIAN TO BE INDIAN we are not against of foreign products.

WE ARE NOT ANTI-MULTINATIONAL..WE ARE TRYING TO SAVE OUR NATION.

EVERY DAY IS A STRUGGLE FOR A REAL FREEDOM.

WE ACHIEVED OUR INDEPENDENCE AFTER LOSING MANY LIVES.

THEY DIED PAINFULLY TO ENSURE THAT WE LIVE PEACEFULLY.

THE CURRENT TREND IS VERY THREATENING.

MULTINATIONALS CALL IT GLOBALISATION OF INDIAN ECONOMY.

FOR INDIANS LIKE YOU AND ME IT IS RECOLONISATION OF INDIA ....

THE COLONIST'S LEFT INDIA THEN. BUT THIS TIME THEY WILL MAKE SURE THEY DON'T MAKE ANY MISTAKES.WHO WOULD LIKE TO LET A" GOOSE THAT LAYS GOLDEN EGGS" SLIP AWAY.

PLEASE REMEMBER: POLITICAL FREEDOM IS USELESS WITHOUT ECONOMIC INDEPENDENCE .RUSSIA , S.KOREA , MEXICO ..........THE LIST IS VERY LONG!!LET US LEARN FROM THEIR EXPERIENCE AND FROM OUR HISTORY.

LET US DO THE DUTY OF EVERY TRUE INDIAN.

FINALLY: IT'S OBVIOUS THAT U CAN'T GIVE UP ALL OF THE ITEMS MENTIONED ABOVE,SO GIVE UP ATLEAST ONE ITEM TO FOR THE SAKE OF OUR COUNTRY.

"LITTLE DROPS MAKE A GREAT OCEAN "

JAI HIND

JAI HIND

JAI HIND With Love and Affection Indian

M.K.Kannan..

Tuesday, June 23, 2009

ObjectDataSource

1. Introduction
This document provides details regarding how to use objectdatasource control in
asp.net application for grid view paging using select method.

2. What is ObjectDataSource?
ObjectDataSource is a non-display control in ASP.NET 2.0 that acts as a bridge
between your data-access objects and data-bound controls on the web page.
ObjectDataSource helps the developer to reduce the code to bind data to data-bound
controls. ObjectDataSource works in stateless mode like the web itself.
ObjectDataSource can be used for CRUD operations (Create, Retrieve, Update, and
Delete). If you use ObjectDataSource to display data in the asp.net page, it calls the
‘select’ method to create an object, reads the properties from that object for the
data-bound control and disposes it before the page has completed. This article
provides a clear description of using ObjectDataSource to bind data to grid view and
paging logic.
3. How to use ObjectDataSource?
Create an ASP.NET website naming ObjectDataSourceDemo for instance. In this
sample I have used enterprise library for establishing database connection. If you are
not familiar with enterprise library you can use your own way to establish connection
to database. In the aspx page just add a grid view and an objectdatasource control
like the code below.
AutoGenerateColumns="false" AllowPaging="true" Width="835px"
OnDataBound="dgvRequests_DataBound" ShowFooter="True">

runat="server" SelectCountMethod="SelectCount" EnablePaging="true"
SelectMethod="GetRequest" TypeName="RequestData">

Set the DataSourceId property of grid view as the id of the ObjectDataSource,
In our case it is ‘objRequest’, and AllowPaging and ShowFooter to true.
Here let us know certain properties of ObjectDataSource before using them.


EnablePaging :
Gets or sets a value indicating whether the ObjectDataSource control has data
caching enabled.


SelectMethod :
Gets or sets the name of the method or function that the ObjectDataSource control
invokes to retrieve data.


SelectCountMethod:
Gets or sets the name of the method or function that the ObjectDataSource control
invokes to retrieve a row count.


TypeName:
To create an instance of the object that the ObjectDataSource control binds to, the
control uses reflection to load the type that is identified by the type name at run time.
Therefore, the value of the TypeName property can be a partially qualified type for code
that is located in the Bin or App_Code directories or a fully qualified type name for code
that is registered in the global assembly cache. If you use the global assembly cache, you
must add the appropriate reference to the assemblies section of the Machine.config or
Web.config file.


In this example I have added a class RequestData.cs in App_Code directory and so the
TypeName is specified as above. Fully qualified class name that is “namespace.Classname”
can be given in this property if the class is not placed in App_Code directory.
Let’s have a look at the SelectMethod.


public DataTable GetRequest(int maximumRows, int
startRowIndex,ObjectDataSourceSelectingEventArgs e)
{
DataTable dtRequest = null;
objBus = new objBusiness();
dtRequest = objBus.GetRequestDetail(out totalPage).Tables[0];
if (dtRequest != null && dtRequest.Rows.Count > 0)
{
Page 5 of 8
e.Arguments.TotalRowCount = totalPage;
}
return dtRequest;
}


The selectMethod must have maximumRows, startRowIndex as arguments as shown
above and return type as Datatable. GetRequestDetail is the method in base class used to
get the data from database and totalPage is the out variable of the method is the total
number of records that is to be returned from the procedure, ‘objBus’ is the instance of the
business class in order to use the method.


The ObjectDataSourceSelectingEventArgs class is used in the OnSelecting method. Because
it is derived from the ObjectDataSourceMethodEventArgs class, the
ObjectDataSourceSelectingEventArgs class provides access to input parameters for
validation and manipulation through the InputParameters property. The
ObjectDataSourceSelectingEventArgs class also provides the ExecutingSelectCount
property, which is used to check whether the currently executing data retrieval operation is
retrieving a row count, in addition to the data. This is important because when data source
paging is enabled, the Selecting event is raised twice. For more information, see
ExecutingSelectCount.


To add the argument ‘e’ in the selectMethod we have added it in InputParameters. If you
need to pass any argument in select method it is necessary to add it in OnSelecting event of
the ObjectDataSource.


public void objRequest_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (!e.ExecutingSelectCount)
{
e.Arguments.MaximumRows = dgvRequests.PageSize;
e.Arguments.RetrieveTotalRowCount = true;
e.InputParameters.Add("e", e);
}
}


The SelectCountMethod in the App_Code just returns the row count as shown
below.


public int SelectCount(ObjectDataSourceSelectingEventArgs e)
{
return e.Arguments.TotalRowCount;
}




To display the page count in the footer of grid view add a label in Footer template of the
grid view and assign the value in DataBound event of the grid view like the code below.
protected void dgvRequests_DataBound(object sender, EventArgs e)
{
if (dgvRequests.Rows.Count > 0)
{
lblpageString = (Label)dgvRequests.FooterRow.FindControl("lblPageString");
if (lblpageString != null)
lblpageString.Text = string.Format("Page {0} Of {1}",
this.dgvRequests.PageIndex + 1, this.dgvRequests.PageCount);
}
}
}
After this just run the asp.net application and you may see the grid view working fine
with the
paging implementation.


4. Conclusion
Thus paging logic can be implemented in grid view using ObjectDataSource.The same can also
be done to DataView control and we can also use ObjectDataSource for deleting. Updating and inserting
data in database.


Thursday, June 11, 2009

Testing Documentation for Projects

TESTING AND IMPLEMENTATION
Implementation is the final and important phase. It involves user training, system testing and successful running of the developed system and changes are made according to their needs. The testing phase involves the testing of developed system using various kinds of data.
An elaborate testing of data is prepared and the system is tested using that test data. While testing, errors are noted and corrections are made. The users are trained to operate the developed system. Both hardware and software securities are made to run the developed system successfully in future.
4.1 Testing
System testing is the stage of implementation, which is aimed at ensuring that the system works accurately and efficiently before live operation commences. Testing is vital to the success of the system. System testing makes a logical assumption that if all the parts of the system are correct, the goal will be successfully achieved. The candidate system is subject to a variety of tests: on-line response, volume, stress, recovery, and security and usability tests.
The testing steps are:
Unit testing
Integration testing
Validation
Output testing
User Acceptance testing
Testing objectives
There are several rules that can serve as testing objectives. They are,
Testing us a process of executing a program with the intent of finding an error.
A good test case is one that has high probability of finding an undiscovered error.
A successful test is one that uncovers as undiscovered error.
If testing is conducted successfully according to the objectives as stated above, it would uncover errors in the software. Generally by testing, we are verifying the following three aspects.
Testing For Correctness
Testing For Implementation Efficiency
Testing For Computational Complexity
Testing for correctness is supposed to verify that a program does exactly what it is designed to do. This is much more difficult than it may at first appear, especially for large programs. The testing is done by running the software for all correct and checking if the system reports any errors. The system is to be tested with the data at the extremes of the input range. The system is also to be tested for values outside the input range. The testing is basically done with an objective to force the system into an error. After finding an error they have to be corrected and tested again.
Test for implementation efficiency attempt to find ways to make a correct program run faster or use less storage. This is to be done by checking arithmetic operations, redundant calculation, group elimination etc. It is a code-refining process, which re-examines the implementation phase of algorithm development.
Tests for computational complexity amount to an experimental analysis of the complexity of an algorithm or an experimental comparison of two or more algorithms, which solve the same problem.
Testing is carried out in different cases. First different units are individually tested and then the system as a whole is tested. Once the system test is satisfactory completed the acceptance test us carried out, where the system is tested with clients data.
4.1.1 Unit Testing
Unit testing focuses verification efforts on the smallest unit of software design, the module. This is also known as “Module Testing”. The modules are tested separately. This testing is carried out during programming stage itself. In this testing step each module is found to be working satisfactorily as regard to the expected output from the module.
When carrying out the unit testing process that each module is working effectively and the corresponding data entry for the developer is working properly and information is transferring from each unit. And all the conditions that what given in the each module is working properly.
4.1.2 Integration Testing
Integration testing focuses on design and the construction of the software architecture. Data can be lost across an interface; one module can have adverse effect on another sub function and so on. Thus integration testing is a part that the software meets all functional, behavioral and performance requirements. The errors, which are uncovered during integration testing, are corrected during this phase.
When carrying out integration testing linking with each module is performing perfectly, and delivering the information between each designation is working properly and messaging broadcasting between all the modules is appropriate.
4.1.3 Validation Testing
Errors discovered where corrected prior to completion of this project with the help of the user by negotiating to establish a method of resolving deficiencies. Thus the proposed system under consideration has been tested by using validation testing and found to be working satisfactorily.
4.1.4 Output Testing
After performing the validation testing, the next step is output testing of the proposed system since no system could be useful if it does not produce the required output in the specific format. The outputs generated or displayed by the system under consideration are tested asking the users about the format required by them. Here, the output is considered into two ways: one is on the screen and the other is printed format.
The output format on the screen is found to be correct as the format designed according to the user needs. For the hard copy also, the output comes out as specified by the user. Hence output testing does not result in any correction in the system. Output testing leading the result we need we are getting as the output.
4.1.5 User Acceptance testing
User acceptance of a system is the key factor for the success of any system. The system under consideration is tested for user acceptance by constantly keeping in touch with the prospective system users at time of developing and making changes wherever required. This is done with regard to the following points:-
Input screen design
Output screen design
On-line message to guide the user
Menu driven system
Format of ad-hoc reports and other outputs
The above testing is done by taking various kinds of test data. Preparation of test data plays a vital role in the system testing. After preparing the test data the system under study is tested using that test data. While testing the system by using test data errors are again uncovered and corrected by using above testing steps and corrections are also noted for future use.
From the above testing that all modules like HelpDesk Master configuration, Asset configuration, Plan Management of the project have developed are tested and they have developed according to needs of the user.
By
Kannan. M. K

Monday, May 25, 2009

How to Install Ajax in ASP.NET

 

Follow these steps to install ASP.NET AJAX.

To install Microsoft ASP.NET AJAX

1.                          Make sure that you are logged in with an account that has Administrator rights.

If your account does not have Administrator rights, the installation process displays the error "The system administrator has set policies to prevent this installation."

2.                          Uninstall any earlier versions of ASP.NET AJAX. If the installation process finds an earlier version on your computer, it will stop.

You can remove earlier versions with the Add or Remove Programs application in Control Panel.

3.                          Download the ASPAJAXExtSetup.msi installation package from the ASP.NET AJAX Downloads Web site.

4.                          To install ASP.NET AJAX from the Windows interface, double-click ASPAJAXExtSetup.msi in Windows Explorer. 

By default, the .msi file is installed in the following location:

drive:\..\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.nnnn.

5.                          To install ASP.NET AJAX from the command line, execute the following command at a command prompt: 

msiexec /i ASPAJAXExtSetup.msi [/q] [/log <log file name>] [INSTALLDIR=<installation path>]

Specify the /q option to perform the installation without user prompts. You can optionally provide an installation path and a file name for logging. If you do not provide an installation path, the default installation path is used.

6.                          If you want to add the ASP.NET AJAX Control Toolkit, download and install it from ASP.NET AJAX Control Toolkit Web site.

To install AJAX Control Toolkit, first of all download it from the links provided in the previous article ASP.Net AJAX Control Toolkit. Now after downloading the zip file, follow these steps:

1.  Create a folder AJAX Control Toolkit at path C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions or the drive where you have installed the Windows on PC.

2.  Then extract the files of downloaded Control Toolkit .zip inside new created folder.

3.  You will get the following folders and files from the extracted items:

o    AjaxControlExtender

o    AjaxControlToolkit

o    Binaries

o    SampleWebSite

o    TemplateVSI

o    ToolkitTests

o    AjaxControlToolkit.sln [Visual Studio Solution file]

 

4.  Double click on AjaxControlToolkit.sln solution file to open it in Visual Studio 2005. It will show a security warning with two project load options:

o    Load project for browsing

o    Load project normally

 

5.  Select load project normally and click ok.

6.  After loading the solution it will display AJAXControlToolkit, SampleWebSite, ToolKitTests, TemplateVSI in the solution explorer.
Right click on TemplateVSI and click build. After successful compile and build go to the path X: or
C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\AJAX Control Toolkit\TemplateVSI\bin


At this path you will get the fresh build of
AjaxControlExtender.vsi

7.  Next Right click on SampleWebSite in the solution explorer and Build Web Site to get the fresh copy of AjaxControlToolkit.dll.
You will get the fresh AjaxControlToolkit.dll at :
X: or
C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\AJAX Control Toolkit\SampleWebSite\Bin


Note: You can see all the Control Toolkit components included in this framework by right clicking on above SampleWebSite in solution explorer --> select view in browser. It will show the sample web site showing the demo of all AJAX control toolkit components.

8.  Now you are ready to add the Control Toolkit in your Visual Studio 2005.
First of all go to TemplateVSI bin folder discussed in step 6 and run
AjaxControlExtender.vsi. This installer will install the ASP.Net web template that will enable you to create AJAX Control Toolkit Web Site.

9.  After installing AjaxControlExtender.vsi, open the Visual Studio 2005 and go for New Web Site, there you will see a new My Template item as AJAX Control Toolkit Web Site, select it and create a new website.

 

How to include AJAX Control ToolKit Components in Toolbox

It's also simple to add Toolkit on Visual Studio Toolbox. In the above new AJAX Control Toolkit Web Site, move your mouse on Controls Toolbox at right side and create a new Tab with name AJAX Toolkit. Then right click under the AJAX Toolkit tab and select choose items, this will open Choose Toolbox Items dialog box. Click on browse button at bottom and select the AJAXControlToolkit.dll file at this path: X: or C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\AJAX Control Toolkit\SampleWebSite\Bin

It will populate the AJAX controls into the AJAX Toolkit tab.

 

 



--By--
கண்ணன்.மா.கா  

Tuesday, May 19, 2009

Silverlight Basics

1.     Introduction

This document provides details regarding how to use Silverlight applications in asp.net application.

2.     What is Silverlight?

Microsoft Silverlight is a programmable web browser plug-in that enables features such as animation, vector graphics and audio-video playback that characterizes rich internet applications. Silverlight 2.0 brought additional interactivity features and support for .Net languages and development tool. It is compatible with multiple web browser used in Win OS and Mac OS. Mobile devices will also be supported.

3.     Features of Silverlight

Silverlight has many features with the .Net framework. Silverlight 2.0 is implemented in .Net framework3.0 to execute the silverlight in the .Net applications. It provides a retained mode graphics system similar to Windows Presentation Foundation (WPF) and integrates multimedia, graphics, animation and interactivity into a single runtime environment. JavaScript scripting can be used to interact with silverlight. Silverlight has the feature to playback the audio and video files with out requiring any plug-in. The Silverlight xaml file and the code behind are compiled and compressed using ZIP and stored in a xap file.

 

Silverlight with a lightweight class library which includes features such as extensible controls, xml web service, networking components and LINQ APIs, Silverlight is a platform independent.

The .Net Framework3.5 in Silverlight adds a subset of WPF UI-programming model, including support for shapes, documents, media and animation objects of WPF. Reusing of Silverlight Design code in WPF is possible with slight modifications. We can develop a xaml application and use for both WPF and Silverlight applications.

 

Silverlight will not support AJAX; there are no validators for the input controls in silverlight. To implement the validation in silverlight forms, we can write validation scripting using JavaScript or we can use special validators for silverlight from Microsoft.

 

Silverlight also includes classes for data access over XML based Web Services, WCF Services and ADO.NET Data Services. 

3.1. Silverlight & WPF

            WPF applications can be deployed to the desktop or run in Internet Explorer (on Windows only). When WPF application run in Internet Explorer they run in a sandbox, so users simply point Internet Explorer at an URL and your application appears without any installation or confirmation need. All development tools are the same (Visual Studio) when making desktop and browser-based WPF applications and you can use the same widgets for both. WPF running in Internet Explorer have some restrictions compared to a program running on the desktop. For example, opening new windows is not possible and communication (WCF) is not allowed. Apparently SOAP calls can be used instead. But Silverlight applications can be deployed to more platforms (OS X and Linux) and more browsers. Like browsers-based WPF applications lose access to some functions compared to desktop applications, Silverlight applications can build on even less infrastructure. Silverlight running sandboxed on "major browsers" on Windows, Linux and OS X -- heavily reduced WPF (missing some 3D functions, widgets gone, etc.) Depend on other 3rd party tools for this functionality. If you develop a Rich Internet Application, it seems like choosing between WPF and Silverlight will be an important decision that will heavily shape your project. When reusing the same code for WPF and Silverlight user controls, the WPF will align the controls in absolute positioning. So when importing the same code inside the silverlight, the slight code changes in alignment of controls should be implemented. In silverlight, there are only limited controls. Silverlight code can be easily implemented in WPF application as the silverlight is a subset of WPF.

3.2. Ajax implementation in Silverlight

            The silverlight will not support AJAX. The validations can be done in silverlight only with the help of javascript or microsoft introduces the validation control toolkit for silverlight. This validation toolkit can be used easily in the silverlight application by referencing the silverlightvalidator assembly in the application. There are seven validators in this assembly namely,

 

·        RequiredField Validator

·        Range Validator

·        Length Validator

·        Regex Validator

·        Phone Validator

·        Numeric Validator

·        SSN Validator

 

Sample code for validation:

 

<TextBox x:Name="txtRange" Height="25" Width="100" >

<slv:ValidatorService.Validator>

<slv:RangeValidator

Min="0"

Max="10"

IsRequired="True"

ManagerName="Group1"

ErrorMessage="Type only between the range"/>     

</slv:ValidatorService.Validator>

</TextBox>

 

            Here the Range Validator is used for the textbox in silverlight. The range falls between 0 to 10. The validator will not allow the user to enter other than the range. Here this validator will also validates the text box as required field.

3.3. Communication

In Silverlight 2.0, the communications of Silverlight and JavaScript in 3 cases are as follows,

·        Silverlight to Silverlight Navigation.

·        Silverlight to JavaScript communication.

·        JavaScript to Silverlight communication. 

The above cases are explained as follows.
 

3.3.1. Silverlight to Silverlight Navigation 

The Navigation of silverlight forms with one another can be easily made in the client side with the help of the some code in the codebehind. If there is two xaml forms  in the silverlight application. We can navigate by the code "this.content= new Page();". By changing the Page() to the next page xaml name. We can also pass values to the second page by initializing an object for that class and we can access all the control of the second class and can pass the value. Sample code for passing values and navigation is as follows

 

Page obj = new Page();

      obj.txtName.Text = cbxEnter.SelectedItem.ToString().Trim();

      this.Content = obj;

Here the Page() is a xaml file, which has a textbox named 'txtName'.  The value which is selected in the combo box of this page namely 'cbxEnter' is assigned to the textbox 'txtName' of Page(). Then the same object is given to the 'this.content'. So that the xaml navigation occurs and the value is moved from one xaml page to another.

3.3.2. Silverlight to JavaScript Communication

The silverlight can communicate with javascript easily. By adding the attribute '[ScriptableType]' for the partial class of the UserControl, in the constructor, we have to register a scriptable object and we have to invoke a javascript function which is placed in javascript file or in the aspx page. The sample code for silverlight to javascript communication is as follows

Code behind code:

[ScriptableType]

    public partial class NewSample : UserControl

    {

        public NewSample()

        {

            InitializeComponent();

 

            HtmlPage.RegisterScriptableObject("Page", this);         

        }

  private void btnTest_Click(object sender, RoutedEventArgs e)

        {

            System.Windows.Browser.HtmlPage.Window.Invoke("ShowTitle",

"Hello from silverlight");

        }

    }

 

Aspx code:

 

<script type="text/javascript">

       function ShowTitle(msg)

 {

            alert("Message From Silverlight :" + msg);

       }

      </script>

 

            Here in the sample code, the javascript function 'ShowTitle(msg)' is called in the button click event in codebehind. By this way, we can interact with the parent page from xaml silverlight.

3.3.3. JavaScript to Silverlight Communication

The silverlight can communicate with javascript easily. The interaction between javascript and silverlight can be done easily by adding the attribute '[ScriptableType]' for the partial class of the UserControl, in the constructor, we have to register a scriptable object and we have to invoke a javascript function which is placed in javascript file or in the aspx page.

In the javascript function, get the elementid of the silverlight xaml. To call the code behind function from javascript, the attribute '[ScriptableMember]' should be added to the function. We can call the code behind function as shown in the sample code as follows

Aspx code:

<script type="text/javascript">

      function ShowTitle(msg)

{

      alert("Message From Silverlight :" + msg);

            var ctrl = document.getElementById("Xaml1");

            ctrl.Content.Page.DisplayText("Hello from javascript");

      }

</script>

 

Code behind code:

[ScriptableType]

    public partial class NewSample : UserControl

    {

        public NewSample()

        {

            InitializeComponent();

 

            HtmlPage.RegisterScriptableObject("Page", this);

            System.Windows.Browser.HtmlPage.Window.Invoke("ShowTitle",

 "Hello from silverlight");

        }

 

        [ScriptableMember]

        public void DisplayText(string msg)

        {

            txtTitle.Text = msg;

        }

 

        private void btnTest_Click(object sender, RoutedEventArgs e)

        {

            System.Windows.Browser.HtmlPage.Window.Invoke("ShowTitle",

"Hello from silverlight");

        }

     }

Here in the sample code, the javascript function 'ShowTitle(msg)' is called in the button click event in codebehind. This javascript function again calls a code behind function. Thus the javascript and silverlight interaction can be implemented with the parent page from xaml silverlight.

 4.     Windows Communication Foundation (WCF)

 

 4.1. Introduction

                       

                                    WCF simplifiesdevelopment of connected applications

 through a new service-oriented programming model.

 

4.2. Step by step web service creation in WCF

           

             à Create new project,Select WCF select Application.

 

  à New project will open ,there will be interface class and .sve (service file). 

 

à In interface class IService1.cs

 

                        è Service Contract

è Operation contract

                        è Data contract

                        è Data member

è Message Contract         

 

Service contract:

                       

                         Service contract is the entire suite of offerings of the service. It can be   

           thought of as a definition of what the service provides.

 

Operation contract:

 

                        Operation contract is the method/operation which does a specific task.

            They actually carry out the implementations within them.

 

Data Contract:

       

Data contract can be consider as vehicles of data.

 

Data member:

 

                        Data member is mark property for data.

 

Message Contract:

           

                        Message contract is the embodiment of the messages that flow between

 the service and the client.

 

             Silverlight will not accept the Dataset so return value from WCF service should

       be in the generic list.

 

Code Interface class

public interface IService1

      {

                [OperationContract]

        IEnumerable<branch> check();

}

 

[DataContract]

      public class branch

      {

        int brId;

        string brName;

        public branch(int bId, string bNam)

        {

            brId = bId;

            brName = bNam;

 

        }

        [DataMember]

        public int BranchId

        {

            get { return brId; }

            set { brId = value; }

        }

        [DataMember]

        public string BranchName

        {

            get { return brName; }

            set { brName = value; }

        }

 

}

 

 

à In Service1.svc.cs

 

    Right click on IService Select Implement Interfaceà Implement Interface

    Method in interface class will come to Service.svc.cs     

Code Interface class 

List<branch> br = new List<branch>();

SqlConnection sc = new SqlConnection(ConfigurationManager.AppSettings["connection"].ToString());

#region IService1 Members    

        public IEnumerable<branch> check()

        {

            try

            {

                sc.Open();

                string str = "SELECT * FROM [RequestBranch]";

                SqlDataAdapter da = new SqlDataAdapter(str, sc);

                DataSet ds = new DataSet();

                da.Fill(ds);

                sc.Close();

 

                foreach (DataRow dr in ds.Tables[0].Rows)

                {

                    br.Add(new branch(Convert.ToInt32(dr[0]), dr[1].ToString()));

                }

 

                IEnumerable<branch> brs = from bran1 in br

select bran1;

return brs;

LINQ concept for return list collection to silverlight

            }

            catch (Exception ex)

            {

                

                throw ex;

            }

        }

 

       

HTML/JAVASCRIPT BLOG

You can find the help for html and javascript codes

Any Doubts Contact my Mail-ID:
kannan.mkv@gmail.com