Fixing SSRS Report Viewer control date picker in Google chrome

SSRS Report Viewer control works well in IE6+ but has some known compatibility issues with other major browsers(Firefox, Chrome etc.) around date picker and print button.

For more information read this

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

I am presenting a simple solution to fix date picker issue in Chrome with  a combination of some server side code and Client side JQuery script.

 

Server Side Code

 

1) Add the below code in the page/control file in which the reportviewer control resides

 <asp:HiddenField ID="DatePickers" runat="server" />

 

2) Add the below code in the code behind file of page/control in which the reportviewer control resides(.Net 2.0 version)


protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);
  DatePickers.Value = string.Join(",",(new List(GetDateParameters()).ToArray()));
}
private IEnumerable GetDateParameters()
{
  // I'm assuming report view control id as reportViewer
  foreach (ReportParameterInfo info in reportViewer.ServerReport.GetParameters())
  {
    if (info.DataType == ParameterDataType.DateTime)
    {
        yield return string.Format("[{0}]",info.Prompt);
    }
  }
}

 

Client Side Code

 

1) Add the below script in the html head section


$(document).ready(function(){

 if ($.browser.webkit)
 {
    $($(":hidden[id*='DatePickers']").val().split(",")).each(function(i, item){
         var h = $("table[id*='ParametersGrid'] span").filter(function(i) {
             var v = "[" + $(this).text() + "]";
             return (v != null && v.indexOf(item) >= 0);
          }).parent("td").next("td").find("input").datepicker({
           showOn: "button"
           ,buttonImage: '/Reserved.ReportViewerWebControl.axd?OpType=Resource&Name=Microsoft.Reporting.WebForms.calendar.gif'
           ,buttonImageOnly: true
           ,dateFormat: 'dd/mm/yy'
           ,changeMonth: true
           ,changeYear: true
           });
     });
  }

});

 

Hope this helps!!! Smile

MVC3 Unobtrusive validation for checkbox

When using unobtrusive validation for checkboxes, it does not validate an unchecked checkbox which is marked as required. Its a known issue. By default, all the checkbox required conditions are ignored in unobtrusive validation.

A workaround for this issue is to add a custom attribute and some code change in the unobtrusive JavaScript library.

1. Create a custom attribute

   

    public class RequireCheckedAtrribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value;
        }
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationType = "requirechecked";
            yield return rule;
        }
    }
  
 

2. replace the condition at line 294 in jquery.validate.unobtrusive.js (not minified) with the below lines


var s = $(options.element).attr('data-val-requirechecked');
if (s != null && s != 'undefined')
    options.message = s;
if (options.element.tagName.toUpperCase() !== "INPUT" || !($(options.element).is(':checkbox') &&
(s == null || s == 'undefined'))) {

 

The new code from line 292 looks as below


adapters.add("required", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        var s = $(options.element).attr('data-val-requirechecked');
        if (s != null && s != 'undefined')
            options.message = s;
        if (options.element.tagName.toUpperCase() !== "INPUT" || !($(options.element).is(':checkbox') &&
(s == null || s == 'undefined'))) {

            setValidationValues(options, "required", true);
        }
    });
 

3. In the model, mark your checkbox field with RequireCheckedAtrribute attribute.

Example:

 
[RequireCheckedAtrribute]
public bool AcceptTerms {get; set;}

 

You can download updated script file from here

 

Happy codingSmile

Replacing Report Viewer date parameter default date picker with JQuery UI date picker

By default, Report Viewer control displays a default date picker for all the date parameters in parameter section. It creates a hidden iframe for each date picker and a calendar image(input type=’image’) is added next to each date input parameter which act as a trigger for the date picker.

 

ReportViewerDefaultDatepicker_thumb3

There may be a situation when you want to use a JQuery date picker instead of default one. The advantage of  JQuery date picker is in its theme roller and can be displayed with custom theme suited to your application. This can be done by using following script on document ready.


   $(document).ready(function(){
   $("table[id*='ParameterTable'] :input[type='image']").each(function(i)
   {
        var s = $(this).attr("src");
        if (s != null && s.indexOf("calendar") >= 0)
        {
            $(this).hide();
            $(this).prev("input").not(":disabled").datepicker({
                showOn: "button",
                buttonImage: s,
                buttonImageOnly: true,
                dateFormat: 'dd/mm/yy'
                , changeMonth: true
                , changeYear: true
            });//end of date picker
        }
    });//end of each

   });//end of ready

   

After fixing, the new JQuery UI date picker looks like as below

 

ReportViewerJQueryDatepicker_thumb3

Hope this helps Smile

Fixing Report Viewer control toolbar in Google Chrome

In Chrome browser, Report Viewer (8 & 9) toolbar elements are displayed in multiple rows as shown below.

 

Report ViewerTB1

 

The quick fix for this to change the toolbar table display to ‘inline-block’ when toolbar is displayed. This can be done by applying the following simple Jquery script on document ready. Add css class ‘ms-report-viewer-control’ to your reportviewer control.


$(document).ready(function() {
   if ($.browser.webkit)
   {
	$(".ms-report-viewer-control :nth-child(3) table").each(function(i, item) {
	$(item).css('display', 'inline-block'); });
   }
});

After this fix, the toolbar elements are displayed in a single row

 

Report Viewer TB2

 

Hope this helps Smile

Passed MCTS .Net Framework 4 Web Applications (70-515)

Smile  Yesterday, I passed MCTS .Net framework 4 (70-515), Web applications(VS2010) with a score of 850/1000. My exam is of 51 questions. The study materials I referred are MSDN documentation  Microsoft Self Paced Training Kit 70-515, JQuery Documentation. The training kit book explains each individual topic in a simple way although most of the contents you can find in MSDN documentation(not organised same as the book).

if you want to pass in the first attempt, focus on the following 

  • 15% nearly 5 questions on Jquery (focus on Jquery core selectors, attributes, Css, Form, Manipulation, Traversing, AJAX) and 2 on Ajax($.ajax)
  • Configuration/Deployment (Web.config structure , focus on all the System.Web elements, Project references, publishing websites using Web Deploy, Publish tools, Generic config replacement)
  • ASP.Net Ajax(UpdatePanels, Timer, UpdateProgress, Postback and asychronous triggers, UpdatePanel modes )
  • 20% Web Forms(Page Declaration attributes, Content) and Controls(User controls, Web Controls, Custom Controls, Templates, Server Controls and HTML Controls etc, Data Binding.), Validation Controls.
  • Application, Page and Control life cycles
  • Master Pages, Themes, Skins, Stylesheets, Scripts, Site Navigation, Menus
  • 2 questions on HttpModules, HttpHandlers( asynchronous too) and configuration in IIS6, IIS7 (Classic and Integrated modes)
  • Security, Authorization and Authentication( Windows and Forms Authentication, Roles, Memberships, Profiles etc)
  • 10% on MVC2 (Controllers, Areas, Constraints, Defaults, ActionResult and its types, Views and Strong typed Views, Models, MVC structure)
  • Globalization and Localization (Local and Global resources, culture formats, meta:resourceKey)
  • Configuring and Updating WCF and ASMX service references and proxies.
  • Caching(5%, focus on Cache.Insert with absolute and sliding expirations, dependencies, OutputCache), Session state, Application States, ViewState, Control State
  • Data related  SQLDataSource, ObjectDataSource, LinqDataSource, XMLDataSource,EntityDataSource and Parameters(Select, Where, Insert, Delete, Update, QueryString etc), Linq, Entity Framework.

Also the new topics in ASP.Net 4 like Dynamic Data (namely scaffolding ), new Web.Config changes etc..

This is my second attempt for MCTS Web applications, My last attempt was in December 2009 for MCTS .Net framework 3.5 certification(based on VS2008 which requires two exams 70-536 and 70-562). I passed 70-536 exam but failed 70-562 exam with a score of 650/1000 where as pass score is 700.

ASP.Net 4.0 BlogEngine.Net A potentially dangerous Request.Form value

This one related to page save error in BlogEngine.net running under .Net 4.0. When saving edited content in the Administration screen you may get this error.

Raw Url : /admin/Pages/Pages.aspx?id=6a2f6007-b224-48f3-94f9-0b4af750668f
Message : A potentially dangerous Request.Form value was detected from
the client (ctl00$cphAdmin$txtContent$TinyMCE1$txtContent=". 

ASP.Net validates page request data to protect against any possible XSS attacks. In ASP.Net 2.0, request validation is enabled for only ASP.Net pages and validated when those pages are executing. Whereas in ASP.Net 4.0, by default request validation is enabled for all requests. As a result validation applies to not only to ASP.Net pages but also to the Web service calls, Http handlers etc.. To prevent this error simply revert ASP.Net behaviour back to 2.0. To do this, add a configuration element in Admin Web.Config.

<httpRuntime requestValidationMode="2.0" /

SharePoint 2010: Site Definition Vs Web Template

Site Definition and Web Template are used for building a SharePoint site. If you are new to SharePoint, you may wonder which one to use?. Well, it depends on your site requirements and extensibility. Both are used to build a site UI interface to the end user.  The major difference is a Web template is always based on a existing Site Definition either directly or indirectly. I have outlined some comparisons in the below table

 

Site Definition

Web Template

core definition in SharePoint Based on existing Site Definition either directly or indirectly
Stored on a Front-end Web Server in folder

%ProgramFiles%Common FilesMicrosoft Sharedweb server extensions14TEMPLATESiteTemplates

Stored as a .wsp file in SharePoint Database.
Complex to create Easier to create
Deployed as Farm solutions with Admin rights Deployed in Solution Gallery(Sandbox)
Once def, cannot be modified can be modified without affecting existing sites
Configurations are defined in WebTemp*.xml and ONET.xml
WebTemp*.xml file contains one or more Template elements which represents a Site Definition
Details of each Template element in WebTemp*.xml are stored in a corresponding Configuration element in the ONET.xml file.
Configurations are defined in a xml and ONET.xml(part of .wsp file).

In the XML, The only difference is WebTemplate element instead of Template as defined in WebTemp*.xml.

The ONET.xml is simpler than that of Site Definition ONET.xml.

 

Note:

1) Sites created from a Site Definition or Sites created from a Web Template (that is based on the Site Definition) may not work properly if modified or removed. New sites based on Site Definition cannot be created. 

2) Out of Site Definition and Web Template, Web Template is easier to create ,maintain, modify and deploy. A Site definition is preferred, when you need custom components(defined in ONET.xml) and email footers,.

3) If you go for a Site Definition, the best practice is to have a minimal Site Definition to be acted as model and extend it with using Site Features whenever required.

SharePoint 2010: Creating a Site Definition Using Visual Studio 2010

A SharePoint site definition is the core definition of what a site in SharePoint. A site definition can include more than one site definition configurations i.e. family of configurations.  A configuration specifies the sets of lists, Features, Modules etc. that are included when a new site is created.

Each site definition is a combination of .aspx , .ascx, .master along with .xml file in Collaborative Application Markup Language(CAML) that are placed in %Program Files%Common FilesMicrosoft Sharedweb server extensions14TEMPLATESite Templates.

Every site definition structure and content is governed by a set of XML files in CAML format. Prominent among them are

WebTemp*.xml : Provide information about how they appear in the UI.

When SharePoint installed, a global WebTemp*.xml is installed in %Program Files%Common FilesMicrosoft Sharedweb server extensions14TEMPLATELCIDXML

where LCID is the numeric ID of language/culture. ex: 1033 for English.

For each site definition, there will be one WebTemp*.xml.

General format of WebTemp*.xml is as shown below


   <Templates>
      <Template Name=”<name>” ID=”ID1”>

        <Configuration ID=”<someid>” Title=”title">

        </Configuration>

         <Configuration ID=”<someid>” Title=”title">

        </Configuration>

      </Template>

      <Template Name=”<name>” ID=”ID1”>

       …

      </Template>

    … …

    </Templates>


Each <Template> element represents a site definition. Every Site Definition is provided with one or more <Configuration> elements. If you want to know more about <Configuration> element, follow this link

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

Onet.xml : All about Navigation areas, List Definitions, Modules, Document Templates, List Templates, Configurations, BaseTypes, Components.

When SharePoint installed, a global Onet.xml is installed in %Program Files%Common FilesMicrosoft Sharedweb server extensions14TEMPLATEGLOBALXML.

For each site definition, there is a corresponding Onet.xml installed in subdirectory(template name) at  %Program Files%Common FilesMicrosoft Sharedweb server extensions14TEMPLATESiteTemplates

Click on this link http://msdn.microsoft.com/en-us/library/ms474369.aspx to know more about format of Onet.xml file.

A Site definition deployed once cannot be modified. The best way is to create a new kind of site. This can be done by creating a new WebTemp*.xml and Onet.xml. 

Few points to remember

  • SharePoint 2010 must be installed on the dev machine. No longer Visual Studio 2010 supports remote debugging for SharePoint.
  • Instance of Visual Studio 2010 must run with elevated permissions i.e. Run as Administrator.

vs2010_sd_admin_error

  • Solution must be deployed as  Farm solutions rather than as Sandbox solutions.

Please follow this link http://msdn.microsoft.com/en-us/library/ee231562.aspx if you want to what is a Sandbox solution in SharePoint 2010.

Follow this link  http://msdn.microsoft.com/en-us/library/ee361616.aspx to know differences between Farm solutions and Sandbox solutions.

Creating a Site Template

To create a site template follow these steps

1) Open Visual Studio 2010 (as administrator), Click on File->New->Project. Select the Site Definition project template under SharePoint 2010 templates folder. Provide solution name and location, Click Ok button.

 vs2010_sd_new

2) Next you’ll see a SharePoint Customization Wizard asking for local site for debugging and deployment. Provide your SharePoint Url and select Deploy as a Farm Solution radio option and then Click Finish.

vs2010_sd_sp_server

3) A new solution will be created as shown in the below image. Note that two xml(WebTemp*.xml, ONet.xml) files are created. And also Features and Modules

vs2010_sd_solution

4) Click Build->Deploy, solution will be deployed on the SharePoint. All Done.

5) Open SharePoint Central Administration Web page, create a new site from your custom site definition.

sp2010_st_custom

6) Open newly created site, you’ll see a custom site web page derived from your site definition.

sp2010_st_custom_site_actions

Embedding a Simple SilverLight Map in a WebPage

SilverLight map can be embedded in a WebPage without any scripting or object tag in the form of a Map URL with optional parameters.

The map URL is in the following format

http://dev.virtualearth.net/embeddedMap/v1/silverlight/{mapMode}?zoomLevel={zoomLevel}
&center={center}&heading={heading}&pushpins={pushpins}&culture={culture}

To embed in a web page, use IFrame tag with src pointing to map URL.

The below table lists available parameters for the map URL. All the parameters can be in any order and are all optional.

Parameter Name Description
   
mapMode the style of the map. Valid values are: Road, Aerial, AerialWithLabels, Birdseye, BirdseyewithLabels
   
zoomLevel zoom level (int 1-19)
   
center map center point latitude and longitude separated by _.
   
heading map orientation 90, 180, 270
   
pushpins map points in latitude and longitude separated by _ if two or more points then separated with ~
   
culture map culture

I have configured a Demo with Jquery to dynamically update map URL with all the parameters.

Demo is located at http://www.rajbandi.dev/Demos/Silverlight/embedmap/

 
 

Visual Studio 2010 and .Net Framework 4 Training Kit

This training kit is designed to help you learn how to utilize visual studio 2010 and framework technologies. it includes presentations, hands-on labs and demos of the following framework technologies

  • C# 4
  • ASP.Net 4
  • Windows 7
  • Entity Framework
  • ADO.Net Data Services
  • Managed Extensibility Framework
  • Windows Communication Foundation
  • Windows Workflow
  • Windows Presentation Foundation

This kit works with Visual Studio 2010 and .Net Framework 4 only. It’ll walk you step by step through loads of content and is a great starter if you’re getting into what’s new in .NET 4.

You can download kit from here Visual Studio 2010 and .Net Framework 4 Training kit