Thursday, November 11, 2010

PushPin to show or hide DIV and maintain state across pages and Users using JQuery

JQuery has very cool features, providing the wide range of plugins to play around with your webpage. Here in this post I m going to discuss regarding a requirement I had to make use of JQuery to maintain the state of a DIV across pages, as well as across Users logged into the application.

Requirement:

This requirement is to provide interface for searching certain content in the SharePoint List based upon the keywords. This search window/pane should have the capability of toggle, as well as the capability of fixing/pin down (stopping toggle i.e showing the DIV) which should be maintained across the pages in the application untill the user either closes the pane or unfix. Also, this provision should be available as per the User choice, logged in to the application.

Example:
For better understanding we shall consider two user's named User1 & User2. When User1 loggs in to the application and prefers to pin down the DIV after showing DIV by toggle, that DIV should be in open state, in all the pages being traversed, untill preferred to pin up. But this preference should not reflect to User2, as this user might not prefer to search or looking into the DIV.

Challenges:
  1. Maintaining the Open/Close state across all pages based upon the preference to show/hide respectively.
  2. Maintain the Open/Close state based upon the logged in User preference to show/hide respectively.

Solution:
  1. Add Script References for
    JQuery Plugin:
    
    
    Download: http://jquery.com/

    Sessions Plugin:
    Download: http://plugins.jquery.com/node/8213/release

    JSON Plugin:
    
    
    Download: http://www.json.org/json2.js
  2. Create a DIV tag holding all your content as below:
    Note:Styles & images are from JQuery UI Smoothness theme.
  3. Add the below script in the head tag
    $(document).ready(function() {
    
     $.namesession.set("LoggedInUser",$().SPServices.SPGetCurrentUser({fieldName: "UserName", debug: false}));
    
     var SearchWindowStatus= ($.namesession.get('SearchWindowStatus_'+$.namesession.get('LoggedInUser',''), '')!= '')?$.namesession.get('SearchWindowStatus_'+$.namesession.get('LoggedInUser',''), '') :$.namesession.set('SearchWindowStatus_'+$.namesession.get('LoggedInUser',''),false);
    
     if(SearchWindowStatus){
      $('#SearchFund-dialog').show();
      $("a[id$=anchorPinPoint]").children().removeClass('ui-icon-pin-w').addClass('ui-icon-pin-s').attr('title','Keep Search Closed');  
    
     }else{
      $('#SearchFund-dialog').hide();
     }
    
    
    
     $(this).click(function() {
    
       $('#SearchFund-dialog').toggle(); 
     }):
    
    
     $("a[id$=anchorPinPoint]").bind({
    
           mouseover:function() {
          $(this).addClass('ui-state-hover');
         },
         mouseout:function() {
          $(this).removeClass('ui-state-hover');
         },
        
        focus:function() {
         $(this).addClass('ui-state-focus');
         },
        blur:function() {
         $(this).removeClass('ui-state-focus');
         },
        click:function() { 
        
          TogglePinPoint(this)
    
         
         return false;
    
         }
      });
        
     function TogglePinPoint(ctrl)
     {
      if($(ctrl).children().hasClass('ui-icon-pin-w'))
       {
        $(ctrl).children().removeClass('ui-icon-pin-w').addClass('ui-icon-pin-s').attr('title','Keep Search Closed');  
        $.namesession.set('SearchWindowStatus_'+$.namesession.get('LoggedInUser',''),true);
       }else if($(ctrl).children().hasClass('ui-icon-pin-s'))
       {
        $(ctrl).children().removeClass('ui-icon-pin-s').addClass('ui-icon-pin-w').attr('title','Keep Search Open');  
        $.namesession.set('SearchWindowStatus_'+$.namesession.get('LoggedInUser',''),false);
    
      } 
     }
    });
    

Note: Ensure your web.config file is configured for AJAX & JSON
Enable SessionState is set to true in the config file

Wednesday, November 10, 2010

Folders in SharePoint Pages Library for Publishing Site

SharePoint Publishing site template has Pages Document Library, which is a repository for pages with a flexibility of creating pages based upon Page Layouts. Pages created in this library by default are configured with three content types Pages, Article Page & Welcome Page each having their own fields based upon necessity.

Pages Library is flexible in creating pages with different layouts, based upon the design & requirement, but does not have a provision to create pages in folders & access them as per the sitemap/ breadcrumbs, as we create in a basic document library. We can go to advanced settings of the library & configure for showing "New Folder" under the New Menu, even though when we create a page under the folders, it is saved under root folder of the library which does not meet our purpose.

         So here in this post, I would like to share one of the solution I implemented in our project, which sufficed very well using  Pages Library for creating pages in the folders.

Troubleshooting:
           The process of troubleshooting started from creating a  new page. In the publishing site when we try to create a new page either from menu option under "Site Actions" or from the "New Menu" in library, we are redirected to "CreatePage.aspx" available under layouts virtual directory. So this is the page where we can customize as per our requirement.

Steps to recreate:

Building Custom page for creating a page:
    1. Copy the "CreatePage.aspx" available in the layouts folder of SharePoint 12 hive & place it in the same directory or else in your custom directory and rename with a custom name as "CreatePage_Custom.aspx".
    2. Open the CreatePage_Custom.aspx in designer or visual studio and search for the tag  
      Set the property "Visible=false" as this is the control which holds name of the Pages library.
      Note: Do not delete this tag, there is a reference in the code behind.
    3. Add the below directive to have publishing assembly reference
      <%@ Import Namespace="Microsoft.SharePoint.Publishing" %>
    4. Microsoft.SharePoint.Publishing.Internal.CodeBehind.CreatePage is the class in the code behind, but the respective methods are not exposed. So the next option is inline coding in the page, where we use custom event of the submit button to have our functilnality to add the page in the Pages library.
      protected void OnCustomSubmit(Object sender, EventArgs e)
      
      {
        string newPageUrl = "";
      
       SPWeb web = SPContext.Current.Web;
      
       PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
      
       PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts();
      
       int layoutItemId = Convert.ToInt32(pageTemplatePicker.SelectedValue);
      
       PageLayout layout = FindLayoutById(layoutItemId,publishingWeb);
      
       string pageName = urlNameTextBox.Text + ".aspx";
      
       PublishingPage newPage = publishingWeb.GetPublishingPages().Add(Request.QueryString["RootFolder"].ToString() + "/" + pageName, layout);
      
       newPageUrl = web.Url + "/" + newPage.Url; // Here you can append the Querystring if you want to show the created page in the Edit Mode.
      
       newPage.Title = titleTextBox.Text;
      
       newPage.Description = descriptionTextBox.Text;
      
       newPage.Update();
      
       Response.Redirect(newPageUrl);
      }
      
      protected PageLayout FindLayoutById(int layoutItemId,PublishingWeb localPublishingweb)
      {
       SPListItem itemById = localPublishingweb.Web.Site.RootWeb.GetCatalog(SPListTemplateType.MasterPageCatalog).Items.GetItemById(layoutItemId);
      
       if (itemById == null)
      
       {
      
        return null;
      
       }
      
       return new PageLayout(itemById);
      }

    5. Refer the server click event to the custom event cretaed above.
       
    6. Creating a custom content type:
      
      
       
        
         
         
         
         
         
         
         
        
        
       
      
    7. Deploy content type to the web application Add this new custom content type to the Pages library from the library settings.
    8. Allow library to display New Folder option in New Menu, for creating sub folders.
    9. Create a page using the new content type available under New Menu.

Reference:
If there is a requirement to create a page from the menu item under Site Actions, please refer to this post.
http://blogs.msdn.com/b/syedi/archive/2008/07/18/why-should-one-save-publishing-pages-in-pages-list-always-in-moss-bend-it.aspx

Saturday, July 3, 2010

SharePoint 2010 Virtual Machine for Evaluation

Virtual Machine running Microsoft SharePoint Server 2010, OCS, Web Applications, FAST Search, Project Server, Project Pro Plus 2010, Visio, Project, SQL Server 2008 R2 and Exchange Server 2010 were published by Microsoft. This download contains a two Windows Server 2008 R2 Hyper-V Virtual Machine set for evaluating and demonstrating Office 2010, SharePoint 2010 and Project Server 2010 – including ECM and PerformancePoint Services

Active directory has been preconfigured with over 200 “demo” users with metadata in an organizational structure. All of these user profiles have been imported and indexed for search within SharePoint Server 2010.

SharePoint Server 2010 has been configured in a “Complete” farm using the default SQL Server 2008 R2 instance. A default site has been created using the Team Site template at http://intranet.contoso.com/ and a FAST Search Center at http://intranet.contoso.com/search/

Get it from: http://go.microsoft.com/?linkid=9728417

Virtual machine “a” contains the following pre-configured software:
  1. Windows Server 2008 R2 Standard Evaluation Edition x64, running as an Active Directory Domain Controller for the “CONTOSO.COM” domain with DNS and WINS
  2. Microsoft SQL Server 2008 R2 Enterprise Edition with Analysis, Notification, and Reporting Services
  3. Microsoft Office Communication Server 2007 R2
  4. Microsoft Visual Studio 2010
  5. Microsoft SharePoint Server 2010 Enterprise Edition
  6. Microsoft Office Web Applications
  7. Microsoft FAST Search for SharePoint 2010
  8. Microsoft Project Server 2010
  9. Microsoft Office Professional Plus 2010
  10. Microsoft Visio 2010
  11. Microsoft Project 2010
  12. Microsoft Office Communicator 2007 R2
Virtual machine “b” contains the following pre-configured software:
  1. Windows Server 2008 R2 Standard Evaluation Edition x64, joined to the “CONTOSO.COM” domain
  2. Microsoft Exchange Server 2010

SharePoint 2010 Virtual Labs

We know SharePoint 2010 is a very advanced product in terms of features, capabilities and infrastructure etc. In this scenarios setting up an environment for ourselves is a difficult process atleaset to evaluate the product.

Eventhough now we can install SharePoint 2010 in Windows 7 & Server 2008 they need to be X-64 bit. Upgrading our machines accordingly might involve some investment. So now we have a Virtual labs provided by Microsoft to evaluate the features listed below.


It's our turn to to explore and update to new technologies provided by SharePoint 2010.
 
Test drive SharePoint 2010 in a Virtual lab. Take part and see how Microsoft Office SharePoint Server supports all intranet, extranet, and Web applications across an enterprise within one integrated platform.

Virtual labs cover the following:
  • MSDN Virtual Lab: Client Object Model
  • MSDN Virtual Lab: Customizing MySites
  • MSDN Virtual Lab: Designing Lists and Schemas 
  • MSDN Virtual Lab: Developing a BCS External Content Type with Visual Studio 2010 
  • MSDN Virtual Lab: Developing a Sandboxed Solution with Web Parts 
  • MSDN Virtual Lab: Developing a Visual Web Part in Visual Studio 2010 
  • MSDN Virtual Lab: Developing Business Intelligence Applications 
  • MSDN Virtual Lab: Enterprise Content Management 
  • MSDN Virtual Lab: Getting Started with SharePoint 2010 
  • MSDN Virtual Lab: LINQ to SharePoint 2010 
  • MSDN Virtual Lab: SharePoint 2010 User Interface Advancements 
  • MSDN Virtual Lab: Visual Studio SharePoint Tools 
  • MSDN Virtual Lab: WorkflowMSDN Virtual Lab: Workflow

Wednesday, April 7, 2010

Handling ClientID issues in SharePoint Webparts & jQuery

In ASP.NET/SharePoint a Control has a fully qualified ID that can be deduced from the control hierarchy and can be accessed with the properties ClientID or UniqueID. It then becomes the unique id or name of rendered html controls. It makes sense that these properties should be used right after the control hierarchy is completely defined, that means before the rendering, therefore in the PreRender.

What is not so well known is that accessing those two properties sets the _cachedUniqueID member, which sets irrevocably the ID to a control. That's why using these properties in ItemCreated events, for example, makes the html id of controls to remain the default defined one.

Example: In a DataList, you have an item template that contains a control, let's call it Control1. The rendered id in html will look like this: ctl00_m_g_aaf13d41_fc78_40be_81d5_2f40e534844f_txtName, but if you use ClientID inside the DataList_ItemCreated event, the rendered html id will be just Control1, thus making any javascript manipulation futile.

Of course, one could create a method to return the UniqueID without setting the cached value, since there are moments when the partial hierarchy is enough to define a proper id. Unfortunately, for controls without a specific and declared id, ASP.NET creates and automatic ID like ctl[number] or _ctl[number] and, of course, those methods and fields are all private or internal. One could use Reflection to get to them, but what would be the point?

UniqueID and ClientID are overridable, though, so one can change their behaviour in user defined controls.

Solution for handling in jQuery, Javascript & SharePoint Webparts (C#).

jQuery is fantastic! It makes client-side development faster and countless plug-ins are available for just about every need. Using jQuery with Asp.NET Web-Forms gets aggravating when dealing with nested server controls. ClientID’s get appended when using ASP.NET Master Pages. Objects in JavaScript tend to look like this:
ctl00_m_g_aaf13d41_fc78_40be_81d5_2f40e534844f_txtName
The difficulty of the issue above is that, in order to get the element txtName, It’s necessary to know the full “path”. It’s quite aggravating to refer to get the object using the method below:
document.getElementByID('ctl00_m_g_aaf13d41_fc78_40be_81d5_2f40e534844f_txtName');
This becomes a big problem when developing server controls or web parts that may be used in a typical ASP.NET application or SharePoint. You cannot hard-code the path above if you don’t know the full path of the control.

Fortunately, there are a few ways to get around this. There are three, in particular, I will mention. The first is the jQuery equivalent to the standard JavaScript method:
document.getElementById("<%=txtName.ClinetID%>");");
This can be done in jQuery by using:
$("#'<%=txtName.ClinetID%>");");
The second jQuery method does not require server tags. This method searches through all tags and looks for an element ending with the specified text. The jQuery code for this method is shown below:
$("[id$='_txtName']");
There are, of course, drawbacks to both methods above. The first is fast, but requires server tags. It’s fast, but it just looks messy. Also, it will not work with external script files. The second alternative is clean, but it can be slow. As I said earlier, there are several other alternatives, but these two are the ones I find myself using the most.

The third registering Javascript in C# code behind.
Page.ClientScript.RegisterStartupScript(GetType(), "saveScript",

String.Format("function EnableSave( isDisabled )"+

"{{ var saveButton = document.getElementById(\"{0}\");"+

"saveButton.disabled=isDisabled;}}", btnSave.ClientID), true);

Do not forget to call this script after controls have been loaded, I mean after Controls.Add(); in CreateChildControls method while developing webparts.

Monday, October 26, 2009

New features in C# 4.0 - Variance


An aspect of generics that often comes across as surprising is that the following is illegal:


IList strings = new List();
IList<object> objects = strings;

The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this. If it were allowed you could write:
objects[0] = 5;
string s = strings[0];

Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety.
 However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say:
IEnumerable<object>

There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element in. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work.

Covariance

In .NET 4.0 the IEnumerable<T>
interface will be declared in the following way:

public interface IEnumerable : IEnumerable
{
        IEnumerator GetEnumerator();
}
public interface IEnumerator : IEnumerator
{
        bool MoveNext();
        T Current { get; }
}

The “out” in these declarations signifies that the T can only occur in output position in the interface – the compiler will complain otherwise. In return for this restriction, the interface becomes “covariant” in T, which means that an IEnumerable<A> is considered an IEnumerable<B>

if A has a reference conversion to B.

As a result, any sequence of strings is also e.g. a sequence of objects.

This is useful e.g. in many LINQ methods. Using the declarations above:
 
var result = strings.Union(objects); // succeeds with an IEnumerable 

This would previously have been disallowed, and you would have had to to some cumbersome wrapping to get the two sequences to have the same element type.

Contravariance

Type parameters can also have an “in” modifier, restricting them to occur only in input positions. An example is IComparer:
 
public interface IComparer
{
        public int Compare(T left, T right);
}

The somewhat baffling result is that an IComparer can in fact be considered an IComparer! It makes sense when you think about it: If a comparer can compare any two objects, it can certainly also compare two strings. This property is referred to as contravariance.  A generic type can have both in and out modifiers on its type parameters, as is the case with the Func<…> delegate types: public delegate TResult Func(TArg arg);   Obviously the argument only ever comes in, and the result only ever comes out. Therefore a Func can in fact be used as a Func. Limitations Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable is not an IEnumerable because the conversion from int to object is a boxing conversion, not a reference conversion.   Also please note that the CTP does not contain the new versions of the .NET types mentioned above. In order to experiment with variance you have to declare your own variant interfaces and delegate types. COM Example Here is a larger Office automation example that shows many of the new C# features in action.
using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class Program
{
    static void Main(string[] args) {
        var excel = new Excel.Application();
        excel.Visible = true;
        excel.Workbooks.Add();                    // optional arguments omitted
        excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically  
        excel.Cells[1, 2].Value = "Memory Usage"; // accessed
        var processes = Process.GetProcesses()
            .OrderByDescending(p => p.WorkingSet)
            .Take(10);
        int i = 2;
        foreach (var p in processes) {
            excel.Cells[i, 1].Value = p.ProcessName; // no casts
            excel.Cells[i, 2].Value = p.WorkingSet;  // no casts
            i++;
        }
        Excel.Range range = excel.Cells[1, 1];       // no casts
        Excel.Chart chart = excel.ActiveWorkbook.Charts.
            Add(After: excel.ActiveSheet);         // named and optional arguments
        chart.ChartWizard(
            Source: range.CurrentRegion,
            Title: "Memory Usage in " + Environment.MachineName); //named+optional
        chart.ChartStyle = 45;
        chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
            Excel.XlCopyPictureFormat.xlBitmap,
            Excel.XlPictureAppearance.xlScreen);
        var word = new Word.Application();
        word.Visible = true;
        word.Documents.Add();          // optional arguments
        word.Selection.Paste();
    }
}
The code is much more terse and readable than the C# 3.0 counterpart. Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges.

New features in C# 4.0 - Features for COM interop

Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0.

Dynamic import

Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.

In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.

This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say

excel.Cells[1, 1].Value = "Hello";
instead of
((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";
and
Excel.Range range = excel.Cells[1, 1];
instead of
Excel.Range range = (Excel.Range)excel.Cells[1, 1];

Compiling without PIAs

Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.

The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.

Omitting ref

Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.

It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.

Open issues

A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.

There are currently no plans to address these remaining speed bumps in C# 4.0.