Tuesday, February 25, 2014

How to use progrmatically SPSITEDATAQUERY in SharePoint

 string username = SPContext.Current.Web.CurrentUser.Name;
            if (username != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (web = site.OpenWeb())
                        {



                            string where = @"<Where><And><Contains><FieldRef Name='AssignedTo' /><Value Type='User'>" + username + "</Value></Contains><And><Leq><FieldRef Name='DueDate' /><Value Type='DateTime'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now) + "</Value></Leq><Or><Eq><FieldRef Name='Status' /><Value Type='Choice'>Not Started</Value></Eq><Eq><FieldRef Name='Status' /><Value Type='Choice'>In Progress</Value></Eq></Or></And></And></Where>";

                            SPSiteDataQuery query = new SPSiteDataQuery();
                            query.Webs = "<Webs Scope='SiteCollection'>";
                            query.Lists = "<Lists ServerTemplate='171'/>";
                            query.ViewFields = "<FieldRef Name='Title' Type='Text'/>";
                            query.ViewFields += "<FieldRef Name='StartDate' />";
                            query.ViewFields += "<FieldRef Name='DueDate' />";
                            query.ViewFields += "<FieldRef Name='Status' />";
                            query.ViewFields += "<FieldRef Name='Assigned_To' Type='UserMulti' Nullable='TRUE' />";
                            query.ViewFields += "<FieldRef Name='TestUser' Type='User' Nullable='True'/>";
                            query.ViewFields += "<FieldRef Name='PercentComplete' Type='Number' Nullable='TRUE' />";
                            query.ViewFields += "<FieldRef Name='Remarks' />";
                            query.Query = where;
                            DataTable dt = web.GetSiteData(query);
                            //foreach (DataRow row in dt.Rows)
                            //{
                            //    string name = row["Assigned_To"].ToString();
                            //}
                            if (dt.Rows.Count > 0)
                            {
                                gvlist.DataSource = dt;
                                gvlist.DataBind();
                             
                            }
                            else
                            {
                                lblEmpty.Text = "No Records Found";
                            }
                        }
                    }
                });
            }

Progrmatically Exception Handler in Sharepoint

Exception Handler Class in Sharepoint
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PRoject_Name
{
   public class Exception_Handlers
    {
     #region Global Variables

        string strListName = "Exceptions Log";
        string FormsSiteCollUrl = SPContext.Current.Site.Url;

        #endregion

        #region Custom Methods

        /// <summary>
        /// GenerateExceptionLog method, which validate whether "Exception Logs" list exists in site, if exists take list object and log the exception
        /// </summary>
        /// <param name="strTitle">Error Title</param>
        /// <param name="strErrMsg">Error Message</param>
        /// <param name="strDesc">Error Description</param>
        public void GenerateExceptionLog(string strTitle, string strErrMsg, string strDesc)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite osite = new SPSite(FormsSiteCollUrl))
                    {
                        using (SPWeb oWeb = osite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists.TryGetList(strListName);
                            if (oList != null)
                            {
                                AcceptException(oList, strTitle, strErrMsg, strDesc);
                            }
                            else
                            {
                                if (CreateList(oWeb))
                                {
                                    oList = oWeb.Lists.TryGetList(strListName);
                                    AcceptException(oList, strTitle, strErrMsg, strDesc);
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// Creates a new custom list called "Exception Logs" along with fields "ErrorMsg" and "Description"
        /// </summary>
        /// <param name="oWeb">passing web from parent method</param>
        /// <returns>return list creation result (true/false)</returns>
        private bool CreateList(SPWeb oWeb)
        {
            bool rval = false;
            try
            {
                oWeb.AllowUnsafeUpdates = true;
                oWeb.Lists.Add(strListName, "Custom list to save exceptions", SPListTemplateType.GenericList);
                SPList olist = oWeb.Lists.TryGetList(strListName);
                olist.Fields.Add("ErrorMsg", SPFieldType.Note, true);
                olist.Fields.Add("Description", SPFieldType.Note, true);
                SPView view = olist.DefaultView;
                view.ViewFields.Add("ErrorMsg");
                view.ViewFields.Add("Description");
                view.ViewFields.Add("Modified");
                view.Query = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                view.Update();
                olist.Update();
                oWeb.AllowUnsafeUpdates = false;
                rval = true;
            }
            catch (Exception ex)
            {
                rval = false;
            }
            return rval;
        }

        /// <summary>
        /// Update exception details in Exception Logs list
        /// </summary>
        /// <param name="oList">Exception Logs list object</param>
        /// <param name="strTitle">Error Title</param>
        /// <param name="strErrMsg">Error Message</param>
        /// <param name="strDesc">Error Description</param>
        private void AcceptException(SPList oList, string strTitle, string strErrMsg, string strDesc)
        {
            try
            {
                if (oList != null)
                {
                    SPQuery oEmptyQuery = new SPQuery();
                    oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                    SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                    SPListItem oItem = oItemColl.Add();
                    oItem["Title"] = strTitle;
                    oItem["ErrorMsg"] = strErrMsg;
                    oItem["Description"] = strDesc;
                    oList.ParentWeb.AllowUnsafeUpdates = true;
                    oItem.Update();
                    oList.ParentWeb.AllowUnsafeUpdates = false;
                }
            }
            catch (Exception)
            {

            }
        }

        #endregion
    }
}

ascx.csPage
try
            {

                if (!Page.IsPostBack)
                {
                    GridData();
                 
                }
            }
            catch (Exception ex)
            {
                exp_handlers.GenerateExceptionLog("Project Name::PRoject_List_Wp::Page_Load", ex.Message, "Failure");
            }