Wednesday, June 29, 2011

Deploy Welcome Page in Team Sites - Method3

Method: 3
We will deploy the new Home Page to the 12th hive and not to the Layouts Folder because I want the look and feel of the URL as http://sites/test/CustomPages/Home.aspx but not like http://sites/test/_Layouts/Home.aspx
The way of doing this is through Feature Receiver when activated sets the new Home Page and deactivated sets to the older Home Page.
Solution Structure

Feature.xml:
The Element Manifest Section should be like this
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
    <ElementFile Location="CustomPages\Home.aspx"/>
  ElementManifests>
Elements.xml:
<Module Name="CustomPages" Path="CustomPages" >
     <File Path="Home.aspx" Url="CustomPages/Home.aspx" Type="Ghostable"/>
  Module>
Here Comes Our FeatureActivated code:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {            
            SPWeb web = properties.Feature.Parent as SPWeb;    
           // back up the original home page
           SPFile defaultPage = web.Files["default.aspx"];
           defaultPage.MoveTo("default-old.aspx");
           //updating the navigation
           SPFolder rootFolder =web.RootFolder;
           rootFolder.WelcomePage = "CustomPages/Home.aspx";
           rootFolder.Update();
        }
FeatureDeactivating code:
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        { 
            //CustomPages/Home.aspx
            SPWeb web = properties.Feature.Parent as SPWeb;
            SPFolder rootFolder = web.RootFolder;           
            // restore the back up
            SPFile originalDefaultPage = web.Files["default-old.aspx"];
            originalDefaultPage.MoveTo("default.aspx");
           //resetting up the navigation 
            rootFolder.WelcomePage = originalDefaultPage.ToString();
            rootFolder.Update();            
        }

Deploy Welcome Page in Team Sites-continuation

Code for the buttons are Part1

protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
if (txtWelcomePage != null) {
using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb site = siteCollection.OpenWeb())
{
txtWelcomePage.Text = site.RootFolder.WelcomePage;
}
}
}
}
}
protected void ButtonOkUpdatePageClick(object sender, EventArgs e) {
if (!string.IsNullOrEmpty(txtWelcomePage.Text)) {
using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb site = siteCollection.OpenWeb())
{
SPFolder rootFolder = site.RootFolder;
rootFolder.WelcomePage = txtWelcomePage.Text;
rootFolder.Update();
SPNavigationNode homeNode = site.Navigation.TopNavigationBar.Navigation.Home;

//This is to update the default navigation
homeNode.Url = SPUrlUtility.CombineUrl(site.Url, txtWelcomePage.Text);
homeNode.Update();

Response.Redirect(SPUrlUtility.CombineUrl(site.Url, "/_layouts/settings.aspx"));
}
}
}
}
protected void ButtonCancelUpdatePageClick(object sender, EventArgs e) {
// redirect to the site's settings page
Response.Redirect(SPUrlUtility.CombineUrl(SPContext.Current.Web.Url, "/_layouts/settings.aspx"));
}
And Coming to the Limitations as you might have seen there is no option to roll back the new Home Page to the default.aspx.So Here Comes the Method3 which gives us that control.

Deploy Welcome Page in Team Sites

In Publishing sites we have an option of setting up Welcome Page ,but this option is not present in Team Sites.
We can achieve this in different ways
  1. Using SharePoint Designer
  2. Deploy a Feature which gives you a Provision of setting up the welcome Page.
  3. Deploy a Feature which will set the new page as Welcome Page on Feature activated and resets the older default when deactivated.
I will discuss methods 2 and 3 here
Method 2:
This is how the Solution structure looks like
Below is the elements.xml where we define the Custom Actions option
<elements xmlns="http://schemas.microsoft.com/sharepoint/">
<customaction>
Id="UserGroupAdminLinkForSettings"
GroupId="Customization"
Location="Microsoft.SharePoint.SiteSettings"
RequireSiteAdministrator="TRUE"
Sequence="120"
Title="Welcome Page">
<urlaction url="_layouts/WelcomePage/WelcomePage.aspx"></urlaction>
</customaction>
</elements>

Feature.xml I have defined to be as Web
This is How the option looks like


When you click on the link this is how you see. Continuation 

Understanding the Application Page CopyUtil.aspx

I have recently came to know about an Application Page called CopyUtil.aspx.
Ever came across a scenario where you have to navigate either to Dispform or EditForm by passing in parameters like siteId,ListId and ItemId.
These are some of the parameters that this page expects which will help you in smooth navigation.
Mostly this is used with SPSiteDataQuery .
The URL would look like this
/_layouts/CopyUtil.aspx?Use=id&Action=dispform&ItemId="itemID"&ListId="listID"&WebId="webId"&SiteId="siteId"
The Action Parameter is the one you have to decide ,it might be dispform or editform.

Friday, June 24, 2011

To Find if the Page in MOSS is in Design Mode

Some Times we have to make the Jquery/JavaScript run when its not in the design mode.
I don't know how many of us has noted this tag "MSOLayout_InDesignMode" .This is a hidden HTML field present on the page. So using that its simple.

The HTML looks like this:
<input type="hidden" name="MSOLayout_InDesignMode" id="MSOLayout_InDesignMode" value="" />
if (document.getElementById("MSOLayout_InDesignMode").value != "1")
{
//do something
}
else
{
//do something
}

Thursday, June 23, 2011

Simple ways to check if List exist in MOSS using Lambda expressions

In MOSS we don't have a pre defined method of to check if a List Exist .Here comes new feature of  C# to extensions to rescue.

public static bool ListExists(this SPWeb web, string listName)
        {
            return web.Lists.Cast().Any(l => l.Title.Equals(listName, StringComparison.OrdinalIgnoreCase));
        }
Alternate for the Same

public static bool ListExists(SPWeb web, string listName)
         {
            var lists = web.Lists;
            foreach (SPList list in lists)
            {
                if(list.Title.Equals(listName))
                    return true;
            }
            return false;
       }

URL Encoding using JQuery

Ever came across a scenario where you have to encode using JavaScript/JQuery other than using C# especially in SharePoint.One of my experience User required a link when clicked to be passed as filter value to the Document Library/List.If the value is simple Text its easy but if the value contains Ex: Harrison & Thomas there is the problem .If you pass in the mentioned value as a  Query string parameter it understands as two arguments and hence the Library is not filtered .Here comes the encoding part as we can extended the Jquery Library function.

$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();
var r=/(^[a-zA-Z0-9_.]*)/;
  while(x
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){
  b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

Now you can call this  function as
$.URLEncode($(this).attr("title"));

Hint: Place this script below the List in Content Editor WebPart

Print Functionality using Javascript on MOSS

One of the Limitation in SharePoint is having no option to print for the users.Even though there are lot of solutions given by third party vendors or even solution mentioned in Codeplex or SharePoint Tips and Tricks blog I feel this can be done also using Java Script.
function printWebPart(tagid){
var WebPartElementID = tagid;
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '\n\n';
//Take data from Head Tag
 if (document.getElementsByTagName != null)
{
var HeadData= document.getElementsByTagName("HEAD");
if (HeadData.length > 0)
PrintingHTML += HeadData[0].innerHTML;
}
PrintingHTML += '\n\n\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML += WebPartData.innerHTML;
bolWebPartFound = true;
}
else
{ bolWebPartFound = false;
 alert ('Cannot Find Web Part');
 }
} PrintingHTML += '\n\n'; //Open new window to print
if (bolWebPartFound)
{
//alert("clicked print");

var PrintingWindow = window.open("","PrintWebPart", "toolbar,width=800,height=600,status=yes,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
PrintingWindow.document.close();
// Open Print Window
PrintingWindow.print();
PrintingWindow.close();
 }
}

Interesting Facts about DateTime and Varchar/Nvarchar in c# vs DataBase

When we insert data from either a console or ASP.net app to DataBase there are some interesting pit falls in a way Data types are handled from both ends.
We know that string in c# accepts null/empty values and you also have designed in the DB whether as Varchar/Nvarchar and allowing null.
When we insert value in the  DB it will not put null instead it throws error .So the best way to do is
Ex:
cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = DBNull.Value;
Similarly for the DateTime
 cmd.Parameters.Add("@OrgTargetDate", SqlDbType.DateTime).Value = System.Data.SqlTypes.SqlDateTime.Null; 

Verify if a Field Exist in MOSS 2007

I had a scenario where I have to iterate the same List name in a Site Collection but different sub sites.
Interesting fact is the list has different Fields.
Even though we don't have a method to verify if a list exist but there is one to check if a Field exist in SharePoint List/Document Library.

 SPList list = site.Lists["Your List Name"];
list.Fields.ContainsField("Yout Field Name")