DCSIMG
September 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 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

September 2010 - Posts

MSDN Subscriber Giveaway Form is Closed

MSDN Subscriber Giveaway Form is Closed

MSDN Subscribers 
The registration form for the MSDN Ultimate Subscribers giveaways is closed.
As I wrote in the previous post I will choose the new owners of the subscriptions after the form will be closed and the names are:

  • Adiel Sharabi
  • Eli Shalom

Thanks for all the participants who filled the form and didn’t get the giveaways. I hope that even so you will continue and contribute to the development community.

MSDN Subscribers Giveaways Reminder

MSDN Subscribers Giveaways Reminder

In a previous post I wrote about two MSDN subscribers which I’m going to give away. As I wrote I’m giving this valuable gift to people in the Israeli development community that will be committed to volunteering at least 100 hours to develop open source projects during the following year.
 MSDN Subscribers

This post is only a reminder that on the 26 of September (in four days) the applying form will be closed. 
Terms of participating:

  • You need to be an Israeli (because if you will be selected I’ll be able to give you the subscriber personally).
  • You are committed to volunteer to at least 100 hours to help developing an open source project during the following year.
  • Filling up the applying form.

Thanks for those who already applied!

Adding Tasks and Jumplists to Pinned Sites in IE9

Adding Tasks and Jumplists to Pinned Sites in IE9

In a previous post I explained what is site pinning and how you can pin a site to Windows 7 taskbar. Adding Tasks and Jumplists to Pinned Sites in IE9 In this post I’m going to explain how to add tasks and jumplists to the pinned site from the previous post example.

Adding Tasks to a Pinned Site

When we pin a site to the Windows 7 taskbar we can include tasks to operate on the pinned site. With this feature you can add tasks for common behavior of your site. For example, in a library site you can add a task to redirect to the last borrowed book page to help the user or a task for seeing the list of books available in the library. 
So how do I achieve the tasks behavior? this is easy – use the new meta tag msapplication-task at the head of the web page. The msapplication-task has a content format of three parameters:

  • name – the name of the task.
  • action-uri – the link to perform when that task is clicked.
  • icon-uri – the link for the icon to show beside the task.

This is an example of a task that redirect to my blog you can see the content format which expect the parameters to be comma delimited:

<meta name="msapplication-task" content="name=My Blog;action-uri=http://blogs.microsoft.co.il/blogs/gilf;icon-uri=/favicon.ico" />

Here is the new head of the previous post example which include two new tasks:

<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" />
</head>

Here is how it will be shown after the site pinning:

Tasks Example

Adding Jumplist to a Pinned Site

When we want to add Jumplist functionality to the pinned site we should be familiar with the Jumplist API that is available in IE9. This API enables the creation, update, show and clear of a Jumplist. This API includes four Javascript methods:

Here is an example for a function that creates a simple Jumplist with one item:

<script type="text/JavaScript">
    function AddJumpList() {
        window.external.msSiteModeCreateJumplist('My Favorite Sites');
        window.external.msSiteModeAddJumpListItem('About Page', '/About.aspx', '/favicon.ico');
        window.external.msSiteModeShowJumplist();
    }
</script>

In the example I’ve put this function in the head of the application master page (of course it should be a part of an external js file):

<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">
        function AddJumpList() {
            window.external.msSiteModeCreateJumplist('My Favorite Sites');
            window.external.msSiteModeAddJumpListItem('About Page', '/About.aspx', '/favicon.ico');
            window.external.msSiteModeShowJumplist();
        }
    </script>
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

In the home web page of the application I added this script which uses the msIsSiteMode to check whether the site is pinned and if so call the AddJumpList function from the previous master page example:

<script type="text/javascript">
    if (window.external.msIsSiteMode()) {
        AddJumpList();
    }
</script>

Here is the pinned site with the added Jumplist:
Jumplist Example 

Summary

In the post I showed how you can add tasks and Jumplists to your web application using simple things like meta tags and Javascript functions. This ability adds to the user experience with IE9 were very common tasks or operations can be exposed as part of the Windows taskbar.

Posted: Sep 22 2010, 06:02 PM by Gil Fink | with 4 comment(s) |
תגים:, ,

IE9 Site Pinning

IE9 Site Pinning

One of the new features that will come with IE9 is the pinned sites ability. IE9 Site PinningIn this post I’m going to explain what is site pinning and show an example for how to do this stuff. If you want to read about this new feature in Hebrew you can read my Newsgeek article.

Site Pinning

IE9 Beta was released last week with a lot of browser improvements and features. One of the new features it includes is site pinning. In this feature we can drag a tab from the browser and pin it to the windows taskbar. 
I’ve build a simple site to demonstrate how to do that:
Example Application 

This is the template that you get when you create a new web application in VS2010.

Lets pin the site. First drag it:
Dragging the site  
Then pin it to the taskbar:
Pinning
Then it is pinned: 
Pinned Site 
Now you can run the site from the taskbar:

Pinned Site Running

Pay attention that the favicon of the pinned site is located left to the back button of the browser. Also the buttons are colored in brown to resemble the icon itself. This is part of the feature and you can change the colors if you like.

How to Enable Site Pinning?

This is the easy part.
You don’t have to anything.
If you have Windows 7 then install IE9 and you can start pinning. It is very recommended to add some meta tags like application-name to the site in order to add some information about your site. Here is an example of how to add the tags to a master page head element:

<head>
    <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="./" />
</head>

Summary

The ability to pin sites to the taskbar is a very nice feature of IE9. It shows that there is a shift in Microsoft direction in regard to the web and web operations systems. Think about it, when you pin sites you are pinning web applications/sites as you do with desktop applications. In a following post I’ll explain how to create jump lists for the pinned site.

Posted: Sep 19 2010, 09:45 AM by Gil Fink | with 3 comment(s) |
תגים:, ,

Quick Tip – Disable/Enable Button by Textbox Client Event using jQuery

Quick Tip – Disable/Enable Button by Textbox Client Event using jQuery

I find myself often with a need to disable/enable a button according to client events that occur on web pages. jQuery LogoToday I helped to implement this behavior again so I thought it will be nice to share the code I used. In this example I’m disabling/enabling a button according to whether a textbox holds some text. I’m using jQuery to make the code simple. Pay attention that this solution can be implemented for other events also.

The Code

$(document).ready(function () {
    $('#txtAgentName').blur(function () {
        if ($.trim(this.value) == "") {
            $('#btnUpdate').attr("disabled", true);
        }
        else {
            $('#btnUpdate').removeAttr("disabled");
        }
    });
});  

As you can see I wire up the ready event of the page and hook a blur event to the textbox with the txtAgentName id. In the blur event I check the value of the textbox and if it is empty I disable the button and if it is not I enable the button. The page that this example is taken from is an MVC 2 view which holds the textbox and the button elements like the following elements:

<input id="btnUpdate" type="submit" value="Update" disabled />
<%= Html.TextBox("txtAgentName") %>

Summary

A lot was written about how jQuery simplify the Javascript code that you write. In this tip I used jQuery to set Html elements appearance when some client event occurs.  

IE9 Beta is Out

IE9 Beta is Out

Internet Explorer 9 beta was released a few minutes ago. IE9
If you want to try it out you can go to this link and download it. 
IE9 is going to include a lot of changes in compare to the previous versions of IE. The main issues and changes that it includes are in performance (new Javascript engine called Chakra for example), in standards compatibility (CSS3, HTML5 ECMAScrpit 5 and more) and of course a new clean UI. 
Here is a screen shot of the new IE9 beta which include very minimal and clean UI and this blogging system:

 

 

First look at IE9 

This new release brings us closer to the RTM release of IE9 which will increase the browser wars that will probably end with no winners but with better browsers.

Posted: Sep 15 2010, 07:40 PM by Gil Fink | with no comments |
תגים:, ,

How to Enable Client Side Validation in ASP.NET MVC 2

How to Enable Client Side Validation in ASP.NET MVC 2

Last night I was teaching MVC framework as part of an ASP.NET course. How to Enable Client Side Validation in ASP.NET MVC 2One of the things that I showed the students was how to use data annotations for server side validation. I got a question about how to enable client side validation in MVC 2 and decided to write about it in a post. So here it goes…

MVC Server Side Validation

In MVC 1 we didn’t have client side validation out of the box. In order to achieve validation we needed to use one of two ways:

  • Implement the IDataErrorInfo interface. In this way every model entity which needs validation have to implement that interface.
  • Decorate every model entity with data annotations for validations. This is my preferred way since it is more elegant and you don’t need to hold the validation implementation inside your model entities.

These ways are server side validation. For client side validation we needed to use client side libraries such as jQuery Validator plug-in and write the client validation code. In MVC 2 this was made easier to implement.

Enabling Client Side Validation in MVC 2

Lets take a look at an entity which is decorated with data annotations:

public class Course
{
  #region Properties
 
  public int CourseID { get; set; }
  [Required(ErrorMessage = "Course title is required")]
  public string Title { get; set; }
  [StringLength(5, ErrorMessage = "Course can have up to 5 days")]
  public string Days { get; set; }    
  public DateTime Time { get; set; }
  public string Location { get; set; }    
  [Range(1,4)]
  public int Credits { get; set; }
 
  #endregion
}

As you can see the course require a title, its credit needs to be between 1 to 4 and the Days property has length of maximum 5 characters. In the courses controller I want to make validation so I hook up the server side validation like I was doing in MVC 1 in the controller:

[HttpPost]
public ActionResult Create(Course course)
{
  try
  {
    if (ModelState.IsValid)
    {
      _courses.Add(course);
      return RedirectToAction("Index");
    }
    return View();
  }
  catch
  {
    return View();
  }
}

The ModelState.IsValid property will trigger the validation on the entity and we will get server side validation. If we want to get client side validation we will have to activate it on the view. In MVC 2 we have another extension method on the HtmlHelper class that will help us to do so. The method is called EnableClientValidation. The create view will look like:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Course>" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Create
</asp:Content>
 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 
    <h2>Create</h2>
    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>
 
        <fieldset>
            <legend>Fields</legend>
            
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CourseID) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CourseID) %>
                <%: Html.ValidationMessageFor(model => model.CourseID) %>
            </div>
            
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Title) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Title) %>
                <%: Html.ValidationMessageFor(model => model.Title) %>
            </div>
            
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Days) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Days) %>
                <%: Html.ValidationMessageFor(model => model.Days) %>
            </div>
            
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Time) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Time) %>
                <%: Html.ValidationMessageFor(model => model.Time) %>
            </div>
            
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Location) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Location) %>
                <%: Html.ValidationMessageFor(model => model.Location) %>
            </div>
            
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Credits) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Credits) %>
                <%: Html.ValidationMessageFor(model => model.Credits) %>
            </div>
            
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
 
    <% } %>
 
    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>
 
</asp:Content>
 

If you will run the application now you will see that even though you explicitly enabled client side validation in the view it won’t run. The reason for that is that you need to link the validation Javascript files to enable validation. Here are the Javascript files you need to link (which exists by default in every not empty MVC 2 application):

  • jquery-1.4.1.js
  • jquery.validate.js
  • MicrosoftAjax.js
  • MicrosoftMvcAjax.js
  • MicrosoftMvcValidation.js

The place to link them is of course the master page so here is the master page implementation:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
 
<!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">
<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>   
    <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>      
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
</head>
 
<body>
    <div class="page">
 
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
              
            <div id="logindisplay">
                <% Html.RenderPartial("LogOnUserControl"); %>
            </div> 
            
            <div id="menucontainer">
            
                <ul id="menu">              
                    <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%: Html.ActionLink("About", "About", "Home")%></li>
                </ul>
            
            </div>
        </div>
 
        <div id="main">
            <asp:ContentPlaceHolder ID="MainContent" runat="server" />
 
            <div id="footer">
            </div>
        </div>
    </div>
</body>
</html>

That is it. Now you have client side validation hooked in your MVC 2 web application.
Validations in Action

Summary

In MVC 2 we have client side validation implemented inside the framework. All we have to do is to link some Javascript files and to add to the relevant view the call for EnableClientValidation of the HtmlHelper class.

MSDN Ultimate Subscriber Giveaways

MSDN Ultimate Subscriber Giveaways

A few days ago I got three MSDN subscribers for MSDN Ultimate to give away as I see fit.
MSDN Subscribers

The subscriptions allow their owner to download and own full featured versions of Visual Studio 2010 Ultimate, as well as most of Microsoft software. The retail value of such subscriber is approximately $12,000. Also, the subscriptions are valid for one year of use. 
So I thought to myself how do I intend to give away such a valuable gift? do I intend to give it in a session I deliver in a user group? or maybe I’m going to give it to one of my friends?
I discarded these ideas since I wanted to give away these subscribers to people who will deserve them.
I decided to give out two subscriptions to people in the Israeli development community that will be committed to volunteering at least 100 hours to develop open source projects during the following year. This way I’m giving the subscriptions to people who are willing to give back to the development community.   
Terms of participating:

  • You need to be an Israeli (because if you will be selected I’ll be able to give you the subscriber personally).
  • You are committed to volunteer to at least 100 hours to help developing an open source project during the following year.
  • Filling up the applying form.

The applying form will be open until the 26 of September. After this date I’ll choose two people that will be given the subscribers.
Open source projects that need help can also appoint me through my Blog contact form.

Stay tuned for more details and details about the third subscription.

Back to Basic – ASP.NET Runtime Impersonation

Back to Basic – ASP.NET Runtime Impersonation

Today I got a question from one of the developers at my main customer. .Net Framework New LogoThe question was how to move an uploaded file from an ASP.NET server to a file server on the network. The answer is of course by impersonating. In this post I’ll explain how you can make ASP.NET impersonation and in more details how to make runtime impersonation.

Impersonation in ASP.NET

When we are doing I/O operations, the operation system makes security checks to understand if the user is authorized to do the operation. The same thing happens when you try to do operations on another machine in your network. Impersonation in ASP.NET occurs when ASP.NET executes code in the context of an authenticated and authorized user. By default, ASP.NET run in the ASPNET account. By using impersonation we can impersonate the ASPNET account to another account that has access to resources which aren’t granted in the internet security permission. One way to impersonate a user is by using the identity element in the web.config. When you use the following code in your web.config, ASP.NET impersonates to the authenticated user or to an anonymous internet user account:

<identity impersonate="true" />

If you want to impersonate to a specific user you can use the following configuration:

<identity impersonate="true" userName="domain\username" password="password" />

Runtime Impersonation

At my customer the previous configuration examples weren’t an option. The second way to impose impersonation is by runtime. This option can be achieved by using the System.Security.Principal and the WindowsIdentity class. The WindowsIdentity class has a method that makes impersonation and returns a WindowsImpersonationContext. The problem with this class is that you need to supply to it an IntPtr which is a security access token of the user that you wish to impersonate to. The solution is to use P/Invoke and call the LogonUser Win32 API. After you get the impersonation context you can run the network operations that you seek to perform. After you finish to do your operations you need to undo the impersonation. The following code shows an example of an impersonation service class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.InteropServices;
using System.Security.Principal;
 
namespace WebApplication1
{
    public class ImpersonationService
    {
        #region Consts
 
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
 
        #endregion
 
        #region External API
 
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern int LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            out IntPtr phToken
            );
 
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool RevertToSelf();
 
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern int CloseHandle(IntPtr hObject);
 
        #endregion
 
        #region Methods
 
        public void PerformImpersonatedTask(string username, string domain, string password, 
            int logonType, int logonProvider, Action methodToPerform)
        {
            IntPtr token = IntPtr.Zero;
            if (RevertToSelf())
            {
                if (LogonUser(username, domain, password, logonType,
                    logonProvider, out token) != 0)
                {
                    var identity = new WindowsIdentity(token);
                    var impersonationContext = identity.Impersonate();
                    if (impersonationContext != null)
                    {
                        methodToPerform.Invoke();
                        impersonationContext.Undo();
                    }
                }
                else
                {
                    // do logging
                }
            }
            if (token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
        }
 
        #endregion
    }
}

Here is an example of how to use the class in your ASP.NET application:

using System;
using System.IO;
 
namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {       
        #region Page Events
 
        private void Page_Load(object sender, System.EventArgs e)
        {
            var service = new ImpersonationService();
            service.PerformImpersonatedTask("username", "domain", "password",
                ImpersonationService.LOGON32_LOGON_INTERACTIVE, ImpersonationService.LOGON32_PROVIDER_DEFAULT, new Action(MethodToPerform));
        }
 
        #endregion
 
        #region Methods
 
        public void MethodToPerform()
        {
            var serverPath = @"\\ServerName\test";
            var dirInfo = new DirectoryInfo(serverPath);
            Response.Write(dirInfo.Exists);
        }
 
        #endregion
    }
}

Summary

In the post I showed a simple way to implement a class that impersonate to a relevant account in order to achieve some functionality that internet security permissions don’t allow.  You should consider to use the web.config instead since it does all the communication with Win32 API instead of the supplied code. The impersonation isn’t limited only to ASP.NET and can be used also in other frameworks.

Recommended Post - Black Jack Using Scrum

Recommended Post - Black Jack Using Scrum

Yesterday, Shai Raiten, a colleague and a friend of mine, published a very original and funny post that describes a custom strategy of wining in “Black Jack” game based on Scrum Methodology. If you didn't read the post I'm recommending you to do so. Here is the link for the post - "Black Jack Using Scrum – Winner Winner Chicken Dinner".

Enjoy!

Bookmark and Share

Back to Basics – Get Client Computer Name in ASP.NET

Back to Basics – Get Client Computer Name in ASP.NET

Today I had a design review meeting about a new small application.Net Logo with ASP.NET
that I’m participating in its development as an architect. One of the crucial features in this application was depending on the ability to identify the client’s computer name (don’t ask me why…). Since this was a crucial thing for my customer I’ve decided to write about it. Pay attention that the solution I offer is for intranet application since it is counting on a DNS server.

Get Client Computer Name

In order to retrieve the client’s computer name you will have to query the DNS server with the client’s IP. The IP can be easily retrieved by using the ASP.NET Request object with its UserHostAddress property.
Here is a method that returns the computer name by a given IP:

public string GetComputerName(string clientIP)
{                        
    try
    {                
        var hostEntry = Dns.GetHostEntry(clientIP);
        return hostEntry.HostName;
    }
    catch (Exception ex)
    {
        return string.Empty;
    }            
}

In order to use this method you’ll have the reference the System.Net namespace which include the Dns class. To consume the method you can write the following code in your ASP.NET application:

GetComputerName(Request.UserHostAddress);

Summary

There are rare times that you need to know what is the name of the computer of your client. I showed how to achieve that using the System.Net.Dns class. Probably there are more solutions to this problem but this one is very easy to implement.

Posted: Sep 01 2010, 03:57 PM by Gil Fink | with no comments |
תגים:,