DCSIMG
October 2010 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

October 2010 - Posts

Update Configurations Without Replacing Them Using Enterprise Library 5 Fluent Configuration API

Update Configurations Without Replacing Them Using Enterprise Library 5 Fluent Configuration API

I got a question today in an article I published about the fluent configuration API in Enterprise Library 5. Adding Connection Strings During Runtime With Enterprise Library Fluent Configuration APIThe question was how to add a database connection string to an existing configuration during runtime. The person who wrote the question also published a specific solution which I refactored to a general purpose solution that I’ll show in this post.

The Problem

When you use the fluent configuration API the ConfigurationSourceBuilder class has just one method to update the configuration which is UpdateConfigurationWithReplace. This method updates the configuration source and replace any existing sections with those built up with the builder. If during runtime we want to update the configuration without replacing the current configuration we have a problem.

The Solution

Use the System.Configuration API to get the current configuration and add it to the new configuration you build. Here is an implementation of how to copy all the current connection strings by using the IDataConfiguration which is part of the fluent configuration API:

private static void CopyCurrentDataConfiguration(IDataConfiguration dataConfig)
{
  // Load the configuration from the configuration file
  var configSource = ConfigurationSourceFactory.Create();
 
  // Retrieve the default datasource name
  var dataConfigurationSection = (DatabaseSettings)configSource.GetSection(DatabaseSettings.SectionName);
  var defaultDatabaseName = dataConfigurationSection.DefaultDatabase;
 
  CopyConnectionStrings(dataConfig, defaultDatabaseName);
}
 
private static void CopyConnectionStrings(IDataConfiguration dataConfig, string defaultDatabaseName)
{
  // Add the configurations from our application config file to the builder
  foreach (ConnectionStringSettings settings in ConfigurationManager.ConnectionStrings)
  {
    var configuredDatabase = dataConfig
      .ForDatabaseNamed(settings.Name)
      .ThatIs
      .AnotherDatabaseType(settings.ProviderName);
 
    if (settings.Name.Equals(defaultDatabaseName))
    {
      configuredDatabase.AsDefault();
    }
  }
}
In the first method I retrieve the Enterprise Library database settings and save the default database name. Then I use the second method to configure all the current connection strings. Since the database provider isn’t known I use the AnotherDatabaseType method to add the providers. Here is an example of how to use these methods to add another connection string to your configuration:
public void AddNewConnectionString(string databaseName, string connString)
{
  var builder = new ConfigurationSourceBuilder();
  var dataConfig = builder.ConfigureData();
  CopyCurrentDataConfiguration(dataConfig);
 
  // Add our database connections to the builder
  dataConfig
    .ForDatabaseNamed(databaseName)
    .ThatIs
    .ASqlDatabase()
    .WithConnectionString(connString);
 
  // Create a new configuration source, update it with the builder and make it the current configuration
  var newConfigSource = new DictionaryConfigurationSource();
  builder.UpdateConfigurationWithReplace(newConfigSource);
  EnterpriseLibraryContainer.Current =
    EnterpriseLibraryContainer.CreateDefaultContainer(newConfigSource);
}

Summary

The lack of current support to only updates without replacing the configurations in the fluent configuration API can cause you trouble when you need that behavior. In the post I showed a workaround to configure the EnterpriseLibraryContainer without replacing the current configurations for connection strings. This method can be applied to other configurations as well but you’ll have to write code to achieve that.

IE9 for Web Developers Session

IE9 for Web Developers Session

Next Thursday (4.11) I’m having a session about Internet Explorer 9 for web developers. Whats New in IE9?The session will take place at Microsoft Ra’anana between 08:30 and 13:00 and it is free. In the session I’m going to present IE9 (which is currently in its beta version) and talk about the main issues that every web developer will need to know when he or she is programming web sites and web applications. If you like to hear this session you can still register the event from this link.

Hope to see you there.

Posted: Oct 27 2010, 08:34 AM by Gil Fink | with no comments |
תגים:, ,

Exposing a Stored Procedure in WCF Data Service

Exposing a Stored Procedure in WCF Data Service

Today I answered a question in the data platform development forums. Exposing a Stored Procedure in WCF Data ServiceThe question was simple – how to expose a stored procedure which is mapped to an Entity Framework model through a WCF Data Service. This post will show you exactly how to do this.

The Stored Procedure

First I’ve created a the following stored procedure:

CREATE PROCEDURE dbo.GetCoursesOrderByTitle
AS
BEGIN
    SET NOCOUNT ON 
    SELECT CourseID, Title, Days, [Time], Location, Credits, DepartmentID
    FROM Course
    ORDER BY Title ASC
END

The procedure is simple and returns all the courses ordered by title. Of course this could be achieved by the use of LINQ to Data Services but I wanted to show the concept of exposing SP in your WCF Data Service.

The Model

After creating the stored procedure I’ve created the Entity Framework model which for simplicity holds only a course entity and also map the stored procedure as a FunctionImport in the model. If you want to understand how to create this sort of mapping go to a old post I wrote about it. The model will look like:

Entity Designer Diagram   Model Browser

Creating the WCF Data Service

After we have our model lets create the WCF Data Service. In order to expose the stored procedure we will have to create a service operation method. Service operations are endpoints that you can create in WCF Data Services in order to add business logic that can’t be supported by the service RESTful interface. These endpoints are consumed like any other endpoints in the REST interface that the WCF Data Service exposes. For further reading about Service Operations I recommend these two posts:

Lets look at the service:

public class SchoolDataService : DataService<SchoolEntities>
{
  public static void InitializeService(DataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("Courses", EntitySetRights.AllRead);
    config.SetServiceOperationAccessRule("GetCoursesOrderByTitle", ServiceOperationRights.AllRead);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  }
 
  [WebGet]
  public IQueryable<Course> GetCoursesOrderByTitle()
  {
    return CurrentDataSource
      .GetCoursesOrderByTitle()
      .AsQueryable();
  }
}

As you can see I use the CurrentDataSource in order to get the Entity Framework ObjectContext and then to execute the stored procedure using its FunctionImport. I also need to set the service operation access rule in order to expose the operation. If I want to consume the service operation right now and not from a client I can view the service in browser and then create the following link for example in order to call the operation:

http://localhost:43054/SchoolDataService.svc/GetCoursesOrderByTitle
 

And the result will be:
Runing Service Operation

Summary

Exposing a stored procedure through WCF Data Services can be achieved by providing service endpoints using the service operation feature. In the post I showed how you can do that by using Entity Framework.

Teched Israel 2010 Here I Come

Teched Israel 2010 Here I Come

Teched Israel 2010 is going to happen next month in Eilat between the 28-30 of November.Teched Israel 2010
On this Teched I’ll have the pleasure to present a session about building N-Tier applications by using Entity Framework 4. In the session I’m going to discuss the considerations and approaches for building these types of applications on top of EF4. For more details about the development tools and technologies track (which is the track I’m participating in) go to the following link: http://www.microsoft.com/israel/TechEd2010/Tracks/DEV.aspx

Hope to see you there.

Sela Open House – Introduction to Entity Framework 4 Slide Deck

Sela Open House – Introduction to Entity Framework 4 Slide Deck

On last Wednesday I had a Sela open house about EF4 in Sela Haifa. Sela Open House – Introduction to Entity Framework 4 Slide DeckI want to thank all the people who came to hear the session. The agenda of the open house included:

  • Introduction to EF
  • How to query and manipulate data using EF
  • EF4

I published the session slide deck and demos in my SkyDrive and you can download it from this link.

Enjoy!

Using the ControllerActivator in MVC 3

Using the ControllerActivator in MVC 3

In the previous post I showed how to use the DependencyResolver in orderUsing the ControllerActivator with Unity in MVC 3 to bring Dependency Injection behavior to a MVC 3 application. In this post I’ll show you how you can use the ControllerActivator in order to activate controllers using your own behavior.

The IControllerActivator

In MVC 3 beta a new interface was introduced – the IControllerActivator. This interface is an injection point in order to create our own behavior in order to activate controllers. That interface is discoverable using the dependency resolver. If you don’t implement the interface and register it in the dependency resolver a default behavior which is to use the Activator.CreateInstance will activate controllers.
The interface includes only one method which is the Create method. This method has the same signature like the DefaultControllerFactory’s GetControllerInstance method.
Here is a simple way to implement the IControllerActivator using the previous post’s DependencyResolver:

public class UnityControllerActivator : IControllerActivator
{
  #region IControllerActivator Members
 
  public IController Create(RequestContext requestContext, Type controllerType)
  {
    return DependencyResolver.Current.GetService(controllerType) as IController;      
  }
 
  #endregion
}

As you can see I use the current DependencyResolver to get the Unity behavior. Of course you can use other behaviors to implement the controller activation. Here is how the InitContainer method from the previous post will look like now:

private static IUnityContainer InitContainer()    
{                   
  var container = new UnityContainer();        
 
  // Register the relevant types for the         
  // container here through classes or configuration 
  container.RegisterType<IControllerActivator, UnityControllerActivator>();                
  container.RegisterType<IMessageService, MessageService>();
  return container;
}

I just added the registration of the IControllerActivator to the container. Now if you will debug the application and set a breakpoint in the Create method you will see that all controller activations will pass through the IControllerActivator. When running the application you will get the same result as in the previous post:
HomeController Result

Summary

In this post I showed how to hook up your own controller activation behavior in MVC 3. This can be achieved by using the new IControllerActivator interface. The example I showed is using the Unity IoC and could be implemented in other ways as well.

Dependency Injection in MVC 3 Was Made Easier

Dependency Injection in MVC 3 Was Made Easier

In the past I wrote a post that showed how to implement Dependency Injection Dependency Injection in MVC 3 Was Made Easierusing Unity in ASP.NET MVC framework. This post revisits that post and shows how you can do the same thing easily in MVC 3. Pay attention that the supplied code is based on MVC 3 beta and may change in the future.

The IDependencyResolver and DependencyResolver

MVC 3 introduces a new interface – the IDependencyResolver. This interface enables service location by providing two methods:

  • GetService(Type serviceType) – this method gets a service type and returns an object if the resolver succeeded in resolving the type. If the resolver couldn’t resolve the type you must return null in order to activate the default MVC behavior.
  • GetServices(Type serviceType) – this method gets a service type and returns an IEnumerable<object> of all the resolved objects. If the resolver couldn’t resolve the type you must return an empty collection to activate the default MVC behavior.

The DependencyResolver is a static class that you can use to register your custom IDependencyResolver. After you implement the IDependencyResolver, you set it in the DependencyResolver using one of the SetResolver overloaded methods. Then you will be able to use the Current property to get the current DependencyResolver in order to resolve types. If you don’t like to use the DependencyResolver ability you need to implement nothing there is default resolving behavior that is built inside the MVC implementation.

Building and Using a UnityDependencyResolver

Here is a simple implementation of a UnityDependencyResolver:

public class UnityDependencyResolver : IDependencyResolver
{
    #region Members
    
    private IUnityContainer _container;    
    
    #endregion
    
    #region Ctor
    
    public UnityDependencyResolver(IUnityContainer container)
    {
      _container = container;
    }
    
    #endregion
    
    #region IDependencyResolver Members
    
    public object GetService(Type serviceType)
    {
      try
      {
        return _container.Resolve(serviceType);
      }
      catch (Exception ex)
      {
        return null;
      }
    }
    
    public IEnumerable<object> GetServices(Type serviceType)
    {
      try
      {
        return _container.ResolveAll(serviceType);
      }
      catch (Exception ex)
      {
        return new List<object>();
      }
    }
    
    #endregion
}

In order to use this resolver the appropriate place to build the container is the Global.asax file. Here is the implementation:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new HandleErrorAttribute());
    }
    
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
      routes.MapRoute(
          "Default", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
      );
    
    }
    
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      
      RegisterGlobalFilters(GlobalFilters.Filters);
      RegisterRoutes(RouteTable.Routes);
      
      var container = InitContainer();
      DependencyResolver.SetResolver(new UnityDependencyResolver(container));       
    }
    
    private static IUnityContainer InitContainer()    
    {                   
      var container = new UnityContainer();        
    
      // Register the relevant types for the         
      // container here through classes or configuration                      
      container.RegisterType<IMessageService, MessageService>();
      return container;
    }
}

As you can see I added the initialization of the container and also I set the DependencyResolver to the Unity implementation. The Message service and the controller are the same classes that I showed in my previous post:

public interface IMessageService 
{ 
  string GetMessage();
}
 
public class MessageService : IMessageService
{
  #region IMessageService Members
 
  public string GetMessage()
  {
    return "Hello Controller!";
  }
 
  #endregion
}

and

public class HomeController : Controller
{
  #region Members     
  
  [Dependency]    
  public IMessageService MessageService { get; set; }
           
  #endregion
 
  #region Actions    
 
  public ActionResult Index()
  {
    ViewModel.Message = MessageService.GetMessage();
 
    return View();
  }
 
  public ActionResult About()
  {
    return View();
  }
 
  #endregion
}

After running this example we will get the following expected result:
HomeController Result

Summary

Let sum up, in MVC 3 beta there is a new way to use DI and IoC containers by implementing the IDependencyResolver interface and registering it in the DependencyResolver static class. There are other injection points that you can use like the IControllerActivator which I’ll write about in a following post.

Sela Open House – Entity Framework 4

Sela Open House – Entity Framework 4

On this Wednesday evening I’m going to deliver an open house in Sela Haifa. Sela Open House – Entity Framework 4 The session is going to include an introduction to Entity Framework, How to query and manipulate data and a section about Entity Framework 4. If you are interested and want more details about the event or want to register you can go to the following link. For the list of open houses that Sela conducts go to this link.

I hope to see you there.

Back to Basics – OnBeforeUnload Event

Back to Basics – OnBeforeUnload Event

There are times when you need to warn your users about unsaved changes before they leave the web page that they are working on. In these times the simple solution is to use the OnBeforeUnload javascript event. In this post I will explain what is this event and how to use it.

OnBeforeUnload Event

The OnBeforeUnload event is fired prior to a page being unloaded. This is the last place that you can prevent the loss of unsaved data before leaving the page. In order to use the event you can wire a handler (javascript function) and use it to do things and also warn your user from the loss of data. If a string is being assigned as the return value of the handler a dialog will appear and will give the users the option to stay on the current page and retain that string. The dialog’s text can’t be changed but the return string will be added to it. Here is a simple example of how to use the event:

<script type="text/javascript">
    window.onbeforeunload = function () {
        return 'You have unsaved data! do you really want to exit?'; 
    }
</script>

and the result when you will close the web page will be:
OnBeforeUnload Fired

Summary

The OnBeforeUnload javascript event can be used in order to prevent the loss of valuable data when users exit a web page. It can also annoy your users since whenever they will try to leave the page they will get the dialog box. So my advice – use this solution only when there is no other choice.

Posted: Oct 12 2010, 10:52 AM by Gil Fink | with 1 comment(s) |
תגים:,

Using Overlay Icon API to Make Client Notifications in IE9

Using Overlay Icon API to Make Client Notifications in IE9

Ever wanted to notify your site clients/users while they are surfing in your site.Using Icon Overlay API to Make Client Notifications in IE9 In one of the applications that I helped to build this was a customer requirement. So in the past you could have implemented a blinking behavior that will make the icon of the browser blinking. Not a very user friendly behavior for my taste. With IE9 you now able to use the new SiteMode Overlay Icon javascript behavior which is part of the site pinning feature.

Overlay Icon API

The Overlay Icon API include two simple methods:

  • msSiteModeSetIconOverlay – the method enables to communicate alerts, notifications and statuses to the site users by adding an icon on top of the the existing web site icon. The method takes two parameters – an image url and a tooltip value.
  • msSiteModeClearIconOverlay – the method clears any existing overlay icon.

Pay attention that this behavior will only work in a pinned site so check whether the site is in SiteMode before using these methods.

Overlay Icon In Action

When the following page is loaded in a pinned site the result will be an overlay icon on top of the pinned site icon:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title>My application</title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <meta name="application-name" content="My Application" />
    <meta name="msapplication-tooltip" content="My Application" />
    <meta name="msapplication-starturl" content="./" />
    <meta name="msapplication-task" content="name=My Blog;action-uri=http://blogs.microsoft.co.il/blogs/gilf;icon-uri=/favicon.ico" />
    <meta name="msapplication-task" content="name=My Linkedin Profile;action-uri=http://il.linkedin.com/in/gilfink;icon-uri=http://www.linkedin.com/favicon.ico" />
    <script type="text/javascript">
        window.external.msSiteModeSetIconOverlay('/info.ico', 'Attention Needed');
    </script>
</head>
<body>
    <form>
    <div class="page">
        <div class="header">
            <div class="title">
                <h1>
                    My ASP.NET Application
                </h1>
            </div>
            <div class="loginDisplay">
                <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
                    <AnonymousTemplate>
                        [ <a href="~/Account/Login.aspx" id="HeadLoginStatus" runat="server">Log In</a>
                        ]
                    </AnonymousTemplate>
                    <LoggedInTemplate>
                        Welcome <span class="bold">
                            <asp:LoginName ID="HeadLoginName" runat="server" />
                        </span>! [
                        <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out"
                            LogoutPageUrl="~/" />
                        ]
                    </LoggedInTemplate>
                </asp:LoginView>
            </div>
            <div class="clear hideSkiplink">
                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false"
                    IncludeStyleBlock="false" Orientation="Horizontal">
                    <Items>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" />
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
                        <asp:MenuItem NavigateUrl="~/IconOverlay.aspx" Text="Icon Overlay" />
                        <asp:MenuItem NavigateUrl="~/msPerformance.aspx" Text="msPerformance" />
                    </Items>
                </asp:Menu>
            </div>
        </div>
        <div class="main">
            <input type="button" value="Remove Icon Overlay" onclick="window.external.msSiteModeClearIconOverlay();" />
        </div>
        <div class="clear">
        </div>
    </div>
    <div class="footer">
    </div>
    </form>
</body>
</html>

The result of running this code can look like:
Icon Overlay Example
The full page can look like:
Icon Overlay
and when pressing the Remove Overlay Icon button it will remove the added information icon.

Summary

IE9 brings a new way to notify users about things that happen in web sites/applications. Using the simple but powerful overlay icon API in pinned sites can make your web site/application more user friendly and more shiny.

Posted: Oct 11 2010, 08:03 AM by Gil Fink | with 1 comment(s) |
תגים:, ,

Using Javascript to Measure Web Page Performance with IE9

Using Javascript to Measure Web Page Performance with IE9

One ability that currently available in IE9 is the new msPerformance javascript object that Using Javascript to Measure Web Page Performance with IE9enables developers to measure real-world performance of websites. In this post I’ll explain what is msPerformance and how you can use it to measure web page performance.

The msPerformance Object

Wanting a web application that performs great is a very regular and crucial demand in these days. With IE9 beta developers have a new set of javascript profiling API integrated at the DOM’s core – msPerformance object. The msPerformance captures key timing information about the load of the root document and also network activity that occurs on the page. This data is available from the DOM after the page was loaded. Using these metrics the developer is able to measure where the browser is spending it’s time during the run of the web application. This of course enables performance tuning when the developer finds bottlenecks or other problems.

How to Use msPerformance?

The msPerformance which is located under the window DOM object exposes three properties:

Those objects hold a lot of properties and information about the performance of the web page that is currently running. The following code example shows how to fill a table with some web page performance measurements:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="msPerformance.aspx.cs"
    Inherits="WebApplication5.msPerformance" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>msPerformance Example</title>
    <script type="text/javascript">
   1:  
   2:         function InsertPerformanceData() {
   3:             if (window.msPerformance != null) {
   4:                 var w = window;
   5:                 var navStart = w.msPerformance.timing.navigationStart + "ms";
   6:                 var navStartTime = Date(w.msPerformance.timing.navigationStart);
   7:  
   8:                 var loadEnd = w.msPerformance.timing.loadEventEnd + "ms";
   9:                 var loadEndTime = Date(w.msPerformance.timing.loadEventEnd);
  10:  
  11:                 var navigation = w.msPerformance.timingMeasures.navigation + "ms";
  12:  
  13:                 var runtime = (w.msPerformance.timing.loadEventEnd - w.msPerformance.timing.navigationStart) + "ms";
  14:  
  15:                 document.getElementById("ticksNavigationStart").innerText = navStart;
  16:                 document.getElementById("timeNavigationStart").innerText = navStartTime;
  17:  
  18:                 document.getElementById("ticksLoadEnd").innerText = loadEnd;
  19:                 document.getElementById("timeLoadEnd").innerText = loadEndTime;
  20:  
  21:                 document.getElementById("timeNavigation").innerText = navigation;
  22:  
  23:                 document.getElementById("timeRuntime").innerText = runtime;
  24:             }
  25:         }        
  26:     
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <th>
                    Event
                </th>
                <th>
                    API
                </th>
                <th>
                    TICKS
                </th>
                <th>
                    TIME
                </th>
            </tr>
            <tr>
                <td>
                    Navigation Start
                </td>
                <td>
                    window.msPerformance.timing.navigationStart
                </td>
                <td id="ticksNavigationStart">
                </td>
                <td id="timeNavigationStart">
                </td>
            </tr>
            <tr>
                <td>
                    Load End
                </td>
                <td>
                    window.msPerformance.timing.loadEnd
                </td>
                <td id="ticksLoadEnd">
                </td>
                <td id="timeLoadEnd">
                </td>
            </tr>
            <tr>
                <td>
                    Run Time
                </td>
                <td>
                    window.msPerformance.timingMeasures.navigation
                </td>
                <td>
                </td>
                <td id="timeNavigation">
                </td>
            </tr>
            <tr>
                <td>
                    Run Time
                </td>
                <td>
                    timing.loadEnd - timing.navigationStart
                </td>
                <td>
                </td>
                <td id="timeRuntime">
                </td>
            </tr>
        </table>
        <input type="button" onclick="InsertPerformanceData();" value="Show Performance Data" />
    </div>
    </form>
</body>
</html>

In this simple page when the button is clicked I first check that the windows.msPerformance exists. Then I pull out some performance data and show it to the user. After pushing the button an example of the table that can be generated could be:
msPerformance Data 
Pay attention that the performance data is available only after the page was loaded!

Summary

IE9 includes a lot of features that can help developers in their daily activities. One of the these features is the new msPerformance javascript object which can help developers with their web pages performance tuning. Currently, this feature isn’t interoperable with other browsers so don’t try to use it outside IE9

jQuery Alert Dialogs Plug-in

jQuery Alert Dialogs Plug-in

When you want to alert the user in the client side of a web application probably you are embarrassed jQuery Alert Dialogs Plug-in(or you don’t give a damn) when you use Javascript built-in alerts. I know I do. Javascript built-in alerts are very ugly IMHO and therefore I try to use alternatives instead. In this post I’ll show a very useful alternative that I’ve been using lately in more then one project – the jQuery Alert Dialogs plug-in.

jQuery Alert Dialogs Plug-in

One of the benefits of using jQuery is the amount of jQuery plug-ins that exists in jQuery eco-system. But the amount of plug-ins also makes it very difficult to find your desired plug-in for each behavior you need. One of the plug-ins I’m using frequently is the jQuery Alert Dialogs. The plug-in “aims to replace the basic functionality provided by the standard JavaScript alert(), confirm(), and prompt() functions”. The plug-in also simulate the use of these standard functions and also gives you the power to create your own style.

How to use the plug-in?

First you will have to download the plug-in from this link – jQuery Alert Dialogs. Also you will have to download jQuery UI Draggable plug-in which the plug-in has dependency on it (or download all the jQuery UI package like I did). After you downloaded all the relevant scripts you will have to add the plug-ins to your web application. Here is how my sample solution was ordered:
Sample Solution 
In the default page I’ve added the following links in the head section:

<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.alerts.js" type="text/javascript"></script>
    <link href="Content/Style/jquery.alerts.css" rel="stylesheet" type="text/css" />
</head>

Now you will be able to use the plug-in included methods:

  • jAlert(message, [title, callback]) – creates an alert.
  • jConfirm(message, [title, callback]) – creates a confirm alert which handle the confirmation in the callback function you supply.
  • jPrompt(message, [value, title, callback]) – creates a prompt alert which handle the value the user type in the callback function you supply.

The following example shows how to use the alert and prompt:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Defualt.aspx.cs" Inherits="WebApplication6.Defualt" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.alerts.js" type="text/javascript"></script>
    <link href="Content/Style/jquery.alerts.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnAlert").click(function () {
                jAlert('Pushed the alert button', 'Alert Dialog');
            });
            $("#btnPrompt").click(function () {
                jPrompt('Type some value:', '', 'Prompt Dialog', function (typedValue) {
                    if (typedValue) {
                        jAlert('You typed the following ' + typedValue);
                    }
                });
 
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Alert Me" id="btnAlert" />
        <input type="button" value="Prompt Me" id="btnPrompt" />
    </div>
    </form>
</body>
</html>

and the output of pushing the prompt button:
Prompt Output

Summary

The jQuery Alert Dialogs plug-in is a very useful plug-in. Avoid using the built-in alerts and start using a more styled and beautiful alerts. If the supplied style isn’t good for your needs then customize it and make it more suitable.

Microsoft MVP for the Second Time

Microsoft MVP for the Second Time

A few minutes ago I got the mail from Microsoft that informed me that I’m a Microsoft MVP for the second time.MVP_FullColor_ForScreen The mail is written as follows: “Congratulations! We are pleased to present you with the 2010 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Data Platform Development technical communities during the past year.”

I would like to say many thanks to the following people - Guy Burshtein, Maor David, All my colleagues in Sela Group, all my friends and of course You my blog readers for helping me keep the MVP Award for another year!