Thursday, March 5, 2009

Open source Web templates : http://www.oswt.co.uk

Open source Web templates : http://www.oswt.co.uk, An interesting site where lots of free web templates available for download. I must say it’s a nice site.

If we are thinking about a quick product that needs some styling and right now we don’t have enough time to invest on design, I would recommend find some useful template from here and using it right way.

image

The templates are not that much rich but not bad either, specially for students who are developing web product for there class assignment can take advantages of using good theme in there projects.

Monday, February 9, 2009

A Beginner's Guide for "Using WCF in JavaScript using Asp.net Ajax"

Contents

    1. Development Platform
    2. Introduction
    3. Using Ajax-Enabled WCF Service item template
    4. Using Service Interface defined in a class library
    5. Configure the Web Application To Use TODO Service
    6. Using Service In JavaScript
    7. Summery
    8. References

Development Platform

  • Visual Studio 2008 SP1
  • Dot.net Framework 3.5 SP1
  • Asp.net Ajax
  • IIS7 or VS Integrated Web Server [WCF and SVS file configured]
  • Windows Vista

Introduction

WCF (Windows communication foundation) added lot of new capability in Microsoft application development platform, particularly in case of how applications communicate to each other. In this article we are going to see how WCF can be used directly from clients JavaScript code. Its a very cool future provided by asp.net Ajax. In this article we are not going to cover every theory about WCF internals rather we only remained focused on how to use the service directly from JavaScript. So no behind the scene stuff of how asp.net or dot net runtime manage this feature.

To demonstrate the ideas and facts we are going create a demo solution with two projects. So with no time waste create a blank solution and save it. Now add a class library project to the solution. Name the class library as "ServiceLibrary". Now Add another web application project to the solution and name it as WEBUI. We are going to see two approach to add WCF service that can be consumed from JavaScript.

  1. Using Ajax-Enable WCF Service item template
  2. Using Service Interface defined in a class library

Using Ajax-Enabled WCF Service item template

Its a very strait forward way to use WCF service in JavaScript. Right Click on the web application project and select add new item. Select Ajax-Enabled WCF Service item template name it as "HelloWorldService.svc" and click ok. Wizard will add a HelloWorldService.svc file to solution as expected. This file have a code behind file as well. If you open the HelloWorldService.svc in xml file editor you will see a markup like this

<%@ ServiceHost Language="C#" Debug="true" Service="WebUI.HelloWorldService"

CodeBehind="HelloWorldService.svc.cs" %>










And if you open the code behind file you will se code some thing like this




namespace WebUI
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloWorldService
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}

// Add more operations here and mark them with [OperationContract]
}
}



Visual Studio 2008 automatically add the necessary configuration for you in the web.config file so no need to configure any thing in web.config. Now go ahead and add a method like HelloWorld() which returns a string "HelloWorld" and add [OperationContract] method attribute to the method. we will explain what the attributes are for later in this article. Now add a page to web application project and name it as "HelloWorldTest.aspx". Drag drop a script manager item from visual studio tool box. Inside the ScriptManager tag add service reference of the service. Bellow a example code is give.




<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/HelloWorldService.svc" />
</Services>
</asp:ScriptManager>



Now add a button and a textbox to the page and on button click use a JavaScript function to call the service. when you will write the service call function Visual Studio 2008 Html Editor will provide intellisense to write necessary function call. Full code of html part is give bellow.




<form id="form1" runat="server">
<div>
<script language="javascript" type="text/javascript">
function GetValueFromServer() {
HelloWorldService.HelloWorld(onSuccess, onFailure);
}

function onSuccess(result) {
document.getElementById('txtValueContainer').value = result;
}

function onFailure(result) {
window.alert(result);
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/HelloWorldService.svc" />
</Services>
</asp:ScriptManager>
<input id="btnServiceCaller" type="button" value="Get Value" onclick="GetValueFromServer()"; />
<input id="txtValueContainer" type="text" value="" />
</div>
</form>



Note that when calling the service we have passed two method one is for callback and other one is for error callback. If we need to pass any parameters to the function parameters will go first and then the call back. So if we have a function name getvalue which take two string parameters as argument we are going to call the function as [NameSpaceName].[ServiceName].getvalue("value one","value two",on_success,on_error); where on_sucess and on_error are callback and error callback respectively.



Using Service Interface defined in a class library



So we have looked how to use a Ajax-Enabled WCF Service using item template. Now we are going to see more traditional WCF Service implementation and we are also going to see how we can expose this service for Asp.net Ajax. when we created the class library project by default its not added with the service model and runtime serialization support which is necessary to run WCF. So we got to add the necessary service references. so go ahead and right client on class library project and select add reference and then select the references.




  1. System.Runtime.Serialization


  2. System.ServiceModel





In this phase we are going to use a TODO Management example to demonstrate the whole idea. Add A Service Based Database and then create a TODO Table with ID,Description and Status Field. Now Add A LinkToSQL class file from item template. Drag Drop the table TODO from database to link to SQL Class File designer. Now Click on the designer surface and from property window change the Serialization Mode to Unidirectional. Now our designer generated Link to SQL classes are ready to use for WCF. If you want to use custom user defined types you must set [DataContract] class attribute to your class and you must add [DataMember] property attribute to each property of the class you want to expose to WCF.



Now we are going to add a service interface like this




namespace ServiceLibrary
{
[ServiceContract(Namespace = "ServiceLibrary")]
interface IToDoService
{
[OperationContract]
ToDo GetToDo(long ID);
[OperationContract]
ToDo AddToDo(ToDo toDo);
[OperationContract]
bool DeleteToDo(ToDo todo);
[OperationContract]
ToDo UpdateToDo(ToDo todo);
[OperationContract]
List<ToDo> GetAllToDo();
}
}



Note that we have mentioned a name space in side the ServiceContract interface Attribute. This is very important. we are going to use this name as the service name in side the JavaScript to access the services. Now we are going to add the implementation to this service interface the code is given bellow. Please note that in bellow code i have used [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] class attribute, this is must requirement for exposing the service as asp.net Ajax enabled WCF service.




namespace ServiceLibrary
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ToDoService : IToDoService
{
#region IToDoService Members
public ToDo GetToDo(long ID)
{
DataClasses1DataContext context = new DataClasses1DataContext();
var toDos = from p in context.ToDos
where p.ID == ID
select p;
List<ToDo> listTodos = toDos.ToList();
if (listTodos != null && listTodos.Count > 0)
{
return listTodos[0];
}
else
{
return null;
}
}

//all the methods is not shown

#endregion
}
}



Configure the Web Application To Use TODO Service



Now that we have defined all the necessary stuff to run our TODO Application its time to expose the service to the client as a asp.net Ajax enabled WCF service. For this we are going to add a Ajax-Enabled WCF Service .svc file. And we will get rid of the code behind file. or we can add a xml file or text file and then rename it to ToDoService.svc. Open it with xml editor and put directive like bellow



<%@ ServiceHost Language="C#" Debug="true" Service="ServiceLibrary.ToDoService" %>



Now we are going to put necessary configuration to run this service in web.config, the code is given bellow



 




<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AspNetAjaxBehavior">
<enableWebScript />
</behavior>
<behavior name="WebUI.HelloWorldServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
</service>
<service name="ServiceLibrary.ToDoService">
<endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding"
contract="ServiceLibrary.IToDoService" />
</service>
<service name="WebUI.HelloWorldService">
<endpoint address="" behaviorConfiguration="WebUI.HelloWorldServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebUI.HelloWorldService" />
</service>
</services>
</system.serviceModel>



Now right click on the file and select view in browser to see the service is up and running well. Few things must be mentioned before moving to next phase. You must add serviceHostingEnvironment and set its aspNetCompatibilityEnabled="true" to be able to use wcf service in asp.net with its features like httpContext, Session etc.



Using Service In JavaScript



Now use the service just like HelloWorldService we have previously used. Bellow I have given few example code to make things clear. Bellow the ScriptManager Mark up is given. Note that we have added a clientServiceHelper.js file. We have put all the client to WCF communication JavaScript functions in that file.




<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Script/ClientServiceHeler.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="~/ToDoService.svc" />
</Services>
</asp:ScriptManager>



We have used asp.net Ajax client side object oriented model to write bellow JavaScript client code which are the part of clientServiceHelper.js.




Type.registerNamespace("ServiceClients");

ServiceClients.ToDoClient = function() {
}

ServiceClients.ToDoClient.prototype = {

AddToDo: function(todo, callback, errorCallBack) {
ServiceLibrary.IToDoService.AddToDo(todo, callback, errorCallBack);
},

DeleteToDo: function(todo, callback, errorCallBack) {
ServiceLibrary.IToDoService.DeleteToDo(todo, callback, errorCallBack);
},

UpdateToDo: function(todo, callback, errorCallBack) {
ServiceLibrary.IToDoService.UpdateToDo(todo, callback, errorCallBack);
},

GetAllToDo: function(callback, errorCallBack) {
ServiceLibrary.IToDoService.GetAllToDo(callback, errorCallBack);
},

dispose: function() {
//disposed
}
}

ServiceClients.ToDoClient.registerClass('ServiceClients.ToDoClient', null, Sys.IDisposable)

// Notify ScriptManager that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();



Summery



In this article we have seen how we can use Ajax-Enable WCF Service item template. The we have seen how we can use a service interface based wcf service. we have also seen how to configure web.config to use the services, last of all we have seen how we can add service reference in ScriptManager. Few things must be mentioned before ending this article we can also add service reference in c# code below a simple code example is given.




ScriptManager manager = ScriptManager.GetCurrent(Page);
ServiceReference reference = new ServiceReference("ToDoService.svc");
manager.Services.Add(reference);



If the beginners encounter problem of not understanding any particular portion of the article please drop a message. You can learn the ABC of WCF here. If you have any difficulty configuring WCF in IIS please see this article here.



References




  1. http://msdn.microsoft.com/en-us/library/aa480190.aspx [WCF - ABC]


  2. http://munna.shatkotha.com/Blog/post/2008/07/08/Install-WCF-Aspnet-in-IIS7.aspx [Configure WCF]


  3. http://msdn.microsoft.com/en-us/library/bb514961.aspx [Expose WCF to Client Script]


  4. http://msdn.microsoft.com/en-us/library/bb763177.aspx [Configure WCF in asp.net Environment]


  5. http://msdn.microsoft.com/en-us/library/bb398785.aspx [Web Service in asp.net]


  6. http://peterkellner.net/2008/09/14/wcf-web-service-json-vs2008/ [Article that discussed the same concept]

Thursday, January 8, 2009

Controls that are not compatible with UpdatePanel controls

We all know that update panel is one of the wonder of asp.net Ajax and really gave a very good first impression on everyone. After mounts past some problems are starting to popup as some of the controls are not compatible with update panel. 

We might need to use other tricks to achieve required feature while using the bellow controls. I have done a little research on Update panel and found that bellow listed controls are not compatible with UpdatePanel.

The following ASP.NET controls are not compatible with partial-page updates, and are therefore not designed to work inside an UpdatePanel control:

  • Treeview
  • Menu control
  • FileUpload
  • HtmlInputFile.
  • GridView
  • DetailsView
  • Login
  • PasswordRecovery
  • ChangePassword
  • CreateUserWizard    
  • The Substitution control

We might skip Updatepanel or use some kind of trick to overcome the problems with the above controls while using Updatepanel.

Source

http://msdn.microsoft.com/en-us/library/cc295545.aspx

Thursday, December 25, 2008

Multiline editable combo in WPF

Today I am going to share a interesting learning experience that I had about editable combo box. In one of my project we have a requirement that all editable text need to support  multi-line support. very easy stuff. Just set IsEditable property of combo box to "true".

   1: <ComboBox x:Name="ddlCombo" 

   2: MaxDropDownHeight="200"  

   3: FontWeight="Normal" 

   4: Text="{my:CellEditorBinding}"  

   5: BorderThickness="0" 

   6: Padding="0" Margin="0" 

   7: IsEditable="True"  

   8: Foreground="Black" />





Now, the problem is, in couple of our grid cell we had combo box with editable feature. User can write their own choice or they can pick a value from the drop down list. since the text box of combo is a text editing area. clients wanted warp text with new line in the edit area of the combo box. After few minutes of "R & D" we discovered the way to override the control template and modified the textbox of combo box in such a way so that it can take multi-line and warp text content in combo box.



To give a textbox warped text feature i just added the following code, and it will do the job.







   1: <TextBox x:Name="PART_EditableTextBox"

   2:             Style="{x:Null}" 

   3:             Template="{StaticResource ComboBoxTextBox}" 

   4:             HorizontalAlignment="Left" 

   5:             VerticalAlignment="Center" 

   6:             Margin="3,3,23,3"

   7:             Focusable="True" 

   8:             Background="Transparent"

   9:             Visibility="Hidden"

  10:             TextWrapping="Wrap" 

  11:             AcceptsReturn="True"                                 

  12:             IsReadOnly="{TemplateBinding IsReadOnly}"/>





Best of luck and happy programming.

Thursday, November 6, 2008

Light box effect with WPF.

Light box effect is becoming a trend to show modal dialog in both web and desktop applications now a days. In WPF we can also achieve this goal with little effort. Its not actually a light box but give users a elusion of a light box.

Wpf Container controls display last element of the logical tree on top of all visual elements. we have used that feature to produce this effect. First of all we are going to add a grid as the root element of a page or window, and we are going to add the dialog XAML as the last child of the grid.


<Border x:Name="panelDialog" Visibility="Collapsed">
<Grid>
<Border Background="Black" Opacity="0.49"></Border>
<!--While Xmal Content of the dialog will go here-->
</Grid>
</Border>




Just put two function for hide and display the dialog. Total Code is given bellow. In bellow code I have Displayed a loading screen with light box effect. When displaying modal dialog just invoke show and hide wait screen methods. Its good to send your cpu expansive jobs to background thread and use dispatcher to update UI while you are in background thread.


 


XAML CODE





<Page x:Class="Home">
<Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<!--All the contents will go here-->
</ScrollViewer>
<Border x:Name="panelLoading" Visibility="Collapsed">
<Grid>
<Border Background="Black" Opacity="0.49"></Border>
<local:TMEWaitScreen></local:TMEWaitScreen>
</Grid>
</Border>
</Grid>
</Page>




C# CODE




#region About Wait Screen
/// <summary>
/// Show wait screen before a web request
/// </summary>
public void ShowWaitScreen()
{
Process del = new Process(ShowWaitScreenUI);
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, del);
}
private void ShowWaitScreenUI()
{
panelLoading.Visibility = Visibility.Visible;
}
/// <summary>
/// Hide a wait screen after a web request
/// </summary>
public void HideWaitScreen()
{
Process del = new Process(HideWaitScreenUI);
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, del);
}
private void HideWaitScreenUI()
{
panelLoading.Visibility = Visibility.Collapsed;
}
#endregion


Best of luck and happy programming.

Friday, October 24, 2008

Display html Content in WPF (XBAP)

Story of displaying html content in WPF or XBAP (WPF browser application) begins with a simple requirement, we have to show printer friendly version(which is a html content) on few reports in our project that run on Internet and which is a WPF browser application. Well it is a quite simple requirement and most of the application needs such kind of printer friendly version that run on web. There are several techniques or solutions to this problem we are going to take a look each of a kind in short.

WPF Frame Element

First of all we are going to see a simple solution to this problem. WPF have an element called Frame element. Frame element is used to display wpf  page and user control. We can also use a frame element to show our html contents. User need to set the source property of the "Frame" to Uri of the Html Page. Here is a simple code example that shows how to do that.

<Grid Height="300" Width="479">
<Frame x:Name="myframe" Source="C:\TabotGenerator\TestXbap\HTMLPage1.htm"></Frame>
</Grid>



Few things must need to take in concern before using frame wpf frame or other elements don't support uri other than the site of origin in partial trust mode. so report handler html or aspx or custom handler must be in the site of origin. And while navigating the source must be marked as a Absolute Uri using the "UriKind" Enum.



Open a new Browser Window



Second solution to show html page in wpf is to use a navigation window object of wpf. Its kind of a mini browser where any wpf page or any resource that is viewable can be loaded. The following code snippet will show how to use a navigation window to show html page.





NavigationWindow window = new NavigationWindow();
Uri source = new Uri("http://mydomain/myapp/report.aspx", UriKind.Absolute);
window.Source = source;window.Show();




In the same category we can also use Hyperlink to Popup more traditional kind of browser window, that is popup a IE browser window just like traditional printer friendly version on sites. but to lunch a new browser window target name property must be set to _blank or some thing like that. bellow code snippet is given. Note that hyperlink element is created inside a label. WPF is by designed like this. hyperlink must be inside text elements for example label and text block.





<Label>
<Hyperlink TargetName="_blank" NavigateUri="http://mydomain/myapp/report.aspx"></Hyperlink>
</Label>




3.5 SP1 Web Browser Control



Microsoft dot net framework 3.5 Service pack one is equipped with a new control type called web browser control. Web browser control is a very smart control supporting navigation to normal Uri source and also displays html content dynamically. User can set its source property to display html page which is traditional way just like two above mentions technique. Web browser control also support three life saving methods.





Uri source = new Uri("http://mydomain/myapp/report.aspx", UriKind.Absolute);
WebBrowser browser = new WebBrowser();
this.Content = browser;browser.Navigate(source);
browser.NavigateToStream(new FileStream("Pathofthehtmlfile",FileMode.OpenOrCreate));
browser.NavigateToString("<html> whole html content </html>");




 



Among the above mention methods “NavigateToString” is very usefull in case we need to display html content which is available to us as a string data. And we don’t have to use any printer friendly handler page on the source of origin site in this case. We can retrieve our printer friendly html content using a string content and then just use NavigateToString to display the conent. We can also use template html to generate html content for printer friendly version.



Using Windows Forms Web Browser control



In case we are not using dot net framework 3.5 sp1 we can still implement the technique to display html content directly in browser without having a ASPX handler page in the site of origin of the XBAP. We are going to use a legacy browser control of window forms. Window forms have a built-in browser control from the release of Microsoft .net framework 2. We can also use this control using this legacy browser control via windows forms host control of WPF.




<Grid Height="300" Width="479"><WindowsFormsHost Name="windowsFormsHost1" /></Grid>



 




System.Windows.Forms.WebBrowser browser = new System.Windows.Forms.WebBrowser();
windowsFormsHost1.Child = browser;
//do assign the html content directly
browser.DocumentText = "our html string";
//or do assign the uri of the html page
Uri source = new Uri("http://mydomain/myapp/report.aspx", UriKind.Absolute);
browser.Navigate(source);




Conclusion



Using the above solution one thing must be kept in mind that any time you can encounter with the system.net.permission error or perhaps partial security violation error. for this you need to modify your code in such a way so that you can get the best out of it. In my case I will use the new 3.5 sp1 browser control. I will retrieve the html content via some web service or WCF service and then assign the string to web browser using navigate to string method. Best of luck and happy programming.