August 13, 2012

Filtering in Sp gridview


#region Sorting
        protected void grdAnnDetails_Sorting(object sender, GridViewSortEventArgs e)
        {
            hidecontrl();                                 

            DataTable dt = Session["All"] as DataTable;
            if (dt != null)
            {
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            }

        }
        #endregion
        #region SortDirection
        private string GetSortDirection(string column)
        {
            string sortDirection = "ASC";
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
        #endregion
        #region Filtering
        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                hidecontrl();
                buildFilterView(ObjD.FilterExpression);
            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }

        void buildFilterView(string filterExp)
        {
            string lastExp = filterExp;
            if (lastExp.Contains("AND"))
            {
                if (lastExp.Length < lastExp.LastIndexOf("AND") + 4)
                { lastExp = lastExp.Substring(lastExp.LastIndexOf("AND") + 4); }
                else
                { lastExp = string.Empty; }
            }

            //update the filter
            if (!string.IsNullOrEmpty(lastExp))
            { FilterExpression = lastExp; }

            //reset object dataset filter
            if (!string.IsNullOrEmpty(FilterExpression))
            { ObjD.FilterExpression = FilterExpression; }
        }



        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            if (Context.Request.Form["__EVENTARGUMENT"] != null &&
                 Context.Request.Form["__EVENTARGUMENT"].Contains("__ClearFilter__"))
            {
                ViewState.Remove("FilterExpression");
            }
        }

        string FilterExpression
        {
            get
            {
                if (ViewState["FilterExpression"] == null)
                { ViewState["FilterExpression"] = ""; }

                return (string)ViewState["FilterExpression"];
            }
            set
            {
                string thisFilterExpression = "(" + value.ToString() + ")";
                List<string> fullFilterExpression = new List<string>();

                if (ViewState["FilterExpression"] != null)
                {
                    string[] fullFilterExp = ViewState["FilterExpression"].ToString().Split(_ssep, StringSplitOptions.RemoveEmptyEntries);
                    fullFilterExpression.AddRange(fullFilterExp);

                    int index = fullFilterExpression.FindIndex(s => s.Contains(thisFilterExpression));
                    if (index == -1)
                    { fullFilterExpression.Add(thisFilterExpression); }
                }
                else
                {
                    fullFilterExpression.Add(thisFilterExpression);
                }
                string filterExp = string.Empty;
                fullFilterExpression.ForEach(s => filterExp += s + " AND ");
                filterExp = filterExp.Remove(filterExp.LastIndexOf(" AND "));
                if (!filterExp.EndsWith("))") && filterExp.Contains("AND"))
                { filterExp = "(" + filterExp + ")"; }
                ViewState["FilterExpression"] = filterExp;
            }
        }
        public void AssignData()
        {

            ObjD = new ObjectDataSource();
            ObjD.ID = "gridds";
            ObjD.SelectMethod = "GetData";
            ObjD.FilterExpression = FilterExpression;
            ObjD.TypeName = this.GetType().AssemblyQualifiedName;
            ObjD.ObjectCreating += new ObjectDataSourceObjectEventHandler(ObjD_ObjectCreating);
            this.Controls.Add(ObjD);
            grdAnnouAll.DataSourceID = ObjD.ID;          
            ObjD.Filtering += new ObjectDataSourceFilteringEventHandler(ObjD_Filtering);          
        }


        public DataTable GetData()
        {
            DataTable dt = new DataTable();

            if (ViewState["Dboard"] == null)
            {
               
                if (!string.IsNullOrEmpty(Request.QueryString["Annmoreid"]))
                {
                    if (!string.IsNullOrEmpty(EncryptHelper.DecryptText(Request.QueryString["Annmoreid "])))
                    {

                        AnnouncementBL obj = new AnnouncementBL(Convert.ToInt32((EncryptHelper.DecryptText(Request.QueryString["Annmoreid "]))));

                        if (IsSuperAdmin || IsAdmin || IsManager)
                        {
                            ViewState["Dboard"] = obj.GetAllItems();

                        }
                        else
                        {

                            ViewState["Dboard"] = obj.GetDispalyedListItem();

                        }
                    }
                    else
                    {
                        Response.Redirect("/Pages/Hme.aspx", false);
                    }

                }
                else
                {
                    AnnouncementBL allobj = new AnnouncementBL();
                    ViewState["Dboard"] = allobj.GetAllListItem();
                }
            }           
           
             dt = (DataTable)ViewState["Dboard"];
            return dt;        


        }


        void ObjD_Filtering(object sender, ObjectDataSourceFilteringEventArgs e)
        {
            ViewState["FilterExpression"] = ((ObjectDataSourceView)sender).FilterExpression;
        }

        void ObjD_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = this;
        }




        #endregion
 Assigndata should be called in Pageload

Paging in SP Gridview




        protected void grd_ClickNext(Object sender, EventArgs e)
        {
            try
            {
                grd.DataSourceID = ObjD.ID;

            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
        protected void grd_ClickPrevious(Object sender, EventArgs e)
        {
            try
            {
                grd.DataSourceID = ObjD.ID;

            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
        protected void grd_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grd.PageIndex = e.NewPageIndex;


            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
      

Server side script for Hiding controls




 public void hidecontrl()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\">\n");
            sb.Append("Sys.Application.add_load(hidebtn);\n");
            sb.Append("function hidebtn() {\n");
            sb.Append("$('input:imagebutton[id$=imgbtnAnnouncEdit]').hide();\n");
            sb.Append("$('input:imagebutton[id$=imgbtnAnnouncDelete]').hide();}\n");
            sb.Append("</script>\n");
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sb.ToString());      
        }
      

call hidecontrl(); in whichever function you need.

August 08, 2012

How to point the domain for Creating a site in the Production server

Step 1:Central Admin->Application Management àWeb application->Configure alternate Access mappings


Step 2: Configure alternate accsess Mapping->

Step 3:
Add Internal Url and choose custom in Zone for the url mentioned below.
Step 4:
Add Internal Url and choose Internet in Zone for the following url mentioned below.
Step 5:RunàInetmgr->Sites àRight click the site ->Bindings
Step 6:Add the host name in the binding
Step 7:Add the host name in the binding for the url shown  below
Step8:After adding the sites to IIS .It will look as shown below
 




Step 9:Reset IIS


July 21, 2012

Creation of webpart page and content editor webpart programatically in sharepoint 2010

 DynamicDL
 public static bool insert(PropellerStudioBL propellerStudioBL)
        {

            bool insert = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (MysiteDataContext context = new MysiteDataContext(SiteHelper.SiteUrl))
                {

                    PropellerItem propellerStudioItem = new PropellerItem()

                    {

                     Title  = propellerStudioBL.Propellertitle,
                     

                    };
                    context.Propeller.InsertOnSubmit(propellerStudioItem);
                    context.SubmitChanges();

                    if (propellerStudioItem.Id > 0)
                    {
                        insert = true;
                        if (propellerStudioBL.Title != null && propellerStudioBL.Title != string.Empty)
                        {
                           
                        }
                        else
                        {
                            insert = true;
                        }
                    }
                }
            });
            return insert;
        }
     public static System.Data.DataTable GetPropellerData(PropellerStudioBL propellerStudioBL)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Url");
            DataRow row;
            SPSite spsite;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {


                using (VCSBINTRANETDataContext context = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {

                    var quer = from propellerda in context.PropellerStudio
                               orderby propellerda.Id descending
                               select propellerda;

                    if (quer != null)
                    {
                        foreach (PropellerStudioItem item in quer.Take(3))
                        {
                            row = dt.Rows.Add();
                            row["Title"] = Convert.ToString(item.Title);
                            row["Url"] = Convert.ToString(SPContext.Current.Web.Url + "/pages/" + item.Title + ".aspx");
                        }
                    }
                }
            });
            return dt;
        }

Gridview

           <asp:GridView ID="grdPropeller"  Width="100%" runat="server" BorderStyle="None" 
               AutoGenerateColumns="False" GridLines="None" EmptyDataText="There are no items to show in this view."
               ShowHeader="False">
               <Columns>
           
                   <asp:TemplateField>
                       <ItemStyle Width="350px" />
                       <ItemTemplate>
                           <asp:HyperLink ID="HypTitle" NavigateUrl='<%# Eval("Url") %>' runat="server">
                           <%# Eval("Title")%>                                              
                     
                       <br />
                          </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
      
 
 Function to add A contenteditorwebpart dynamically

protected void createcontenteditorwebpart(string pagename)
        {
            SPSite site = SPContext.Current.Site;
                using (SPWeb web = site.OpenWeb())
                {
                            

                    SPList list = web.Lists["Pages"];
                    string postInformation =

                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +

                      "<Method>" +

                        "<SetList Scope=\"Request\">" + list.ID + "</SetList>" +

                        "<SetVar Name=\"ID\">New</SetVar>" +

                        "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +

                        "<SetVar Name=\"Type\">WebPartPage</SetVar>" +

                        "<SetVar Name=\"WebPartPageTemplate\">1</SetVar>" +

                        "<SetVar Name=\"Title\">" + pagename + "</SetVar>" +

                        "<SetVar Name=\"Overwrite\">true</SetVar>" +

                      "</Method>";
                    string processBatch = web.ProcessBatchData(postInformation);
                    web.Update();
           
                }
               
          
        }
Function to creat A webpartPage 
 public void Createwebpartpage(string title)
        {
          
            createcontenteditorwebpart(title);
            SPFile page = SPContext.Current.Web.GetFile("/Pages/" + title + ".aspx");
            using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                XmlElement p = new XmlDocument().CreateElement("p");
                p.InnerText = "Edit this webpart to add content on this Page";
              

                ContentEditorWebPart cewp = new ContentEditorWebPart
                {
                    Content = p
                };
                wpmgr.AddWebPart(cewp, "Header", 0);
            }
            page.Update();
         

        }
Note:
1.Call  Createwebpartpage(txtPropellerTitle.Text);function in submit button.
2.Add Microsoft.sharepoint.publishing dll in reference

Sample for creating a a Article page programatically
 public void createuserwiki(string title)
        {
            SPWeb spweb = SPContext.Current.Web;

            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(spweb);
            string pageName = title + ".aspx";

            PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();
            PageLayout currPageLayout = pageLayouts[9];
            PublishingPageCollection pages = publishingWeb.GetPublishingPages();
          
           PublishingPage newPage = pages.Add(pageName, currPageLayout);

            newPage.ListItem[FieldId.PublishingPageContent] = "";
            newPage.ListItem[FieldId.RollupImage] = "";
            newPage.ListItem[FieldId.Title] = "";

            newPage.ListItem.Update();
            newPage.Update();
            newPage.CheckIn("This is just a comment");
            SPFile page = SPContext.Current.Web.GetFile("/Pages/" + title + ".aspx");
            using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                XmlElement p = new XmlDocument().CreateElement("p");
                p.InnerText = "Edit this webpart to add content on this Page";
                // page.DeleteProperty(pageLayouts[0]);

                ContentEditorWebPart cewp = new ContentEditorWebPart
                {
                    Content = p
                };
                wpmgr.AddWebPart(cewp, "Header", 0);





            }