Search This Blog

Monday, September 21, 2015

How to pass data from one webpart to another webpart in sharepoint ?


In certain situation we need to pass data from webpart to another webpart present in the same site. To implement the connection functionality between WebParts, we should create an Interface .This interface will be implemented by both the provider and consumer classes.

Then we will use the ConnectionProvider and ConnectionConsumer attribute to make the connection between the two webpart.

EXAMPLE:

1.  Interface :  
  
    public interface Test
    {
        string Name { get; set; }
    }


2. The provider class :

    public class Provider : WebPart, Test
    {
        TextBox tb = new TextBox();
        Button btn = new Button();
        string _Name = "";

        public string Name
        {
            get{return _Name;}
            set{_Name = value;}
        }       
        
        protected override void CreateChildControls()
        {
            btn.Text = "Show";
            btn.Click += new EventHandler(btn_Click);
            tb.Text = "Prem";
            Name = tb.Text;
            this.Controls.Add(tb);
            this.Controls.Add(btn);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            EnsureChildControls();
            RenderChildren(writer);
  
        }
        void btn_Click(object sender, EventArgs e)
        {
            Name = tb.Text;
        }
      
        [ConnectionProvider("Test Provider")]
        public Test ProvideCommunication()
        {
            return this as Test;
        }  
      }

3.The consumer class:

     public class Consumer : WebPart
    {
        private Test providerWebPart;

        [ConnectionConsumer("Test Consumer")]
        public void ReceiveName(Test  provider)
        {
            providerWebPart = provider; 
        }
        protected override void Render(HtmlTextWriter writer)
        { 
            if (providerWebPart != null)
                writer.Write("Value provided is : " + providerWebPart.Name);
            base.Render(writer); 
        }
    }

When the button is clicked the value for  the Name is set. Then the current instance of the interface is pass to consumer webpart. The ReceiveName Method will  act as a receiver of the Test interface.

Source:http://www.mindfiresolutions.com/How-to-pass-data-from-one-webpart-to-another-webpart-in-sharepoint--798.php

Friday, September 11, 2015

How to Filter DataView WebPart (DVWP) from Query String

Assuming you already have a working data view webpart:

  1. Open SharePoint designer and the page that the data view web part exists on

  2. From the Options tab of the Data View Tools section in the ribbon, select Parameters 

  3. Create a new parameter of type Query String - specifiy the parameter name, the query string variable name (what its called in the URL), and the default value (for when no value is supplied)


  4. From the Options tab of the Data View Tools section in the ribbon, select Filters

  5. Set up the filter to use your parameter (QueryParameter will be the parameter name you supplied)

  6. If you have problems with the steps above, I'll add that I always start with an empty data view web part and then manually add the data source and columns to it through the menus and XSLT. I find that this route tends causes me less trouble than adding a data view web part with the data source directly attached

How to take document icons from SharePoint 2013

        protected void grdDocuments_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataRowView dr = e.Row.DataItem as DataRowView;
                    string iconUrl = DocumentBL.GetIconUrl(dr["File_x0020_Type"].ToString());
                    string docurl = "/" + dr["FileRef"].ToString().Split('#')[1];

                    Image iconImg = e.Row.FindControl("iconImage") as Image;
                    HtmlAnchor aImage = (HtmlAnchor)e.Row.FindControl("aIconImage");

                    if (iconImg != null)
                    {
                        iconImg.ImageUrl = iconUrl;
                        aImage.HRef = docurl;
                    }

                    e.Row.Cells[3].Text = Convert.ToDateTime(dr["Modified"]).Date.ToString("yyyy-MM- dd");
                }
            }
            catch (Exception ex)
            {
             
                throw;
            }
        }

        public static string GetIconUrl(string icon)
        {
            SPWeb web= SPContext.Current.Web;
            string docIcon = SPUtility.MapToIcon(web, icon, string.Empty, IconSize.Size16);
            return string.Format("{0}/_layouts/images/{1}", web.Url, docIcon);
        }

List of common SharePoint 2013 Result Source IDs

Although the new Result Source feature in SharePoint 2013 is really cool, writing queries against them is not.  With scopes you could specify them by name (i.e.: All Sites or People).  However with result sources, you must specify the id not the name.  This cane make it tricky to develop custom coded solutions.  Luckily, it turns out that the IDs of the built-in result sources are all the same (at least they appear to be) with the exception of the Conversations result source.  In comparing an on-premises installation of SharePoint 2013 with a SharePoint Online Preview tenant, here is the list I came up with.  Hopefully, it will save you some time when you need to write a query.

Result SourceID
Documentse7ec8cee-ded8-43c9-beb5-436b54b31e84
Items matching a content type5dc9f503-801e-4ced-8a2c-5d1237132419
Items matching a tage1327b9c-2b8c-4b23-99c9-3730cb29c3f7
Items related to current user48fec42e-4a92-48ce-8363-c2703a40e67d
Items with same keyword as this item5c069288-1d17-454a-8ac6-9c642a065f48
Local People Resultsb09a7990-05ea-4af9-81ef-edfab16c4e31
Local Reports And Data Results203fba36-2763-4060-9931-911ac8c0583b
Local SharePoint Results8413cd39-2156-4e00-b54d-11efd9abdb89
Local Video Results78b793ce-7956-4669-aa3b-451fc5defebf
Pages5e34578e-4d08-4edc-8bf3-002acf3cdbcc
Pictures38403c8c-3975-41a8-826e-717f2d41568a
Popular97c71db1-58ce-4891-8b64-585bc2326c12
Recently changed itemsba63bbae-fa9c-42c0-b027-9a878f16557c
Recommended Itemsec675252-14fa-4fbe-84dd-8d098ed74181
Wiki9479bf85-e257-4318-b5a8-81a180f5faa1
Of course this doesn’t help you much for your own custom result sources, but at least you should be able to work with this list for anything built-in.  This is especially useful if you want to write queries to do people search or get popular items.

Source:http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2013/01/04/list-of-common-sharepoint-2013-result-source-ids.aspx

Method to Convert Generic List to Datatable

        public static DataTable BuildDataTable<T>(IList<T> lst)
        {
            //create DataTable Structure
            DataTable tbl = CreateTable<T>();
            Type entType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
            //get the list item and add into the list
            foreach (T item in lst)
            {
                DataRow row = tbl.NewRow();
                foreach (PropertyDescriptor prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                }
                tbl.Rows.Add(row);
            }
            return tbl;
         }

        private static DataTable CreateTable<T>()
        {
            //T –> ClassName
            Type entType = typeof(T);
            //set the datatable name as class name
            DataTable tbl = new DataTable(entType.Name);
            //get the property list
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
            foreach (PropertyDescriptor prop in properties)
            {
                //add property as column
                //tbl.Columns.Add(prop.Name, prop.PropertyType);
                tbl.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
            prop.PropertyType) ?? prop.PropertyType);
            }
            return tbl;
        }

Creating Visual Web Part Properties

[ToolboxItemAttribute(false)]
public class Sample_Web_Part : WebPart
{
 
    protected override void CreateChildControls()
    {
     
    }

    public static Boolean SampleBoolean;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Boolean"),
    WebDescription("Please Choose a Sample Boolean")]
    public Boolean _SampleBoolean
    {
        get { return SampleBoolean; }
        set { SampleBoolean = value; }
    }

    public static string SampleText;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Text"),
    WebDescription("Please Enter a Sample Text")]
    public string _SampleText
    {
        get { return SampleText; }
        set
        {
            // Sample Validation
            Regex oRegEx = new Regex("[a-zA-Z]+");
            if (!oRegEx.IsMatch(value))
                throw new Microsoft.SharePoint.WebPartPages.
                    WebPartPageUserException(
                    "Please enter alphabeth characters only");
            SampleText = value;
        }
    }

    public static int SampleNumber;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Number"),
    WebDescription("Please Enter a Sample Number")]
    public int _SampleNumber
    {
        get { return SampleNumber; }
        set { SampleNumber = value; }
    }

    public static DateTime SampleDate;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Date"),
    WebDescription("Please Enter a Sample Date")]
    public DateTime _SampleDate
    {
        get { return SampleDate; }
        set { SampleDate = value; }
    }

    public enum CityEnum { Mumbai,Aukland, Londan,Sydney };
    public static CityEnum SampleDropDown;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Drop Down"),
    WebDescription("Please Choose a Sample DropDown")]
    public CityEnum _SampleDropDown
    {
        get { return SampleDropDown; }
        set { SampleDropDown = value; }
    }
}

Thursday, September 10, 2015

ThreadAbortException

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead ofResponse.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:

  Response.Redirect ("nextpage.aspx", false);
      
If you use this workaround, the code that follows Response.Redirect is executed.

For Server.Transfer, use the Server.Execute method instead.