Saturday, September 10, 2011

Create Calendar Workspace and Redirect to custom workspace page in SharePoint 2010

I want to discuss regarding custom calendar workspace in this post. when we create a sharepoint calendar workspace, it is automatically redirects to out of box page newMWS.aspx where you can give  the url name of workspace in oob page. as per our client requirement it should not redirect to newMWS.aspx  page and should not ask for to create a site.

to achieve this we must create a Custom Calendar List

lets see below steps
1.) check the workspace checkbox by default
2.)Restrict the user to uncheck the checkbox
3.) Redirect to a custom page when the workspace is created.

i created custom content type and when you click on this from new menu, it automatically checked to workspace checkbox . when you click on save button it redirects to customworkspace.aspx page
first step :

1)You must create a Custom List Definition for Calendar.

Actual Field  :

<Field ID="{08fc65f9-48eb-4e99-bd61-5946c439e691}" FillInChoice="False" Type="CrossProjectLink" Name="WorkspaceLink" Format="EventList" DisplayName="$Resources:core,Workspace;" DisplayImage="mtgicon.gif" HeaderImage="mtgicnhd.gif" ClassInfo="Icon" Title="$Resources:core,Meeting_Workspace;" Filterable="TRUE" Sealed="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="WorkspaceLink" ShowInDisplayForm="FALSE">
               
                <FieldRefs>
          <FieldRef Name="Workspace" RefType="LinkURL" CreateURL="newMWS.aspx">$Resources:core,Calendar_MeetingWorkspaceField_Desc;</FieldRef>
          <FieldRef Name="RecurrenceID" RefType="RecurrenceId" DisplayName="$Resources:core,Instance_ID;" />
          <FieldRef Name="EventType" RefType="EventType" />
          <FieldRef Name="UID" RefType="UID" />
        </FieldRefs>
      </Field>
             

here you can give your custom page url which is avilable in _layouts folder.

Update a filed as mentioned below :

<Field ID="{08fc65f9-48eb-4e99-bd61-5946c439e691}" FillInChoice="False" Type="CrossProjectLink" Name="WorkspaceLink" Format="EventList" DisplayName="$Resources:core,Workspace;" DisplayImage="mtgicon.gif" HeaderImage="mtgicnhd.gif" ClassInfo="Icon" Title="$Resources:core,Meeting_Workspace;" Filterable="TRUE" Sealed="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="WorkspaceLink" ShowInDisplayForm="FALSE">FieldRefs>FieldRef Name="Workspace" RefType="LinkURL" CreateURL="customworkspace.aspx">$Resources:core,Calendar_MeetingWorkspaceField_Desc;</FieldRef>FieldRef Name="RecurrenceID" RefType="RecurrenceId" DisplayName="$Resources:core,Instance_ID;" />FieldRef Name="EventType" RefType="EventType" />FieldRef Name="UID" RefType="UID" />FieldRefs>Field>

2nd step: Create custom workspace content type

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
        <ContentType ID="0x01020040bc988755064919bdff99cafa3b38f4001421e28a5efd4635aa50cf2a4083bf51"
                                 Name="CTCustomWS"
                                 Group=" Custom Content Types"
                                 Description="Custom Workspace content Type"
                                 Inherits="TRUE"
                                 Version="0">
                <FieldRefs>
<!-- this field will be useful for to show workspace url  -->
                        <FieldRef ID="{41063E43-A214-4434-8313-FC88C859CFA9}" Name="OPSWorkspaceLink" DisplayName="Workspace Link" ShowInNewForm="FALSE" />
                </FieldRefs>
         
        </ContentType>
</Elements>

 3rd step: Create a event receiver to update workspace url
  public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            string sSubString, sSiteTitle, sWSName = string.Empty;
            //SPSite oSite = null; // new SPSite(properties.SiteId);
            //SPWeb oWeb = oSite.OpenWeb(properties.RelativeWebUrl);

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                     using (SPSite oSite = new SPSite(properties.SiteId))
                     {
                         using (SPWeb oWeb = oSite.OpenWeb(properties.RelativeWebUrl)) //
                         {
                             oWeb.AllowUnsafeUpdates = true;
                             EventFiringEnabled = false;

                             if (properties.List != null)
                             {
                                 //(please replace with your id)
                                 if (properties.List.BaseTemplate.ToString() == "10013") // calendar basetemplate id
                                 {
                                     //for calendar event workspace
                                     if (properties.AfterProperties["ContentType"] != null && properties.AfterProperties["WorkspaceLink"] != null)
                                     {
                                         if (properties.List.BaseTemplate.ToString() == "10013" && properties.AfterProperties["ContentType"].Equals("CTCustomWS") && properties.AfterProperties["WorkspaceLink"].Equals("True"))
                                         {
                                             if (properties.AfterProperties["Title"] != null)
                                                 sWSName = properties.AfterProperties["Title"].ToString();

                                             string sURL = properties.List.ParentWebUrl + "/_layouts/customworkspace.aspx?title=" + sWSName; // +"&location=" + sLocation + "&Desc=" + sDescription + "&startdt=" + sStartDate + "&enddt=" + sEndDate; // +"&IsDlg=0";
                                             properties.AfterProperties["OPSWorkspaceLink"] = "<DIV><A href='" + sURL + "' target='_blank'>" + properties.AfterProperties["Title"].ToString() + "</A></DIV>";
                                             properties.AfterProperties["WorkspaceLink"] = true;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { }
        }

  public override void ItemUpdating(SPItemEventProperties properties)
        {
//please follow all conditions as mentioned in the adding event
string sURL = properties.List.ParentWebUrl + "/_layouts/customworkspace.aspx?title=" + sWSName;
                                            properties.AfterProperties["OPSWorkspaceLink"] = "<DIV><A href='" + sURL + "' target='_blank'>" + properties.AfterProperties["Title"].ToString() + "</A></DIV>";
}

 4th step:

now we are done with custom calendar list definition and event reciever to update workspace url. i am implementing code for customworkspace.aspx page

actually here i am showing 4 user controls in the workspace page
UCWorkingDocuments
UCPictureLibrary
UCTasksUCAttendees

protected void Page_Load(object sender, EventArgs e)
        {
            //System.Diagnostics.Debugger.Break();                       
            try
            {
   //when u click on save button in the custom content type window, it automatically redirects to our custom page as we mentioned in the schema.xml page. it returns querystring splistitem value.
                if (Request.QueryString["Item"] != null)
                {
                    oWeb = SPContext.Current.Web;
                    SPList oCalendarList = oWeb.Lists.TryGetList("Calendar");

                 

                    SPListItem oCalItems = oCalendarList.GetItemById(Convert.ToInt32(Request.QueryString["Item"].ToString()));

                    if (oCalItems != null && oCalItems["Title"] != null)
                    {
                        sTitle = oCalItems["Title"].ToString();

                        if (oCalItems["Location"] != null)
                            lblLocation.Text = oCalItems["Location"].ToString();

                        if (oCalItems["Start Time"] != null)
                            lblStartDate.Text = Convert.ToDateTime(oCalItems["Start Time"].ToString()).ToString();

                        if (oCalItems["End Time"] != null)
                            lblEndate.Text = Convert.ToDateTime(oCalItems["End Time"].ToString()).ToString();

                        if (oCalItems["Description"] != null)
                            lblDescription.Text = oCalItems["Description"].ToString();

                        if (oCalItems["Title"] != null)
                            lblMissionName.Text = oCalItems["Title"].ToString();

   //these r all workspace page user controls
                        UCWorkingDocuments.sWorkspaceTitle = sTitle;
                        UCPictureLibrary.sWorkspaceTitle = sTitle;
                        UCTasks.sWorkspaceTitle = sTitle;
                        UCAttendees.sWorkspaceTitle = sTitle;
                        hdnWorkspaceTitle.Value = sTitle;
                    }
                }

            

            }
            catch (Exception exp)
            {
                Response.Write(exp.Message.ToString());
            }
            finally
            {
                oWeb.Dispose();
            }
        }

Picture1: you can see custom content workspace from new menu


picture:2
in this workspace page i am showing 4 user controls like documents, tassks, attendees, picture library



   //task usercontrol code..
SPList oTaskList = oHomeWeb.Lists.TryGetList("OPSTasks");
                      if (oWorkingDocumentsList == null)
                      {
                          oWorkingDocumentsList = oHomeWeb.Lists.TryGetList("Tasks");
                      }

                      SPView oCustomView = oWorkingDocumentsList.Views["CustomView"];
                      oCustomView.RowLimit = 5;

                      ListViewWebPart lvwpShowFiles = new ListViewWebPart();
                      lvwpShowFiles.ID = "wpListView";
                      lvwpShowFiles.ListName = oWorkingDocumentsList.ID.ToString("B").ToUpper();
                      lvwpShowFiles.ViewGuid = oCustomView.ID.ToString("B").ToUpper();

                           dvSummaryView.Controls.Add(lvwpShowFiles);


 5th step:

we are almost done with custom workspace. now we have to implement javascript code to select automatically check the chekbox for custom content type event. you can see in the below picture.



I am hiding workspace checkbox for calendar event as you see in the below picture , i dont want to let users create a workspace from this event. I mean "Events" allows to create a regular caledar event without a workspace.




javascript code:

<script type="text/javascript">
      
   
        _spBodyOnLoadFunctionNames.push("fillDefaultValues");
   
       function fillDefaultValues() {

           var cid = querySt("ContentTypeId");

           if (cid != null) {
//here mission means custom workspace content type
               var vMission = cid.match("0x01020040BC988755064919BDFF99CAFA3B38F4001421E28A5EFD4635AA50CF2A4083BF51");


               if (vMission != null) //for calendar  mission contenttype
               {
                   getTagFromIdentifierAndTitle("input", "checkbox", "Workspace");
               }
               else //for calendar event contenttype
               {
                   var vEvents = cid.toLowerCase();
                   if (vEvents.match("0x01020040bc988755064919bdff99cafa3b38f4") != null) {
                       hideWorkspace();
                   }
               }
           }
           else {
               var dropdownid = getContentType("select", "Choice", "Content Type");
               //alert(dropdownid);
               if (dropdownid != null)
               {
                   // alert("dropdownid" + drop  Adownid);
                   var dropdown = document.getElementById(dropdownid);
                   var index = dropdown.selectedIndex;
                   var evetype = dropdown.options[index].text;
//alert("misssion:" + evetype);
                   if (evetype == "Mission") {
                       // alert("misssion:" + evetype);
                       getTagFromIdentifierAndTitle("input", "checkbox", "Workspace");
                   }
                   else if (evetype == "Events") {
                       //alert("event: " + evetype);
                       hideWorkspace();
                   }

               }
           }
       }

       //finds content type dropdown and returns id (this code execute when click on event in calendar Lists/Events/calendar.aspx page)
       function getContentType(tagName, identifier, title) {
           var len = identifier.length;
           var tags = document.getElementsByTagName(tagName);
           for (var i = 0; i < tags.length; i++) {
               var tempString = tags[i].id;

               if (tempString.match('ContentTypeChoice')) //get content type id from dropdown
               {
                   return tags[i].id;
               }

           }
           return null;
       }


       function hideWorkspace() {
           var TDs = document.getElementsByTagName("TD");
           var i = 0;
           var tagContent = "";
           while (i < TDs.length) {
               try {
                   tagContent = TDs[i].innerText || TDs[i].textContent;
                   if (tagContent.indexOf("Workspace") == 0 || tagContent.indexOf("Workspace") == 3) {
                       TDs[i + 1].parentNode.removeChild(TDs[i + 1]);
                       TDs[i].parentNode.removeChild(TDs[i]);
                   }
               }
               catch (err) { }
               i = i + 1;
           }
       }

       //it checks the workspace checkbox and restrict to uncheck from user
       function getTagFromIdentifierAndTitle(tagName, identifier, title) {

           var len = identifier.length;
           var tags = document.getElementsByTagName(tagName);
           for (var i = 0; i < tags.length; i++) {

               //alert("id::" + tags[i].id + "---title:---" + tags[i].title);
               var tempString = tags[i].id;
               if (tempString.match('CrossProjectLinkField')) {
                   document.getElementById(tags[i].id).checked = true;

                   //user cant uncheck the checkbox
                   var v = document.getElementById(tags[i].id);
                   v.onclick = function () { return false; }
                   return true;
               }

           }
           return null;
       }

       function querySt(ji) {
           hu = window.location.search.substring(1);
           //alert(hu);
           gy = hu.split("&");
           for (i = 0; i < gy.length; i++) {
               ft = gy[i].split("=");
               if (ft[0] == ji) {
                   return ft[1];
               }
           }
       }

       function ReadOnlyCheckBox() {
           return false;
       }

    </script>

No comments:

Post a Comment

Followers