Friday, January 16, 2009

Resource file usage in .Net

This article describes how we can consume values from Resource file in various scenarios.

1) Consume resource value in C# code :



btnCancel.Text = Resources.myResource.ButtonCancel;




2) Consume resource value in HTML / Client control in HTML code :


<input type="button" id="btnAdd" text="<%= Resources.myResource.ButtonAdd %>" />




3) Consume resource value in Server control in HTML code :


<asp:ListItem Text="<%$ Resources:myResource, Yes%>"></asp:ListItem>



4) Consume resource value to set some para / span text in HTML code :


<p>
<asp:Literal runat="server" Text="<%$ Resources:myResource, Success%>" />
</p>



Note : In the above code, myResource is resource file name.

What I get the conclusion by implementing above scenarions are that :
In case of C# code, resource value usage is straight, just Resources.resourceFileName.keyName.
Whereas in case of HTML / ASP.Net code, if I am using HTML / Client control then we have to use "<%= ... %>" (percentage symbol) and in case of Server control we have use "<$= ... %>" (dollar symbol).

Thursday, January 15, 2009

To change style (CSS) of menuitem in SharePoint

This article describes how we can change the style (CSS) of menuitem in SharePoint.

Open the following file (preferably in Visual Studio IDE):

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\STYLES\Core.css

To change menuitem cell (Line 1345 --- aprox) :



.ms-menuimagecell
{
background:Maroon
/*background:#ffe6a0 */

url("/_layouts/images/selectednav.gif")
repeat-x;
cursor:pointer;
border:solid 1px #ffffff;
padding:0px;
height:18px;
}



To change menuitem - OnHover (Line 4012 --- aprox) :


.ms-MenuUIItemTableHover
{
background-color:Blue;
border:1px solid Red;

/*background-color:#ffe6a0;
border:1px solid #d2b47a;*/
}



Note : Before making any changes, don't forget to keep the back-up copy of Core.css

Following will be the effect of above changes :

Customize --- "Welcome UserName" control in SharePoint

This article describes how we can customize --- "Welcome UserName" control in SharePoint.



To edit the existing Welcome control in sharePoint, first you have to open the following file (preferably in Visual Studio IDE):

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx



<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Control Language="C#" Inherits="Microsoft.SharePoint.WebControls.Welcome,Microsoft.SharePoint,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" AutoEventWireup="false" compilationMode="Always" %>
<SharePoint:PersonalActions AccessKey="<%$Resources:wss,personalactions_menu_ak%>" ToolTip="<%$Resources:wss,open_menu%>" runat="server" id="ExplicitLogout" Visible="false">
<CustomTemplate>
<SharePoint:FeatureMenuTemplate runat="server"
FeatureScope="Site"
Location="Microsoft.SharePoint.StandardMenu"
GroupId="PersonalActions"
id="ID_PersonalActionMenu"
UseShortId="true" Visible="true"
>
<SharePoint:MenuItemTemplate runat="server" id="ID_PersonalInformation"
Text="1 <%$Resources:wss,personalactions_personalinformation%>"
Description="<%$Resources:wss,personalactions_personalinformationdescription%>"
MenuGroupId="100"
Sequence="100"
ImageUrl="/_layouts/images/menuprofile.gif"
UseShortId="true" Visible="false"
/>
<SharePoint:MenuItemTemplate runat="server" id="ID_LoginAsDifferentUser"
Text="2 <%$Resources:wss,personalactions_loginasdifferentuser%>"
Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
MenuGroupId="200"
Sequence="100"
UseShortId="true"
/>
<SharePoint:MenuItemTemplate runat="server" id="ID_RequestAccess"
Text="3 <%$Resources:wss,personalactions_requestaccess%>"
Description="<%$Resources:wss,personalactions_requestaccessdescription%>"
MenuGroupId="200"
UseShortId="true"
Sequence="200"
/>
<SharePoint:MenuItemTemplate runat="server" id="ID_Logout"
Text="4 <%$Resources:wss,personalactions_logout%>"
Description="<%$Resources:wss,personalactions_logoutdescription%>"
MenuGroupId="200"
Sequence="300"
UseShortId="true" Visible="false"
/>
<SharePoint:MenuItemTemplate runat="server" id="ID_PersonalizePage"
Text="5 <%$Resources:wss,personalactions_personalizepage%>"
Description="<%$Resources:wss,personalactions_personalizepagedescription%>"
ImageUrl="/_layouts/images/menupersonalize.gif"
ClientOnClickScript="javascript:MSOLayout_ChangeLayoutMode(true);"
PermissionsString="AddDelPrivateWebParts,UpdatePersonalWebParts"
PermissionMode="Any"
MenuGroupId="300"
Sequence="100"
UseShortId="true"
/>
<SharePoint:MenuItemTemplate runat="server" id="ID_SwitchView"
MenuGroupId="300"
Sequence="200"
UseShortId="true"
/>
<SharePoint:MenuItemTemplate runat="server" id="MSOMenu_RestoreDefaults"
Text="6 <%$Resources:wss,personalactions_restorepagedefaults%>"
Description="<%$Resources:wss,personalactions_restorepagedefaultsdescription%>"
ClientOnClickNavigateUrl="javascript:MSOWebPartPage_RestorePageDefault()"
MenuGroupId="300"
Sequence="300"
UseShortId="true"
/>
</SharePoint:FeatureMenuTemplate>
mmm
</CustomTemplate>
</SharePoint:PersonalActions>
<SharePoint:ApplicationPageLink runat="server" id="ExplicitLogin"
ApplicationPageFileName="Authenticate.aspx" AppendCurrentPageUrl=true
Text="<%$Resources:wss,login_pagetitle%>" style="display:none" Visible="true" />



Note : The above code is modified one... so don't copy-paste it exactly. Also keep the back-up of your original file :)

To hide a particular menuitem, either you can delete its code from the file or set its Visible property to false (as specified in above code for menuitem 1 & 4).

Following will be the result of above code:




To add a new menuitem, you can refer following article:
Custom-action-locations-and-groupid (to add extra menu in drop down)

Friday, December 19, 2008

Dot Net Tips n Tricks

1) To set the textbox's Text property having TextBoxMode property set to Password:
In case of normal textbox, we change its Text property by writing following code :



TextBox txtSample = new TextBox();
txtSample.Text = "Sample";


But in case if we are using textbox for Password purpose, then we have to set its TextBoxMode to Password. So to change its Text property we have to use following code:


TextBox txtPassword = new TextBox();
if (txtPassword.TextMode == TextBoxMode.Password)
{
//newValue is the new value that we want to set.
txtPassword.Attributes.Add("value", newValue);
}




2) Code to remove HTML contents from a string :


public string RemoveHTML(string strHTML)
{
//System.Web.HttpContext.Current.Server.HtmlDecode
return Server.HtmlDecode(Regex.Replace(strHTML, "<(.|\n)*?>", ""));
}

Tuesday, December 9, 2008

ASP.Net Calendar control

Following are the steps to use ASP.Net calendar control in a web page:

1) Add <asp:Calendar ... > control tag in your web page.

HTML code:



<table>
<tr>
<td>
<asp:TextBox ID="txtDate" runat="server" Width="300px"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnDate" runat="server"
Text="..." OnClick="btnDate_Click"></asp:Button>
</td>
</tr>
<tr>
<td>
<asp:Calendar ID="calendar" runat="server" OnDayRender="OnDayRender"
BackColor="#ffffff" Width="300px" Height="300px" Font-Size="14px"
NextPrevFormat="shortmonth" DayNameFormat="firsttwoletters"
Visible="False" OnSelectionChanged="calendar_SelectionChanged">

<TodayDayStyle ForeColor="White" BackColor="Black"></TodayDayStyle>
<NextPrevStyle Font-Size="14px" Font-Bold="True"
ForeColor="#333333"></NextPrevStyle>
<DayHeaderStyle Font-Size="14px" Font-Bold="True"></DayHeaderStyle>
<TitleStyle Font-Size="16px" Font-Bold="True"
BorderWidth="2px" ForeColor="#000055"></TitleStyle>
<OtherMonthDayStyle ForeColor="#CCCCCC"></OtherMonthDayStyle>

</asp:Calendar>
</td>
<td>
</td>
</tr>
</table>



2) As visible property of calendar control is set to false, so on button click event set calendar's visible property to true and also set the selected date of calendar from the textbox.

CSharp (C#) code:


protected void btnDate_Click(object sender, EventArgs e)
{
try
{
if (txtDate.Text.Trim() != "")
calendar.SelectedDate = Convert.ToDateTime(txtDate.Text);
}
catch
{ }

calendar.Visible = true; //showing the calendar.
}




3) Add code to handle the SelectionChanged event of calendar control.

CSharp (C#) code:


protected void calendar_SelectionChanged(object sender, EventArgs e)
{
//Displaying the selected date in TextBox
txtDate.Text = calendar.SelectedDate.ToString("d");
calendar.Visible = false; //hiding the calendar.
}




4) Now to disable the earlier/previous date selection in caledar control, handle OnDayRender event of Calendar control.

CSharp (C#) code:


protected void OnDayRender(Object sender, DayRenderEventArgs e)
{
e.Day.IsSelectable = (e.Day.Date >= DateTime.Today);
//e.Day.IsSelectable = (e.Day.Date >= DateTime.Now);
}




Following is the snapshot of Calendar control in a web page :

Wednesday, December 3, 2008

SharePoint's ListViewWebPart

To use SharePoint's ListViewWebPart directly in your ASPX page, follow these steps:

1) Register Microsoft.SharePoint.WebPartPages namespace in ASPX page :



<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>




2) Add following ListViewWebPart's html code :


<WebPartPages:ListViewWebPart ID="oListViewWP" runat="server" __WebPartId="{GUID}"
WebPart="true"></WebPartPages:ListViewWebPart>


Note :
Replace GUID in above code either by a newly generated GUID or if you are using SharePoint designer, then SharePoint designer will automatically insert a new GUID in your HTML code when you try to save the ASPX page.


3) Add following server side code to populate data in ListViewWebPart :


SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["Announcements"];

oListViewWP.ListName = oList.ID.ToString("B").ToUpper();
oListViewWP.ViewGuid = oList.Views["MyView"].ID.ToString("B").ToUpper();

oListViewWP.GetDesignTimeHtml();


Note :
Don't forget to write oListViewWP.GetDesignTimeHtml();, otherwise ListViewWebPart will not display any data in it.

Here MyView is just a dummy SPView name, you can use either default SPView or can create a new SPView with only desired columns and settings.

====================================================================
====================================================================

Now if you want to hide/remove the ToolBar from ListViewWebPart, then as per me following are the two ways :
1) Set SuppressWebPartChrome property of WebPart


oListViewWP.SuppressWebPartChrome = true;



2) One of the problem with above code is that it hide the toolBar in ListViewWebPart as well as in the SPList/SPView from which it is displaying the data
( I face this problem, not sure about others :) ).

So, the other alternative is to add following CSS in our code:


<style type="text/css">
.ms-menutoolbar { display: none; }
</style>


Be careful while using the above CSS, because it hide all the ToolBars which uses the .ms-menutoolbar CSS class.


Reference :
MSDN Forum


====================================================================
====================================================================

If you want to apply Filter on ListViewWebPart's column or in other words, display data in ListViewWebPart with only desired column value, then write following code :


string columnValue = "SP";
oListViewWP.FilterString = "FilterField1=Title&FilterValue1=" + columnValue;



The above code results in the display only those records whose column name Title has value SP.

====================================================================
====================================================================

Another major challenge that i faced while using ListView WebPart (or in any normal WebPart) is to change/modify the Empty message or no record message.

The exact message is : There are no items to show in this view of the "ViewName" list. To create a new item, click "New" above.

One of the way to change this message is to modify the ViewEmpty XML node of ListViewXml.

Following code snippet describes the way to change the empty message of ListView WebPart :


//oListViewWP is ListView WebPart instance
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(oListViewWP.ListViewXml);
XmlNode node = xmlDoc.SelectSingleNode("//ViewEmpty");
if (node != null)
{
StringBuilder strB = new StringBuilder();
strB.Append("<HTML><![CDATA[<SPAN Class='ms-vb' style='width:200px;'>]]></HTML>");
strB.Append("<HTML>There is no item to show.</HTML>");
strB.Append("<HTML><![CDATA[</SPAN>]]></HTML>");

node.InnerText = strB.ToString();
}

oListViewWP.ListViewXml = xmlDoc.OuterXml;
oListViewWP.GetDesignTimeHtml();



Note : It is required to set the ListViewXml before GetDesignTimeHtml() function call.


Otherwise, if you are using SharePoint Designer and using/populating ListView WebPart in design time. Then simply search following text :
There are no items to show in this view of the and replace it with your required/desired message.


Another way is to change/modify the text directly in core.resx file that reside at following location :
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Resources\core.resx.

Note : If we change the core.resx file, it will be gets reflected in all sites that are using the core.resx resource file.

Friday, November 28, 2008

CAML Tips n Tricks

CAML --- Collaborative Application Markup Language

1) CAML query to fetch a record :



SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["Announcements"];

string strQuery = "<Where>" +
"<Eq>" +
"<FieldRef Name='ID'/>" +
"<Value Type='Number'>1</Value>" +
"</Eq>" +
"</Where>";

SPQuery oQuery = new SPQuery();
oQuery.Query = strQuery;
SPListItemCollection ItemCol = oList.GetItems(oQuery);
if (ItemCol.Count > 0)
{
string strTitle = ItemCol[0]["Title"].ToString();
}





2) CAML query to fetch highest/lowest record :


//To get highest value set Ascending to False else to
//get lowest value don't use it (by-default Ascending is set to True).
string strQuery = "<OrderBy>" +
"<FieldRef Name='ID' Ascending='False' />" +
"</OrderBy>";

SPQuery oQuery = new SPQuery();
oQuery.Query = strQuery;
//Set the RowLimit, so that it fetch only 1 record which is the required one.
oQuery.RowLimit = 1;





3) CAML query to fetch only the required columns instead of all columns (by-default) :


//Specify only the required columns name in ViewFields.
string strViewFields = "<FieldRef Name='ID'/>" +
"<FieldRef Name='Title'/>" +
"<FieldRef Name='Name'/>";

SPQuery oQuery = new SPQuery();
oQuery.ViewFields = strViewFields;





4) CAML query to update SPListItem(s) in batch/bulk :


//Current WebSite.
SPWeb oWebsite = SPContext.Current.Web;
SPQuery oQuery = new SPQuery();

// Set up the variables to be used.
StringBuilder methodBuilder = new StringBuilder();
string batch = string.Empty;

string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ows:Batch OnError=\"Return\">{0}</ows:Batch>";

SPList oList = oWebsite.Lists["Announcements"];
//Get SPList's ID
string listGuid = oList.ID.ToString();

//Here we are going to change 'Title' Column/SPField of SPListItem.
string methodFormat = "<Method ID=\"{0}\">" +
"<SetList>" + listGuid + "</SetList>" +
"<SetVar Name=\"Cmd\">Save</SetVar>" +
"<SetVar Name=\"ID\">{1}</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#Title\">{2}</SetVar>" +
"</Method>";

//Set the RowLimit, to optimize the performance.
query.RowLimit = 100;
do
{
SPListItemCollection unprocessedItems = oList.GetItems(query);
//Process all the returned items in this page
// Build the CAML update commands.
for (int i = 0; i < unprocessedItems.Count; i++)
{
//SPListItem ID
int itemID = unprocessedItems[i].ID;
//Set the new value, based on the requirement/logic.
//Here you can use an Array or a Constant string.
string newValue = "Sample";
//string newValue = myArray[i];

methodBuilder.AppendFormat(methodFormat, itemID, itemID, newValue);
}

// Build the final string.
batch = string.Format(batchFormat, methodBuilder.ToString());

// Process the batch of commands.
string batchReturn = oWebsite.ProcessBatchData(batch);

//Gets an object used to obtain the next set of rows in a paged view of a list.
query.ListItemCollectionPosition = unprocessedItems.ListItemCollectionPosition;
} while (query.ListItemCollectionPosition != null);



Reference :
Batch Updating List Items in Windows SharePoint Services 3.0

Google