Thursday, May 24, 2012

Customising exception with SPException class

I found this approach for handling the excepting in SharePoint 2010 is an elegant way. I simply pass the System Exception to SPException class and retrieved the exception details. Previously I have used the using operator to suppress the exception and clean carbage collection on my coding. But there were plenty of situation to capture the error and log into the database or system file. Here I have used to log the error details with inputs and result in the SharePoint List. I need to check this code and refine using "SPDisposeChecker tool".
protected void Button1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(TextBox1.Text) && !String.IsNullOrEmpty(TextBox2.Text))
            {
                int a = Convert.ToInt32(TextBox1.Text);
                int b = Convert.ToInt32(TextBox2.Text);
                SPSite site=null;
                SPWeb web=null;
                SPList list=null;
                SPListItem item=null;

                try
                {

                    site = SPContext.Current.Site;
                    web = site.OpenWeb();
                    list = web.Lists["Calc"];
                    item = list.Items.Add();
                    item["A"] = a;
                    item["B"] = b;
                    Label1.Text = (a / b).ToString();
                    item.Update();

                }

                catch (Exception ex)
                {
                    SPException ex1 = new SPException(ex.Message, ex);

                    item["A"] = a;
                    item["B"] = b;
                    item["Result"] = ex1.Message;
                    item.Update();
                }

            }
        }

Monday, May 21, 2012

Generating ics file from sharepoint calendar

This code will generate the outlook's meeting file format.ics file. This codes were written for the scenario where the meeting will be announced in SharePoint Calendar with EventID and the column named Meeting Attendees [People Picker with multiple values] to capture the acknowledgement of the end user. Every time user generate the ics file,their details will be logged into different List. This will also address the how to insert the SPUser value into SPUserFieldValueCollection and SPFieldUserValue programmatically in People Picker control.
 using (SPSite site = SPContext.Current.Site)
                {
                      StringBuilder sb = new StringBuilder();
        
                    using (SPWeb web = site.OpenWeb())
                    {

                        SPList list = web.Lists["Calendar"];
                        string _CamlQuery = "" + Convert.ToInt32(Request.QueryString["EventID"].ToString()) + "";
                        SPQuery query = new SPQuery();
                        query.Query = _CamlQuery;
                        DataTable dt = list.GetItems(query).GetDataTable();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            lblEventId.Text = dt.Rows[i]["EventID"].ToString();
                            lblTitle.Text = dt.Rows[i]["Title"].ToString();
                            lblDescription.Text = dt.Rows[i]["Description"].ToString();
                            lblStart.Text = dt.Rows[i]["EventDate"].ToString();
                            lblEnd.Text = dt.Rows[i]["EndDate"].ToString();
                            lblLocation.Text = dt.Rows[i]["Location"].ToString();
                        }

                        DateTime start = Convert.ToDateTime(lblStart.Text);
                        DateTime end = Convert.ToDateTime(lblEnd.Text);
                        sb.Append("BEGIN:VCALENDAR"); sb.Append(",");
                        sb.Append("PRODID:-");
                        sb.Append("VERSION:1.0"); sb.Append(",");
                        sb.Append("BEGIN:VEVENT"); sb.Append(",");
                        sb.Append(start.ToString("yyyyMMdd\\THHmmss\\Z")); sb.Append(",");
                        sb.Append(end.ToString("yyyyMMdd\\THHmmss\\Z")); sb.Append(",");
                        sb.Append("LOCATION:" + lblLocation.Text); sb.Append(",");
                        sb.Append("CATEGORIES:Meeting"); sb.Append(",");
                        sb.Append("DESCRIPTION:" + lblDescription.Text); sb.Append(",");
                        sb.Append("meeting=0D=0A"); sb.Append(",");
                        sb.Append("SUMMARY:" + lblTitle.Text); sb.Append(",");
                        sb.Append("PRIORITY:3"); sb.Append(",");
                        sb.Append("END:VEVENT"); sb.Append(",");
                        sb.Append("END:VCALENDAR");
                        string[] contents = sb.ToString().Split(',');
                        File.WriteAllLines("C:\\windows\\Temp\\" + lblTitle.Text.ToString() + ".ics", contents);
                    }

                }

Tuesday, May 08, 2012

Sorting Attached files in SharePoint List Item

Recently I have a requirement to sort the attached files those attached into SharePoint List Item. I have an application page to retrieve these collection of files by passing the item's id in page "Bulletted List" control has been used and set the property as hyper link.

Uploading the attachment into this Item also done through SharePoint Object Model.It's simply works fine on retrieving and showing them in ASP.NET's bulleted control.Later out business requirement got changed.They wanted these attached files were sequentially ordered and displayed so.

I tried many approaches to sort these files using Generic Classes in C# . I found lot of useful methods using LinQ,SortedList,KeyValuePair,Dictionary and SortedDictionary.But I need to implement in ASP.NET 2.0 only.

Still I found no luck :)- on my sorting tasks on attached files.But the development environment is verily limited to ASP.NET 2.0. Couple of day later,I started to think of actual index in attachment collection in sharepoint list item. When I checked the item and its view mode.I found all of the attached files were randomly ordered still I could not pin point in what basis these were ordered.

Sorting based on "File Info" ???.

On Checking on SPAttachmentCollection class I found its just name of the attached files array not even the file object.So I get the URL for each of this files and assigned to SPFile.

Now I have "TimeCreated" property of this SPFile.I pass these file names and its time of creation into Dictionary class to sorting. Interesting Dictionary class can only sorting the collection of items by "Key" not as value.But I need to sorting by value "TimeCreated". But If I wanted to sorting based on "TimeCreated" property,every time an end user need to create new file and upload.If they upload old files it won't make any sense and won't be end user friendly.

So I need to check alternate way of sorting this files.May be I need to use ICollection class to sort the attachment collection.

Anyhow ASP.NET 3.5 enables this task very simple by few lines of code.

 SPSite site = SPContext.Current.Site;
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Friends"];
            SPListItem item = list.GetItemById(1);
            Dictionarydictionary = new Dictionary();
            SPAttachmentCollection attachments = item.Attachments;

            foreach (string fileName in attachments)
            {
                SPFile file = web.GetFile(attachments.UrlPrefix + fileName);
                dictionary.Add(file.Name.ToString(), file.TimeCreated);
            }
             List> sorted = (from sp in dictionary orderby sp.Value select sp).ToList();
            ListBox1.DataSource = sorted;
            ListBox1.DataBind();
            ListBox1.DataSource = sorted;
            ListBox1.DataBind();

Monday, May 07, 2012

current user in sharepoint

Trimmed lines of code to get the currently logged in user details in SharePoint
 public SPUser GetCurrentUser()
        {
            var context = SPContext.Current;
            SPWeb web = context.Web;
            return web.CurrentUser;
        }

After you getting the SPUser object you can retrieve the login name,email,first name and last name of this user.