Friday, August 21, 2009

How to exclude fields from SharePoint ListFieldIterator Control

Here I am going to share with you a very small things but I think it’s very helpful. SharePoint Web Controls provides set of controls which we can use for generating our custom pages very easily without writing much custom code, there is control called “ListFieldIterator”, in which we need to specify which SharePoint List we are going to bind with controls and it will generate all controls related to SharePoint List.

In ListFieldIterator control if we want to exclude some fields from generated control, then we can use ListFieldIterator.ExcludeFields property, but when we have multiple fields for exclusion then we need to separate the fields with a semicolon and pound sign ";#" as separator, for single field we are using "." as separator.

SharePoint Web Controls rocks !!!

Thursday, August 13, 2009

SharePoint Master Pages and Branding

Today I’ll talk about master pages and branding fundamentals into SharePoint :)

Every WSS 3.0 site is provisioned with a special Master Page gallery which contains a master page template known as default.master. This file is deployed in the 12-hive under 12\TEMPLATE\GLOBAL. Each new WSS site provides an instance of default.master. It is possible to customize default.master, but if you do, it becomes unghosted and this can affect efficiently and scalability.

The default.master page contains controls (including links, menus, icons and navigation components), named placeholders, and delegate controls. Named placeholders are used to add unique contents to a page template of page instance that is linked to a master page. Delegate Controls provide a way to substitute elements into the master page layout that affect every site. Delegate Controls are changed via activating features; therefore modifications to delegate controls require no changes to the default.master or site pages that are linked to default.master.

WSS provides several standard controls to support navigation including the SiteMapPath control which populates a breadcrumb navigation menu to allow users to navigate from the current site upwards to the top-level site of current site collection. Navigation is based on the infrastructure provided by ASP.NET 2.0.

You can also create a custom master page template. To do this you must create the master page template itself, and then create a feature that provisions an instance of this master page in the Master Page gallery for a specific site. Finally you need to redirect site pages to use your custom master page instead of using default.master.

You can customized the look and feel of a site (brand it) by using Cascading Style Sheets.You can find standard language specific CSS files in \TEMPLATE\LAYOUTS\1033\STYLES.The primary file is called core.css. This file is scoped at farm level, so it is not a good idea to change it. Instead one way to change the look and feel is to use Themes which are found in TEMPLATE\THEMES.or we can create a custom.css file and put into TEMPLATE\LAYOUTS\1033\STYLES\<your folder>.Brand images are located in TEMPLATE\IMAGES

Keep writing!! 

Sunday, August 9, 2009

Sharepoint Page Types - Application and Site Pages

Hello Friends

SharePoint allows page ghosting, the ability to store a single copy of a page as a page template (on the file system). From which it creates page instances. Top level pages that are identical for many web applications are handled as ghostable pages, however once a page is customized, it becomes unghosted. The purpose of page ghosting is to improve efficiency and scalability. The idea is that if 100 websites need the same default.aspx page, then that page is handled very efficiently via page ghosting. Ghosted pages are compiled into a DLL which is kept in memory.

Since customized pages are numerous, it would take too much memory to compile each of them into a DLL and store them all in memory. SharePoint provides a mechanism that allows customized .aspx pages to be stored in the context database. For this to work SharePoint must be able to find the page in SQL instead of on the local drive. SharePoint provides SPVirtualPathProvider a class that abstracts the Page Parse. This class decides whether a page is ghosted or unghosted. Unghosted page must be individually parsed and loaded into memory.

SharePoint websites contain some special virtual directories: _layouts, _vti_bin, and _wpresources which are used by the WSS runtime. The physical location of these virtual directories is under web server extensions.

SharePoint supports application pages and site pages. Application pages can not be customized. They perform better and can contain inline code. You can create new application pages and integrate them into menus using CustomActions.xml elements. An application page is typically used in many websites. A good example of application page would be settings page which administrators can find in the Site Actions menu.

Application pages are deployed in the <12 hive>\TEMPLATES\LAYOUTS folder. Application pages are scoped at the farm level. They are used to provide much standard functionality for provisioning and administering sites.

Site pages can be customized and are unghosted. Although they must be retrieved from the content database, parsed, and then loaded into memory, unlike DLLs, they can be unloaded from memory too. Possibly this makes websites with a large number of pages because memory is freed up when pages are no longer needed.

The SPFile class is used to read and write to the contents of a site page. The SPFolder class supports a hierarchy of site pages.

Disha Shah

Saturday, August 8, 2009

How to attach/delete/upload files to SharePoint List Item using Object Model

Hello Friends

I have one requirement in which I need to develop a web part in which users can upload multiple documents to SharePoint List Item and they can see all uploaded files into data grid control, they also need facility for user to delete selected files, add new files from same control and also they can download files.

Here in this post, I am writing code for each functionality as per my requirements.

Snippet code of deleting attachment from SharePoint list item :

private void DeleteAttachment(int NodeID, String strFileName)
    {
        try
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;

            SPListItem delItem = lstAudit.GetItemById(NodeID);
            SPAttachmentCollection atCol = delItem.Attachments;
            foreach (string strDelfileName in atCol)
            {
                if (strDelfileName == strFileName)
                {
                    atCol.Delete(strDelfileName);
                    delItem.Update();
                    lstAudit.Update();

                    return;
                }
            }

        }
        catch (Exception eDel)
        {
            string errDel = eDel.Message;
        }
    }
   

Snippet code for downloading attachment from SharePoint List Item :

 private void DownloadAttachment(string FileName)
    {
        try
        {
            string AttachmentURL = string.Empty;
            AttachmentURL = FileName;
            string strName = AttachmentURL.Substring(AttachmentURL.LastIndexOf("/") + 1);
            string sbURL = AttachmentURL.Trim();
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            Response.AppendHeader("Content-disposition", "attachment; filename=" + strName);
            Response.AppendHeader("Pragma", "cache");
            Response.AppendHeader("Cache-control", "private");
            Response.WriteFile(sbURL);
            Response.End();
        }
        catch (Exception eDwn)
        {
            Response.Write(eDwn.Message);
        }
    }

Snippet code of uploading document to SharePoint List Item :

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName = "";
            string strExtensionName = "";

            fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);

            if (fileName != "")
            {
                strExtensionName = fileName.Substring(fileName.IndexOf(".") + 1);
                if (strExtensionName.Equals("webpart") || strExtensionName.Equals("dll") || strExtensionName.Equals("bat") || strExtensionName.Equals("exe"))
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "Invalid fileName!!";
                }
                else
                {
                    string _fileTime = DateTime.Now.ToFileTime().ToString();

                    string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);

                    if (txtFileName.Text.Trim().Length > 0)
                    {
                        fileName = fileName.Replace(fileName.Substring(fileName.LastIndexOf("\\") + 1), txtFileName.Text) + "." + strExtensionName;
                    }
                    string _newfilePath = _fileTime + "~" + fileName;

                    string tempFolder = Environment.GetEnvironmentVariable("TEMP");

                   
                    string _filepath = tempFolder + _newfilePath;
                   
                    FileUpload.PostedFile.SaveAs(_filepath);

                    AddRow(fileName, _filepath, 0, true);
                }
            }
            else
            {

                lblMessage.Visible = true;
                lblMessage.Text = "Please Selct file Name";

            }

        }
        catch (Exception Ex)
        {
            Response.Write(Ex.Message);
        }

    }

   
    protected void dgdUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int recordToDelete = e.RowIndex;

        //dt = (DataTable)Page.Session["Files"];
        dt = (DataTable)ViewState["Files"];

        int cn = dt.Rows.Count;

        if (Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]) != 0)
        {
            DeleteAttachment(Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]), dt.Rows[recordToDelete].ItemArray[1].ToString());
        }

        dt.Rows.RemoveAt(recordToDelete);

        dt.AcceptChanges();
        //Page.Session["Files"] = dt;
        ViewState["Files"] = dt;
        dgdUpload.DataSource = dt;
        dgdUpload.DataBind();
    }
    private void AddMoreColumns()
    {

        dt = new DataTable("Files");

        dc = new DataColumn("ID", Type.GetType("System.Int16"));
        dt.Columns.Add(dc);

        dc = new DataColumn("FileName", Type.GetType("System.String"));
        dt.Columns.Add(dc);

        dc = new DataColumn("FilePath", Type.GetType("System.String"));
        dt.Columns.Add(dc);

        //Page.Session["Files"] = dt;
        ViewState["Files"] = dt;

    }
    private void AddRow(string file, string path, int ID, Boolean bolCheckForfiles)
    {

        Boolean bolAddRow = true;
        //dt = (DataTable)Page.Session["Files"];
        dt = (DataTable)ViewState["Files"];
       
        if (dt == null)
        {
            AddMoreColumns();

        }
        if (bolCheckForfiles)
        {
       
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow drExistingrow in dt.Rows)
                {

                    if (drExistingrow["FileName"].ToString() == file)
                    {
                        bolAddRow = false;
                    }
                }
            }
        }
        if (bolAddRow)
        {

            dr = dt.NewRow();

 

            dr["ID"] = ID;
            dr["FileName"] = file;
            dr["FilePath"] = path;

 

            dt.Rows.Add(dr);

            //Page.Session["Files"] = dt;
            ViewState["Files"] = dt;

            dgdUpload.DataSource = dt;

            dgdUpload.DataBind();//bind in grid

        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Same File Name already exists!!!";
        }
    }

   
   

    protected void dgdUpload_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "View")
        {
            string file = e.CommandArgument.ToString();
            DownloadAttachment(file);

        }
    }

 

        if (dt != null)
        {

            int _dtcnt = dt.Rows.Count;
            foreach (DataRow dr in dt.Rows)
            {

                Boolean bolAddAttachment = true;
                fileName = dr["FileName"].ToString();
                if (itmCorrectiveActionFinding.Attachments.Count > 0)
                {
                    foreach (string strAttachedname in itmCorrectiveActionFinding.Attachments)
                    {

                        if (fileName == strAttachedname)
                        {
                            bolAddAttachment = false;

                        }
                    }
                }
                if (bolAddAttachment)
                {
                    string strFilepath = dr["FilePath"].ToString();

                    StreamReader sr = new StreamReader(strFilepath);

                    Stream fStream = sr.BaseStream;

                    contents = new byte[fStream.Length];

                    fStream.Read(contents, 0, (int)fStream.Length);

                    fStream.Close();

                    itmCorrectiveActionFinding.Attachments.Add(fileName, contents);

                    itmCorrectiveActionFinding.Update();
                    lstCorrectiveActionFinding.Update();
                    SPContext.Current.Web.Update();
                    System.IO.File.Delete(strFilepath);

                }
            }
        }

How to Integrate AJAX with Publishing SharePoint Site Templates

Hello Friends, 

When I have enabled AJAX with SharePoint into my site, I need to do lots of configuration changes into my site related to adding some new sections into web.config file, etc. 

This link is very useful; it’s giving us step by step instruction for how to integrate AJAX with SharePoint site.  

http://sharepoint.microsoft.com/blogs/mike/Lists/Posts/Post.aspx?ID=3 

But I have figured out that we need to make some more changes into master page in which we have publishing SharePoint site templates, Collaborate SharePoint site template

We need to open master page of Collaboration Site Template and need to add below lines. 

<BODY scroll=”yes”>

  <form runat=”server”>

 <WebPartPages:SPWebPartManager runat=”Server”/>

 <asp:ScriptManager runat=”server”></asp:ScriptManager> 

Hope it will help to someone! 

Thanks and Enjoy!!!

How to display detailed error messages into SharePoint page

It happens most of time with everyone when they are working with SharePoint and gets error message is “An unexpected error occurred”, that’s very boring and frustrated error message into SharePoint page, which leaves a number of guesses and questions. 

If you would like to know what exact error description is, then we need to make following changes into our SharePoint web application web.config file. 

1> CallStack=”false” changed to CallStack=”true” 

2> <customErrors mode=”On” /> changed to <customErrors mode=”Off” /> 

Happy debugging :)