Subscribe: Advanced Dotnet Tutorial
Added By: Feedage Forager Feedage Grade B rated
Language: English
accordion  add  application  button  code  control  create  grid  new  page  project  silverlight  system  visual studio  web  xaml 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Advanced Dotnet Tutorial

Advanced Dotnet Tutorial

Updated: 2018-04-18T04:42:26.953-07:00


ASP.NET 4.0 Web Control ClientID


In ASP.NET, each web control is identified uniquely using the ‘ID’ property of the control. We can access the server controls in the code behind using this ‘ID’ property. However, when the web form with server side controls renders in the form of HTML, the server side ID gets converted into client side ID. But for client-side developers, it becomes difficult when they want to access HTML elements using JavaScript. The reason is that the ‘ID’ property gets generated at runtime and is not known at design time. Although you can use expressions to access them, the code is not very readable.In ASP.NET 4.0, Microsoft has given developers the control to render client side ID of server controls, by introducing a new property called ‘ClientIDMode’. It offers the following options to render the server side ‘ID’ at client end –AutoID – this is the same as previous web server control ‘ID’ rendering at client side.Static – this option keeps the server ID name intact even at the client side. For example if the Textbox ID at server side is ‘txtCustomerID’ then at client side, it will remain as it is.Predictable – this option is used for repeating templates like Gridview or Listview.Inherit – ClientID will be generated the same way as Parent ID. For example, if the ParentID is ‘MainContent’ then the Textbox ‘txtCustomerID’ will be ‘MainContent_txtCustomerID’.Now let’s see some examples of the same. Create an ASP.NET 4.0 website with the name ‘ClientIDExample’ as shown below –Now let’s add the following pages to the application –InheritIDPage.aspx.AutoIDPage.aspx.StaticIDPage.aspx.PredictableID.aspx.Make sure that you choose the ‘Site.master’ page when you add the above pages. Now let’s add code for the ‘AutoIDPage.aspx’ –Note: I have used document.writeln just for illustration purposes. It won’t work in a document that’s served as XHTML.In the above code, we are using JavaScript to print the client ID which is rendered from server side to client side.When you run this page, you will see an output similar to the one shown below –Now write the following code in our ‘StaticIDPage.aspx’ –Run this page and you should see the following output –Now let’s add the following code in ‘InheritIDPage.aspx’ –In this demo, we are using the Northwind database and Employee table. In the ‘GridView’ control, we are setting two properties – ‘ClientIDMode’ and ‘ClientIDRowSuffix’. The ClientIDRowSuffix property is used during client ID generation. Now run this page. Right click the page in browser and view the source code. You will see the following output –You can control the web control client ID generation at Page level as well as web site level. For eg: include ClientIDMode property at Page directive as shown below –If you want to set the ClientIDMode at web site level, you can use the web.config settings as shown below –In this post, we have seen how easy it is to take control of Client ID generation as per our requirement. The entire source code of this article can be downloaded over hereRead More :[...]

Tracing in .Net 2.0


Tracing is a new feature given in .Net 2.0 that helps the user to view different steps occurred while execution of a single Page at run time. Tracing Information help you to investigate errors or unwanted results while ASP.Net process a page request.

By default tracing is disabled so if you want to view the tracing information you have to enable the tracing.

Tracing can be of two types Page Level Tracing and Application Level Tracing.

Page Level Tracing:

Gives information about a particular page.

To enable the page level tracing Add "Trace=true" in Page directive of ASP.Net Page

<%@ Page Trace="true" %>

Other attribute that you can use here is TraceMode

Set TraceMode to SortByTime to soert the Information in order in which they were processed.

Set TraceMode to SortByCategory to sort the Information in the different categories

<%@ Page Language="VB" Trace="True" TraceMode="SortByCategory" %>

Application Level Tracing:
Gives information about whole application.

Application level tracing can be enabled in web.config file by using the trace element inside system.web tag.

Other elements that can be used are

pageOutput-> Set this element to true if you want to display trace information at the end of page ;Set this element to false if you want to display trace information in TraceViewer.

requestLimit-> Number that indicates for how many requests trace information is required.

Note: Trace attribute in Page directive overwrites the trace attribute in web.config file.

How to view trace information with trace viewer
To do this tracing should be enabled in web.config file.
  1. Navigate to trace.axd in the root of your application.

    For example, if the URL for your application is http://localhost/SampleApplication, navigate to http://localhost/SampleApplication/trace.axd to view the trace information for that application.
  2. Select the View Details link for the request that you want to investigate.

CSS: Change Image of Button On Hover and Disabled


This article helps to understand how CSS is changed automatically when a button is disabled from the server side. Further, how to define CSS when a user hovers over an element.Step 1: Define CSS for buttonDefine two css (i.e. one for hover and another normal) for each button.Button1: Which will enable 3rd button CSS for button1 when it is hovered by the user. Here CButtonMakeEnable:hoverdoes it all; :hover defines what css is applied when an element is hovered..CButtonMakeEnable:hover        {            background: url("Images/buttonMakeEnableHover.png");            background-repeat: no-repeat;            background-position: top right;            background-color: transparent;            cursor: pointer;            border: 0px;            height: 48px;            width: 48px;        }  CSS for button1 when it is not hovered by the user. Here the css is defined for normal behavior.        .CButtonMakeEnable        {            background: url("Images/buttonMakeEnableNormal.png");            background-repeat: no-repeat;            background-position: top right;            background-color: transparent;            cursor: pointer;            border: 0px;            height: 48px;            width: 48px;            outline-width: 0px;        }Button 2: Which will disable 3rd button CSS for button2 when it is hovered by user. Here .CButtonMakeDisable:hover does it all; :hover defines what css is applied when an element is hovered..CButtonMakeDisable:hover        {            background: url("Images/buttonMakeDisableHover.png");            background-repeat: no-repeat;            background-position: top right;            background-color: transparent;            cursor: pointer;            border: solid 0px #ff0000;            height: 48px;            width: 48px;        }  CSS for button2 when it is not hovered by the user. Here the css is defined for the normal behavior.        .CButtonMakeDisable        {            background: url("Images/buttonMakeDisableNormal.png");            background-repeat: no-repeat;            background-position: top right;            background-col[...]

Tweeter search application with Silverlight (Beginners) your first Silverlight application


Developers who are new to Silverlight or in learning phase this demo/article can help them creating a small application. This isn't just a hello world application this something interesting more than that. So ready to get your hand dirty with some XAML code and little bit power of Silverlight.To create a Silverlight project you should have Silverlight library component installed on your computer. If you have visual studio 2010 installed then you are good to go as Silverlight 3.0 project template can be found there. Open a new project -> and select the Silverlight application from the Silverlight template.  Now when you click OK you'll see the next window prompting you few more details about what kinda project you want to run your Silverlight application with in:Leave the default selections and click OK.Now you'll see two projects in your solution explorer.Let go to our MainPage.xaml file to create some UI for our application. Add a Button and Listbox will create a UI and XAML like this. Set the Name and Content properties for your convenience.

Editing the Path of any Shape in XAML Silverlight


In Expressing Blend we are not only limited to draw some primitives line rectangle, line or ellipse. Expression Blend help us to create any shape. Expression Blen has two tools named Pen and Pencil which let us to create path and selection cursor let us to modify the shape. Let's create any shape using these tools.Follow the steps:Step 1Create a new project in Expression Blend and draw a rectangle and fill any color.Step 2Using selection tool select the rectangle and click on Object > Path > Convert to Path. This option will add four anchor points to rectangle, click on 'Direct Selection' tool to view that anchors.Step 3Now select Pen tool to add three new anchor points in exiting rectangle shape. Notice, you click to add new anchor when see + sign with pen tool and also notice the – sign with pen tool to delete exiting anchor point. Press Ctrl+Z for undo.Step 4After inserting two new anchor points select the 'Direct Selection' tool and modify the shape by dragging center anchors.Step 5Now fill some Radial Gradient color to shape to create shape asStep 6Now select the 'Direct Selection' tool and select three anchor points by pressing Ctrl key and move it downward.READ MORE>>[...]

Add a polygon to the Silverlight Bing Map


MapPolygon:The MapPolygon class accepts a list of points that define its shape and location on the map.MapPolygon class is used to represent a polygon on the map.Namespace: Microsoft.Maps.MapControlAssembly: Microsoft.Maps.MapControl (in microsoft.maps.mapcontrol.dll) Create Silverlight application:Open Visual Studio 2010. Go to File => New => Project. Select Silverlight Application from the installed templates Silverlight.  Enter the Name and click on Ok. Click OK. Go to C:\Program Files (x86)\Bing Maps Silverlight Control\V1\Libraries\ (Check the path where you have installed Bing Maps Silverlight Control). Add the following assemblies to the project.o Microsoft.Maps.MapControl.Common.dllo Microsoft.Maps.MapControl.dll  Replace MainPage.xaml with the following code                                                                                         Add the following in MainPage.xaml.cs.private void btnCreatePolygon_Click(object sender, RoutedEventArgs e)        {             MapPolygon polygon = new MapPolygon();            polygon.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Gray);            polygon.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black);            polygon.StrokeThickness = 1;            polygon.Opacity = 0.7;            polygon.Locations = new LocationCollection() {             new Location(15,-15),            new Location(15,15),            new Location(-15,15),            new Location(-15,-15)};            MapWithPolygon.Children.Add(polygon);        }  Build the solution. Hit F5. The output looks like the followingREAD MORE >>[...]

Getting started with testing an ASP.NET Webforms Application (MVP Pattern)


In this article we explore how unit tests are created in an ASP.NET WebForms Application. Although there are sections that are specific to the MVP pattern, there are also a few tips and guidelines about Unit Testing of a Web Application in general.The purpose of this article is to explain how to test an ASP.NET Webforms Applications. How the Model-View-Presenter pattern is helping us in that, how do we use mock-up libraries to simulate objects like HttpContext and how do we use Visual Studio 2010 Testing Environment.Testing Web Applications First of all, when we want to test a Web Application we are considering two types of tests. Acceptance Tests and Unit Tests.Acceptance Tests Acceptance Tests are tests from a user prospective and most of the times an automated-browser testing tool is used (like WatiN, Selenium etc.) So we are testing the user experience, if our app works in different browsers, if client-validation works as it should etc.Unit Tests Unit Tests are tests dedicated to test our code, our business logic and validation, our database interaction and everything that are not related to how data is displayed. Although many times Unit Tests and Acceptance Test may have overlapping areas (example, when testing if a page works simultaneously validation is also being tested) it's important to have both in a project.For now, let's focus on Unit Tests.Example Let's consider the following real world but simple example:Almost every website has a contact page. The user enters his details and sends them to the server. The server processes the data and informs the user about the result. How can we test a page like this?Figure 1: Screenshot - Contact Page Explaining the MVP Pattern The MVP pattern stands for Model-View-Presenter and doesn't differ a lot from MVC (Model-View-Controller). When an application is developed using the MVP pattern it's more testable because layers are being separated from each other. So each layer's responsibility is clearer thus easier to define test cases to run against. An excellent open-source framework that helps us build a WebForms application using the MVP Pattern is WebFormsMVP. This framework is being used in this example.An implementation of the page above using the MVP Pattern along with a brief explanation of the pattern its self would be the following.Model Model is the class that holds the data of our page. In this case it is a simple class with three properties that are represented by our text fields and one property that holds if the Model is persisted or not to our database.Listing 1: ContactModel.cs view sourceprint?1.public class ContactModel 2.{ 3.    public string Name { get; set; } 4.    public string Message { get; set; } 5.    public enProcessState ProcessState { get; set; }         6.    public string Email { get; set; } 7.}It's also included just for reference the enProcessState enum.Listing 2: enProcessState.cs view sourceprint?1.public enum enProcessState 2.{ 3.    Pending, 4.    Saved 5.}View View, in this case, is the user control that displays the form and defines events – if necessary – that correspond to user actions. Because a view can be implemented in various ways an interface is being defined and the user control is implementing that interface.Listing 3: IContactView.cs view sourceprint?01.public interface IContactView : IView 02.{ 03.    event EventHandler Contacting; 04.} 05.public class ContactEventArgs : EventArgs 06.{ 07.    public string Name { get; set; } 08.    public string Email { get; set; } 09.    public string Message { get; set; } 10.}The implementation of the interface is our user control.Listing 4: Con[...]

CUDA integration with C#


CUDA enabled hardware and .NET 4 (Visual Studio 2010 IDE or C# Express 2010) is needed to successfully run the example code. Visual C++ Express 2008 has been used as a CUDA C editor (2010 version has changed custom build rules feature and cannot work with that provided by CUDA SDK for easy VS integration). Part 1: Environment and tools configuration for CUDACUDA is a general purpose parallel computing architecture introduced by NVIDIA. CUDA programs (kernels) run on GPU instead of CPU for better performance (hundreds of cores that can collectively run thousands of computing threads). It comes with a software environment that allows developers to use C as a high-level programming language. This computation technology is used in mathematics, science, finance, modeling, image processing and so on. Basic CUDA configuration for developing purpose:Download and install CUDA toolkit for correct OS, use version 3.1 or latest 3.2RC or version 3.0 for device emulation (limited usage but works without CUDA enabled device, not supported after version 3.0)  Download and install SDK for the same OS and toolkit version  Update display drivers if you encounter problems with SDK installationVisual C++ Express 2008 (or VS2008) configuration:1. Syntax coloring Open Tools -> Options from main window, then Text Editor -> File Extension, add .cu and .cuhextensions with Microsoft Visual C++ Editor Copy file usertype.dat from [sdk dir]\C\doc\syntax_highlighting\visual_studio_8\ to ProgramFiles\Microsoft Visual Studio 9.0\Common7\IDE\ folder Restart Visual Studio2. New project, 32bit Windows XP version Default SDK location is c:\Documents and Settings\All Users\Application Data\NVIDIA Corporation\NVIDIA GPU Computing SDK\  Default toolkit location is C:\CUDA\ Create empty Win32 console application and add source file with .cu extension Select newly created project in the Solution Explorer window and then right mouse key ï‚® Custom Build Rules, use Find Existing button to locate Cuda.rules file in [sdk dir] \C\common\ folder, add it and mark on the list of available rule files  Select again project -> Properties, select Release Configuration and then from the tree view:- Configuration Properties -> Linker -> General -> Additional Library Directories:add this line (default folders) C:\CUDA\lib;"C:\Documents and Settings\All Users\ApplicationData\NVIDIA Corporation\NVIDIA GPU Computing SDK\C\common\lib"  Configuration Properties -> Linker -> Input -> Additional Dependencies: cudart.lib Use the same settings for Debug Configuration For emulator configurations use Configuration Manager to add new configurations based on Release and Debug ones, name them as EMU-Release and EMU-Debug (or as you wish) Select EMU-Release from Configuration combo-box:- Change cudart.lib to cudartemu.lib- From tree view select CUDA Build Rule v3.0.14 (or similar) ï‚® General and set Emulation Mode toYes  Do the same for EMU-Debug3. New project, 64bit Windows 7 version Default SDK location is c:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK\ Default toolkit location is C:\CUDA\ The rest is basically similar to win32 variant except that:- Use Configuration Manager to create new solution configurations AMD64_Release, AMD64_Debugand emulation versions if needed (copy settings from Release and Debug configurations)- Use Configuration Manager to add new solution platform x64 and copy setting from Win32- In Project contexts window choose platform x64 for all AMD64 configurations- Linker -> General -> Additional Library Directories: c:\CUDA\lib64; "c:\ProgramData\NVIDIACorporation\NVIDIA GPU Computing SDK\C\common\lib"- Linker -> Input - Additional Dependencies: cudart.libImportant notes about example files:You must do this basic configuration to be able to open attached example because of custom build rule ent[...]

Playing and Controlling Video Playback in XAML Silverlight


Using videos in a Silverlight based application is a very exciting feature that come early Silverlight 2. Today we see the most extended Silverlight specially Microsoft added GPU Hardware Acceleration for video and bitmap in Silverlight 3 and now Silverlight 4 supports the output protection for video and audio.How to Play Video   To play the video, we can simply drag the compatible [List of Supported Media Formats] video file on the development stage. Now, if you add videos in the development stage and test it, then it will have the following three annoying work: Movie will automatically start Movie runs untill the end and when reaches at end can't run again Once movie starts there is no way to stop or pause this But by using some coding in code-behind we can control the playback of movie. Let's see how!   1. Dealing with Automatic Start   By default videos automaticall get started when we run the project, it is distracting feature from the users point of view. To change auto start false, select the video on stage and in properties uncheck the 'AutoPlay' option.     2. Dealing with Endless Playback   By default, when the video reaches the end then it stops and does not start again. To change such a setting follow the steps: Select the video on stage In Properties, switch the mode from 'Properties' to 'Events'. In the Event list, point to 'MediaEnded' label and type the event handler name (I will be using md_ended_eve) and then press tab to apply it and it automatically switches you to code-behind with a new event. Now type the following code inside event handler. (intro_wmv).Stop();(intro_wmv).Play();In above code 'intro_wmv' is my media fine name.  Now test the application. Note to use 'AutoPlay' to true when you are testing endless loop.   XAML Code               XAML.CS Code using System;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Ink;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;namespace SilverlightApplication1{       public partial class MainPage : Grid       {              public MainPage()              {                     // Required to initialize variables                     InitializeComponent();              }              private void md_ended_eve(object sender, System.Windows.RoutedEventArgs e)              {&[...]

Silverlight Bing Map Control in SharePoint 2010


Silverlight Bing Map Control in SharePoint 2010In this article we will be seeing how to use Silverlight Bing map control in SharePoint 2010.Bing Map Developer Account:Open  Go to New User section and click on Create.  Sign in using Windows Live ID. Enter the account details and click on Save.  Bing Map Developer account will be created successfully.Bing Maps Key:Bing Maps Key should be created to authenticate your Bing Maps application as described in the SDK for the Bing Maps API we are using. If you run the program without providing the valid Bind Maps Key then the map appears in the browser with a message that you have invalid credential appears.    • Select Create or view keys in the Tasks left-hand menu MAP APIs.• In the Create key box on the My keys page, provide the following information for the application that will use the Bing Maps key:Application name Required. The name of the application. Application URL Required. The URL of the application. Application Type Required. The scenario for your application. Select the application type that best represents the application that will use this key.The following are general descriptions of these types.   Application Type Description Broadcast Application is used for public or internal-facing television, movies or similar.Developer Application does not exceed 125,000 sessions or 500,000 transactions within a 12 month period.Education Application is used for public use by schools, including faculty, staff and students.Evaluation/Trial Application is used for public or internal use during a 90 day evaluation period.Mobile Application is used for publically available and installable applications on mobile handsets.Not-for-profit Application is used by a tax-exempt organization.Enterprise This option is available to licensed enterprise accounts only.READ MORE >>[...]

Security model of Internet Information Services for ASP.NET


IIS has its own security configuration and even for any request reaching the ASP.NET runtime, IIS verifies the request with it's own security configuration. So the first gatekeeper in the ASP.NET security pipeline is actually IIS. So let us understand those security mechanisms which IIS implements:

1. Authentication: IIS support following authentication mechanism
  • Basic authentication:
  • Digest authentication
  • Passport authentication
  • Window authentication
  • Certificate authentication

Point to remember:
  1. Any authentication which IIS performs results into an authenticated window user, so this means that IIS supports authenticating window users only.
  2. If ASP.NET is configured to support form or window authentication, then configure IIS to support basic or digest authentication.
  3. If ASP.NET is configured to support form or custom authentication, then configure IIS to support anonymous access.
  4. With XP, it comes with IIS 5.x
  5. With Server 2003, it is IIS 6.0

How to configure IIS for authentication:

Point to member here

  1. When the Anonymous User option is checked then everyone is given access to a web page and it overrides all authentication settings.
  2. If IIS is configured to anonymous authentication, we can still use ASP.NET-based security to authenticate users either with ASP.NET-integrated mechanisms such as forms authentication or a custom type of authentication.

  3. Windows authentication configures IIS to validate the credentials of the user against a Windows account configured either on the local machine or within the domain. A Credential submitted by a user is verified against the Windows account.
  4. When Basic Authentication is checked it defines an additional HTTP header for transmitting user names and password across the wire but nothing is encrypted here. It is transmitted in the form of a base64 encoding.

  5. Digest authentication is similar to basic authentication with the difference that instead of sending credentials in the form of Base64 encoding, user password and username are hashed.


Database Binding with Accordion Control


This article demonstrates how to bind an Accordion Control with a database in ASP.Net using Ajax.We are assuming that you have already completed the installation of the Ajax Toolkit as well as have a basic understanding of coding.About the control:The Accordion is a web control that allows you to provide multiple panes and display them one at a time. It is like having several CollapsiblePanels where only one can be expanded at a time. The Accordion is implemented as a web control that contains AccordionPane web controls. Each AccordionPane control has a template for its Header and its Content. We keep track of the selected pane so it stays visible across postbacks. It also supports three AutoSize modes so it can fit in a variety of layouts. None - The Accordion grows/shrinks without restriction. This can cause other elements on your page to move up and down with it. Limit - The Accordion never grows larger than the value specified by its Height property. This will cause the content to scroll if it is too large to be displayed. Fill - The Accordion always stays the exact same size as its Height property. This will cause the content to be expanded or shrunk if it isn't the right size.The Accordion is written using an extender like most of the other extenders in the AJAX Control Toolkit. The extender expects its input in a very specific hierarchy of container elements (like divs), so the Accordion and AccordionPane web controls are used to generate the expected input for the extender. The extender can also be used on its own if you provide it appropriate input.This article provides a few steps which will be easy to follow.Step 1:Before you can use any of the Ajax Control Toolkit controls in a page, you first need to add a ScriptManager to the page. You can drag the ScriptManager from the Visual Studio Toolbox window onto the page. The ScriptManager is located in the Ajax Control Toolkit tab under the Toolbox. Step 2:Create one which is like: Step 3:Drag an Accordion Control from the ToolBox, which will look like:            Step 4:Apply some css on it and change its property according to the requirement. Step 5:Generate the OnItemDataBound events.Which will look like:READ MORE >>[...]

Hosting Mobile WebSite Under IIS


First we have to create a mobile web application. For how to create a mobile web site see my previous article Developing Mobile Pages.

Once we have created our mobile pages the testing of the mobile pages is not as easy as you think; for testing of mobile pages you can use desktop browsers as well as Mobile Emulators. With desktop browsers you can test by direst debugging application but in mobile emulators first we have to host our website under IIS. For testing mobile pages in an emulator we have to host the website first under IIS.

Hosting Website:

Check out the following screenshot which will help you to host the website under IIS.
  1. Open IIS Manager

  2. Right click on Default Web Site->New->Virtual Directory which will open the following screen.

  3. Provide a virtual name by which you want to access your website while typing URL. And click on next.
  4. The next screen will ask you to provide the physical content of your application.

  5. On the next screen it will ask you the permission setting for you website. Select all permission and click on next and then finish.

  6. After finishing website creation your web site is created.


What is Foreground or Background Thread


Threading is a concept we all understand and most of us would have implemented them in real world applications. Here is one more explanation of inner level detail on threads - that is Foreground and Background threads. Types of ThreadsBasically, there are two types of threads which fall into:Foreground Thread Background Thread Foreground ThreadForeground threads are threads which will continue to run until the last foreground thread is terminated. In another way, the application is closed when all the foreground threads are stopped.So the application won't wait until the background threads are completed, but it will wait until all the foreground threads are terminated. By default, the threads are foreground threads. So when we create a thread the default value of IsBackground property would be false.Background ThreadBackground threads are threads which will get terminated when all foreground threads are closed. The application won't wait for them to be completed.We can create a background thread like following:Thread backgroundThread = new Thread(threadStart);backgroundThread.IsBackground = true;backgroundThread.Start();Test ApplicationWe can see the difference by using a windows or console application. In the attachment,provided such an application. The application is explained below:The application contains 2 buttons, on click of each it will create a thread.Each thread will be executing a method which takes 25 seconds to execute through a mere Thread.Sleep() invoke.private void TenSecondsMethod(){    // Method of 25 seconds delay    Thread.Sleep(25000);}The first one will be Background thread and second would be Foreground.After clicking each button, you can try closing the application.From the windows task manager we can see the application would not be listed in the case of Background thread created.From the windows task manager we can see the application would be still running in the case of Foreground thread created. The following image shows the snapshot of task manager just after closing the application after invoking a foreground thread. The application will continue to run until all the foreground threads are completed.READ MORE >>[...]

Pop Search Form Control in Silverlight


Silverlight is a new and powerful browser plug-in that works with Mac OS, Windows and Linux. It helps you create rich web application that is safe, secure and scalable cross-platform. This article will use Visual Studio 2008 to create Silverlight pop search form control.System RequirementThis application requires the user to have copy of Visual Studio 2008 Microsoft Silverlight 2 Tools for Visual Studio 2008 SP1 ( Northwind database in MS SQL Server The article assumes a familiarity with C#, as well as with using Visual Studio 2008 to create Silverlight applications. Elementary knowledge of WCF, Web Service, LINQ would be beneficial but not absolutely necessary to fully understand the content of this article.Design RequirementThe main control is combining with two textboxes and one button as Fig 1. The first textbox has ability to display data and enter data. The button will show up pop search form. The second textbox has ability to display data only.Fig 1. Main Control with function descriptionsThe pop search form control has datagrid to display data and it has searching function as Fig 2.Fig 2. Pop Search Form control with function descriptionsThere are two ways to bring data from datagrid to the main control.By double click datagrid By click OK buttonFig 3. Bring selected data back to Main controlThere is one way to extract data without pop search form.Types correct ID (key) in first textbox to display Name (Value) data.Fig 4. Types correct ID to display NameCreate Silverlight and WCF ProjectOnce we know control's functionalities, now we can start to create our project in Visual Studio 2008. Let's create all the projects we need, then we will tackle each project to achieve goal.**Please download the code and walkthrough it with each step Step 1. Create Silverlight ApplicationIn Visual Studio 2008, go File->New->Project then select Sivlerlight Application. You can name whatever name you would like to call. I will name it popFormDemo in this sample as Fig 5.Fig 5. Create Silverlight projectYou should see the wizard window after you click OK in step 1. We will leave it in default setting as Fig 6.Fig 6. Add Silverlight Application wizardAdd New Folder under PopFormDemo Project with name CusControl as Fig 7. Fig 7. Create new folder in PopFormDemo projectUnder CusControl Folder, add New Silverlight user control with name PopForm as Fig 8.Fig 8. Add new Silverlight User Control in CusControl folderREAD MORE >>[...]

Use of Stopwatch Class in C#


Using the following line a new stopwatch object will be created:System.Diagnostics.Stopwatch myStopWatch = newSystem.Diagnostics.Stopwatch();The "Start" method will start the stopwatch:myStopWatch.Start();The "Stop" method will stop the stopwatch:myStopWatch.Stop();To display the value of the stopwatch then use the code shown below:/// /// To get the value of Hours../// myStopWatch.Elapsed.Hours.ToString();/// /// To get the value of Minutes../// myStopWatch.Elapsed.Minutes.ToString();/// /// To get the value of Seconds../// myStopWatch.Elapsed.Seconds.ToString();/// /// To get the value of Milliseconds../// MyStopWatch.Elapsed.Milliseconds.ToString();Main Code :using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;namespace MyBlog{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            System.Diagnostics.Stopwatch myStopWatch = newSystem.Diagnostics.Stopwatch();            //Start StopWatch...            myStopWatch.Start();            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myDatabase.mdf;Integrated Security=True;User Instance=True");            SqlDataReader dr;            try            {                conn.Open();                SqlCommand cmd = new SqlCommand("SELECT StudName FROM Student WHERE StudId=1", conn);                dr = cmd.ExecuteReader();                while (dr.Read())                {                    //it will display Name of Student whose Id is "1"...                    mytxtName.Text = dr.GetValue(0).ToString();                }                //S[...]

Resource Management In Silverligt 3


The files required for any Application to run other than project related files are called resources. It can be a text file or image file or any other file. In this article, we will be seeing how images can be accessed in various ways in a Silverlight application.

Types of Resource Management

There are 3 ways we can manage resources such as:
  1. Add Image as Resource
  2. Add Image as Content
  3. Add Image as Resource in an external assembly
Create a Silverlight Project

Figure 1.1 Creating Silverlight Project

Designing the Application

For our sample application let's put 3 Image Control, 3 Buttons and 3 TextBlocks to display the type of resource. Use blend to design the application.


Figure 1.2 Designing the Application

Add Images to the Project

In SampleSilverlightApplication project add a folder called images and two images are added. As you can see the images we are going to change the Build Action of the images. We will change the Build Action for firefox.png to Resource and IE.png to Content.


Figure 1.3 Adding images to the project


Figure 1.4 Changing the Build Action of the Images.

Adding another Project

To use Image from another assembly we need to add project to the solution and we will add the Image to it. Then we will add the project refference to our main project (SampleSilverlightApplication).


Figure 1.5 Adding another project to the Solution and adding Images to the added project

We have just added One Silverlight Class Library to the Solution and added the folder images and ofcourse we added chrome.png. The SecondApplicaion reference is added to the SampleSilverlightApplication.


Splash Screen in Silverlight 3 Application


If a Silverlight application is small, it will be downloaded quickly and appear in the browser. If a Silverlight application is large, it may take a few seconds to download. As long as your application takes longer than 500 milliseconds to download, Silverlight will show an animated splash screen.Splash Screens can be used for the following purposes: To show the Progress of downloading the xap file. (By Default) Copyright Information Custom Animation.Crating Silverlight ProjectFire up Visual Studio 2008 and create a Silverlight Application. Name it as SplashScreenInSL3.The built in Splash Screen is not that exciting. It simply displays a ring of blinking circles and the percentage of the application that's been downloaded so far.If you don't like the stock splash screen, you can easily create your own. Essentially, a custom splash screen is a XAML file with the graphical content you want to display, and a dash of JavaScript code that updates the splash screen as the application is downloaded.Add a new XAML file to your ASP.NET website (not the Silverlight project). Choose the Silverlight JScript page template, enter a name, and click Add. This XAML file will hold the markup for your splash screen.Add the following xaml code into it.                            Next, you need to add a JavaScript function to your ASPX entry page or ASP.NET test page. (If you plan on using both, place the JavaScript function in a separate file and then link to it in both files using the source attribute of the script block.) The JavaScript code can look up named elements on the page using the sender.findName() method, and manipulate their properties. It can also determine the current progress using the eventArgs.progress property. In this example, the event handling code simply updates the text and widens the progress bar based on the current progress percentage: To use this splash screen, you need to add the splashscreensource parameter to identify your XAML splash screen and the onsourcedownloadprogresschanged parameter to hook up your JavaScript event handler. If you want to react when the download is finished, you can hook up a different JavaScript event handler using the onsourcedownloadcomplete parameter.(object)

InitParams in Silverlight


If you are developing a Silverlight Application, and you need to pass some parameters inside – for example a key and value pair then we can pass the key value pair from the aspx page itself. We will see how we can do this in Silverlight.Create a Silverlight ProjectFigure 1.1 Creating Silverlight ProjectAdding parametersOpen the "InitializingParametersTestPage.aspx" and find the tag tag  as followspublic IDictionary AppParams;In Application_Startup event initialize the parameters as followsprivate void Application_Startup(object sender, StartupEventArgs e)        {            AppParams = e.InitParams;            this.RootVisual = new Page();        }Using ParametersIn Page.xaml add ListBoxes to show the parameter valuesXaml Code                                                                                                                                                        In code behind of the Page.xaml.cs add the following code to bind the parametersnamespace InitializingParameters{    public partial class Page : UserControl    {        public Page()        {            InitializeComponent();            App myApp = App.Current as App;             foreach (string item in myApp.AppParams.Keys)            {                myKeysList.Items.Add(item);            }            foreach (string item1 in myApp.AppParams.Values)  &[...]

Scene Order (Layer Order) in XAML Silverlight


XAML is fully based on composition of object scenes. Every XAML page has a parent/top most container (like UserControl/Canvas/Page etc) and it may have zero or more children elements (like Grid/Rectange/Ellipse etc). Look at the example below:


In the above screenshot, use three elements named LayoutRoot, LayoutRoot1 and Rec1. LayoutRoot (white background) is lower most (beneath); look at the code above and examine the order of elements:
  1. LayoutRoot (Grid)
  2. LayoutRoot1 (Grid)
  3. Rec1 (Rectangle)

Please note that, usually we write code in a top to bottom approach in general, so the order of shapes (elements) also varies on this. If you wish to bring "LayoutRoot (White Grid)" to the front then the order of elements will also be rearranged automatically. Look at the screenshot below:



Plane Projection in Silverlight 3


In this article we will see Projection in Silverlight, which describe how to transform an object in 3-D space using perspective transforms. In this article we will use Plane Projection, which represents a perspective transform (a 3-D-like effect) on an object.Creating Silverlight ProjectFire up Visual Studio 2008 and create a Silverlight Application. Name it as PlaneProjectionInSL3.Open the solution in Expression Blend 3 to design the application.Our basic aim of the sample is to rotate an image in 3 directions that is X, Y and Z plane. So we need three TextBlocks and three Slider Controls and an Image Control.The design will look something similar to the following:If you look into the Objects and Timeline Pane you will find the following controls are used.Now go back to Visual Studio 2008 environment.Here is the Xaml code for your reference:                                                                                                                                                                                                                          File Uplalod from Silver Light application to server location using WCF


This article will explain, How to upload a file from SilverLight client to server location using WCF.To achieve above task, follow the below steps. Assume, that Reader has a basic concept of WCF Silver Light Cross Domain Issue Hosting of WCF Service Pictorial representation of output Follow the Steps below Step 1:Create and Host the WCF Service.a. Create the Contract. This got only one method, which is taking as input a file to upload.IService1.svcusing System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.Text; namespace FileUploadService       {        [ServiceContract]    public interface IService1                         {           [OperationContract]        void SaveFile(UploadFile UploadFile);}}b. Create the Data Contract. This is going to contain the information about the uploaded file. You could either put this UploadFile Data Contract in same file with contract or in separate file.[DataContract]    public class UploadFile    {        [DataMember]        public string FileName;         [DataMember]        public byte[] File;    }c. Implement the Service. We are simply creating instance of FileStream in create mode and writing the stream into that.READ MORE>>[...]

Hello Program in Silverlight using Expression Blend & Visual Studio


Install Expression Studio (it includes Blend, Encoder, Design, Web applications) for Visual Studio so that we can start developing Silverlight by using either Visual Studio or Expression Blend. Finally, what we have here is, Expression Blend adds the features to existing Visual Studio.Creating "Hello" Program using Expression BlendLet's start Expression Blend; you will get the following splash screen at first.This screen loads all necessarily program files to memory for building Silverlight Application. After a couple of seconds, you will get the following screen.In this screenshot, look at the items in the red circle. ProjectsThis tab lets us open any recently used projects from a list, create a new project or open any existing projects. HelpThis tab lets us open the User Guide by visiting online tutorials or web communities. SamplesThis tab provides sample projects developed by Expression Blend development team from Microsoft or somebody else. Now, let's click on the "New Project" option; you will get the following screen.As marked in screenshot.Project TypesIn the above screenshot, look at the red rectangle. There are two project type options available; Silverlight and WPF. Here are some major differences between them.Silverlight and WPF (Windows Presentation Foundation) are two different products from Microsoft, but they have lots of overlap. WPF is a Microsoft technology meant for developing enhanced graphics applications for desktop platform. In addition, WPF applications can be hosted on web browsers which offer rich graphics features for web applications, but it is limited to Operating Systems. Web Browser Applications (WBA), developed on WPF technology uses XAML (read as Zameel) to host user interface for browser applications. XAML stands for eXtended Application Markup Language which is a new declarative programming model from Microsoft. XAML files are hosted as discrete files in the Web server, but are downloaded to the browsers and converted to user interface by the .NET runtime in the client browsers. WPF runs on .NET runtime and developers can take advantage of the rich .NET Framework and WPF libraries to build really cool windows applications. WPF supports 3-D graphics, complex animations, hardware acceleration etc. Silverlight is simply a subset of WPF. Silverlight is meant to be used online, while WPF is for local use. You can use Silverlight applications regardless of the operating system you use, while WPF applications are restricted to later versions of the Windows operating system. Silverlight lacks access to local resources, while WPF can utilize local resources. Silverlight only has perspective 3D support, while WPF is capable of full 3D images.Now come back to our topic, after selecting Silverlight from "Project Types", you will see five project categories. Silverlight Application + WebsiteA project with an associated website for creating rich cross-platform, web-based applications. Silverlight ApplicationA project for creating rich cross-platform, web-based applications but without an associated website.Silverlight Databound ApplicationA project that uses data and command bindings to support loose coupling between View and ViewModel.Silverlight Control LibraryA project for creating custom controls that can be reused across other Silverlight applications. Silverlight SketchFlow ApplicationA project for prototyping rich cross-platform, web-based applications.Finally, use the first one that is "Silve[...]

Creating nice tab feature in Silverlight


This article uses cool animation in silverlight to create a tab bar like look. Create two custom button controls in the sample for the two tabs you see in the picture above. Creating a custom buttonFor creating a custom button, you just have to place a button control into the work area. Right click the button control and select "Edit Control Parts (Template)" and then select "Create Empty". This will create an empty button control to work with.Now you can use any of the other controls like rectangle, ellipse, textblock to create you custom button control.Here in my sample, place one rectangle and textblock to create custom button. In sample, you can see two button control for the two tabs.Code for the two button's are:

SelectedValue and SelectedValuePath in Silverlight 4


In this article we will see about SelectedValue and SelectedValuePath while Binding. This feature is added in Silverlight 4.

SelectedValue and SelectedValuePath

These properties enable a ComboBox to behave as a look up table, that means a value can be displayed in ComboBox but when selected another property would be selected.

Let's do a sample where we can see it.

Let's have a ComboBox to display the data and a TextBlock which will display another property of the bound data of ComboBox.

Let's have sample data which can be bound to ComboBox.


The above class represents a sample Employee Entity structure.


Now in xaml we need to do proper binding as follows:


As you see in above xaml display, we have set the SelectedValuePath which is different from the displaying Path. In our case SelectedValuePath is "EmailID" and for display it is "EmployeeName".

In the TextBlock, the Text property is bound to the SelectedValue of the Element ComboBox.