Tag Archive: WebPart


Debugging Webpart dll from GAC

The global assembly cache (GAC) provides a centralised, machine-wide storage location for .NET assemblies. When you add an assembly to the GAC, you allow it to be shared by many programs, rather than requiring a copy to be installed for each application. It’s also the place you need to register your WebPart library when develop SharePoint WebPart solution.

To reduce the time for debugging, it’s mean without having to deploy my SharePoint solutions, fire up IIS, etc. etc. You can register output library to GAC directly with External Tools extension in Visual Studio.

By this way, you just build and deploy sourcode project only 1 time. After that, any changes from code behind, you can run this tool for your features update.

1. Download and extract bat file at here

2. Open Visual Studio, in this post, I would like show on Visual Studio 2008.
– Browse to Tools/External Tools
– Click Add button
– Fill some information as below. At Command textbox, browse and select bat file above

– Check on Use Output Window and Click OK to finish

3. Make sure it work correctly
– Rebuild project
– Select Tools/copyToGac from Visual Studio top menu
– Open Output window, the output result should be like this.

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen

Calendar is a great feature from SharePoint to hep you orgainze task, schedule and collaborate for your workspace. But WSS3.0 just allowed you display calendar data and Calendar view within current web and can not publish in another sites by default.

Today, I will show you how to develop a global calendar WebPart which will get data from specify Calendar list using SPquery and calendar view control. So you can easy to show on any page you want and display recurrence event as well.

Create Calenar list

Firstly, you need a calendar list to store all data for global calendar’s query and filter. In this article, I place this Calendar under subsite Workspace as below

Create Calendar Control

I will implement this webpart receive 2 parameters from WebPart properties

– Calendar List URL: This parameter will tell our Global calendar webpart where is calendart list datasource to query.

protected string calendarListUrl = string.Empty;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category(“Officience”)]
[WebDisplayName(“Calendar URL”),
DefaultValue(“/workspace/Lists/Calendar/calendar.aspx”),
WebDescription(“Calendar URL Property”)]
public string CalendarListUrl
{
get { return calendarListUrl; }
set { calendarListUrl = value.Trim(); }
}

– Locaton of Department: This parameter will provide name of Location. In this context, I call it as “Filter By Department”, so base on this parameter, we can filter event belong to this Department

protected string departmentFilter = string.Empty;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category(“Officience”)]
[WebDisplayName(“Filter By Department”),
DefaultValue(“Others”),
WebDescription(“Filter By Department”)]
public string DepartmentFilter
{
get { return departmentFilter; }set { departmentFilter = value.Trim(); }}

In the webpart code behind, as first thing you need to create and add calendar control inside CreateChildControls() method

protected override void CreateChildControls()
{
div = new HtmlGenericControl(“DIV”);div.Attributes.Add(“class”, “calendar”);Controls.Add(div);base.CreateChildControls();

try

{

AddButtons();

AddCalendar();

}

catch (Exception ex)

{

Controls.Add(new LiteralControl(“<b>Error</b> “));

Controls.Add(new LiteralControl(ex.ToString()));

}

}

Next, we need to implement AddButton and AddCalendar method.
In AddButton method, we will define 2 button, the first one allow you create New Event and the second one will redirect you to original calendar view (View All Events)

private void AddButtons()
{
LiteralControl sbCreate = new LiteralControl();SPList oList = GetListByUrl(CalendarListUrl);
string []strList = oList.DefaultViewUrl.Split(new char[] { ‘/’ });string strUrl = oList.DefaultViewUrl.Replace(strList[strList.Count() – 1].ToString(), “NewForm.aspx”);string NewFormUrl = strUrl + “?Source=” + Context.Request.Url;

sbCreate.Text = “<div id=\”divIdForm\”>” +

“<button id=\”BtnSubmit\” type=\”button\” onclick =  \”javascript:window.location='” + NewFormUrl + “\”)>” +

“New Event” +

“</button> ” +

“<button id=\”BtnViewAll\” class=\”btnView\” target=\”_blank\” width=\”100px\” type=\”button\” onclick = \”javascript:window.location='” + oList.DefaultViewUrl + “‘\”)>” +

“View All Events” +

“</button> ” +

“</div> “;
div.Controls.Add(sbCreate);

}

In AddCalendar method, we will declare and create calendar control. We need reference to specify web and then we play with returned data.

private void AddCalendar()
{
SPCalendarView calendar = null;calendar = new SPCalendarView();calendar.Visible = true;calendar.EnableViewState = true;

calendar.ViewType = GetCalendarType(Page.Request[“CalendarPeriod”]);

calendar.DataSource = getDataFromCalendar(CalendarListUrl, DepartmentFilter);

calendar.DataBind();

div.Controls.Add(calendar);

}
/// <summary>
/// Gets the type of the calendar view.
/// </summary>
/// <param name=”type”>The type to be checked.</param>
/// <returns>Correct view type of calendar.</returns>
private static string GetCalendarType(string type)
{
if (type == null)

type = string.Empty;

switch (type.ToLower())

{

case “day”:

return “day”;

case “week”:

return “week”;

case “timeline”:

return “timeline”;

default:

return “month”;

}

}

Now we implement for getDataFromCalendar() method. In this method, I seperated for 2 kind of event, they’re normal event and recurrence event, this method also use Location field as condition for filter material. Then we detect calendar view type (day view, week view,  month view) by request variables and as a last thing we bind data to calendar and add calendar to web part controls collection.

private SPCalendarItemCollection getDataFromCalendar(String str_calendarlist_url, String Organizer)
{
SPCalendarItemCollection collection = new SPCalendarItemCollection();string temp = “”;SPList oList = GetListByUrl(str_calendarlist_url);SPCalendarItem citem = null;

foreach (SPListItem item in oList.Items)

{

// Get calendar item which is not recurrence event

if (!(bool.Parse(item[“Recurrence”].ToString())))

{

if (item[“Location”] != null)

{

// Filter with Location

if (item[“Location”].ToString().ToLower().Trim() == Organizer.ToLower().Trim())

{

citem = new SPCalendarItem();

citem.ItemID = item[“ID”].ToString();

try

{

citem.StartDate = DateTime.Parse(item[“EventDate”].ToString());

}

catch { }

try

{

citem.EndDate = DateTime.Parse(item[“EndDate”].ToString());

}

catch { }

temp = item[“Title”] as string;

temp += ” ” + item[“RecurrenceData”];

citem.Title = item[“Title”] as string;

temp = oList.ParentWebUrl + “/” + oList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

citem.DisplayFormUrl = temp.Replace(“//”, “/”);

citem.Location = item[“Location”] as string;

citem.Description = item[“Description”] as string;

if (bool.Parse(item[“Recurrence”].ToString()))

{

citem.IsRecurrence = true;

}

else

{

citem.IsRecurrence = false;

}

citem.CalendarType = Convert.ToInt32(SPCalendarType.Gregorian);

collection.Add(citem);

}

}

else

{

citem = new SPCalendarItem();

citem.ItemID = item[“ID”].ToString();

try

{

citem.StartDate = DateTime.Parse(item[“EventDate”].ToString());

}

catch { }

try

{

citem.EndDate = DateTime.Parse(item[“EndDate”].ToString());

}

catch { }

temp = item[“Title”] as string;

temp += ” ” + item[“RecurrenceData”];

citem.Title = item[“Title”] as string;

temp = oList.ParentWebUrl + “/” + oList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

citem.DisplayFormUrl = temp.Replace(“//”, “/”);

citem.Description = item[“Description”] as string;

if (bool.Parse(item[“Recurrence”].ToString()))

{

citem.IsRecurrence = true;

}

else

{

citem.IsRecurrence = false;

}

citem.CalendarType = Convert.ToInt32(SPCalendarType.Gregorian);

collection.Add(citem);

}

}

}

// Query recurrence data

SPQuery queryRecurrence = new SPQuery();

queryRecurrence.ExpandRecurrence = true;

queryRecurrence.Query = “<Where>” +

“<And>” +

“<Eq>” +

“<FieldRef Name=’Location’ />” +

“<Value Type=’Text’>” + Organizer + “</Value>” +

“</Eq>” +

“<And>” +

“<Eq>” +

“<FieldRef Name=’fRecurrence’ />” +

“<Value Type=’Recurrence’>1</Value>” +

“</Eq>” +

“<DateRangesOverlap>” +

“<FieldRef Name=’EventDate’ />” +

“<FieldRef Name=’EndDate’ />” +

“<FieldRef Name=’RecurrenceID’ />” +

“<Value Type=’DateTime’>” +

“<Month />” +

“</Value>” +

“</DateRangesOverlap>” +

“</And>” +

“</And>” +

“</Where>” +

“<ViewFields>” +

“<FieldRef Name=’Title’ />” +

“<FieldRef Name=’EventDate’ />” +

“<FieldRef Name=’EndDate’ />” +

“<FieldRef Name=’fRecurrence’ />” +

“<FieldRef Name=’Absentee’ />” +

“</ViewFields>”;

// Look forward from the beginning of the current month

DateTime calendarDate = DateTime.Today;

if (!string.IsNullOrEmpty(Page.Request[“CalendarDate”]))

DateTime.TryParse(Page.Request[“CalendarDate”], out calendarDate);

queryRecurrence.CalendarDate = new DateTime(calendarDate.Year, calendarDate.Month, 1);

// Returns all items (including recurrence instances) that

// would appear in the calendar view for the current month

SPListItemCollection calendarItems = oList.GetItems(queryRecurrence);

foreach (SPListItem listItem in oList.GetItems(queryRecurrence))

{

SPCalendarItem calItem = new SPCalendarItem();

calItem.ItemID = listItem[“Edit Menu Table End”].ToString();

calItem.Title = listItem[“Title”].ToString();

calItem.CalendarType = Convert.ToInt32(SPCalendarType.Gregorian);

calItem.StartDate = (DateTime)listItem[“Start Time”];

if (listItem[“End Time”] != null)

{

calItem.hasEndDate = true;

calItem.EndDate = (DateTime)listItem[“End Time”];

}

else

calItem.hasEndDate = false;

if (listItem[“Description”] != null)

calItem.Description = listItem[“Description”].ToString();

if (listItem[“Location”] != null)

calItem.Location = listItem[“Location”].ToString();

temp = “”;

temp = oList.ParentWebUrl + “/” + oList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

calItem.DisplayFormUrl = temp.Replace(“//”, “/”);

collection.Add(calItem);

}

return collection;

}

Finally, I implement an utility method to get SPList from an url. So, you can easy to define where is the datasource by webpart’s properties

/// <summary>
/// Get List By URL
/// </summary>
/// <param name=”url”>List’s URL</param>
/// <returns>SPList</returns>
private SPList GetListByUrl(string urlListname)
{
if (urlListname.IndexOf(“http://&#8221;) < 0)if (urlListname.IndexOf(“Forms”) > -1)urlListname = SPContext.Current.Site.Url + urlListname;else if (urlListname.IndexOf(“Lists”) < 0)

urlListname = Microsoft.SharePoint.WebControls.SPControl.GetContextSite(Context).RootWeb.Url + “/Lists/” + urlListname + “/AllItems.aspx”;

else

urlListname = SPContext.Current.Site.Url + urlListname;
SPList listFromUrl;

using (SPSite site = new SPSite(urlListname))

{

using (SPWeb web = site.OpenWeb())

{

string pageUrl = urlListname.Substring(web.Url.Length).TrimStart(new char[] { ‘/’ });

listFromUrl = web.GetListFromUrl(pageUrl);

}

}

return listFromUrl;

}

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen
Related Article:
%d bloggers like this: