GSCustomMenuSection

Contents for SharePoint, ReactJS, C#, ASP .Net, JavaScript, JQuery, SQL

Friday, May 27, 2016

Hide default "There are no items to show in this view of the list." message using Jquery


While working with SharePoint's OOTB list view webpart, certain times we come accross a situation where there are no records in that particular view. Requirement wants not to display the OOTB message "There are no items to show in this view of the list. To add a new item, click "New"." to end user. In that scenario you can do following to get rid of OOTB message.


  • Open your webpart page in edit mode.

  • Add a content editor webpart to the page.

  • You can either put below javascript in a file and add its reference/ put the code in content editor webpart



  • < script type="text/javascript"> $(document).ready(function(){ $(".ms-vb").css("display","none"); }); < /script>

    Save the page and there you go. OOTB message is hidden in all webparts in page where there are not items to show.


    Failed to load expression host assembly. Details: Could not load file or assembly


    Failed to load expression host assembly. Details: Could not load file or assembly 'expression_host_f7d608c0ebb24f48bac018b81c6ff665, Version=11.2.30319.1, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Failed to grant permission to execute. (Exception from HRESULT: 0x80131418)



    This error occurs if we are trying to use report viewer and local reports.

    Explanation:
    By design assembly need full trust to read local reports, else they throws above error. Error itself states that "Failed to grant permission to execute." Which means the local rdlc file is not accessible due to permission.

    Resolution:
    You need to provide full trust permissions. To do so, you need to add/update an entry in web.config of your site where report viewer is used.


    < system.web > < trust level="Full" /> < /system.web >

    Wednesday, March 23, 2016

    Export List items to excel

    In this blog we will see how to export a list in excel using server side object model.

    First block we will retrieve all items from the list. This can be done in several ways.
    • You can get all items without filtering any columns. This will consist of all hidden and default columns as well.
    • You can get all items with removing hidden columns
    • You can get specific set of items based on some filter
    Add two references to your visual studio solution
      System.Data.dll & Microsoft.SharePoint.dll
    We will call getListData(siteUrl, listName), this method have two parameters:
      siteurl : this is the site url from which you will fetch data listName : this is list name from which you will fetch data
    
    private void getListData(string siteUrl, string listName)
    {
        DataTable tableForExcel = null;
    
        SPSecurity.RunWithElevatedPrivileges(delegate ()
        {
            using (SPSite objectCurrentSite = new SPSite(SPContext.Current.Site.RootWeb.Url))
            {
                using (SPWeb objectCurrentWeb = objectCurrentSite.OpenWeb())
                {
                    SPList objectList = objectCurrentWeb.Lists.TryGetList(listName);
    
                    SPListItemCollection objectListItemCollection = null;
    
                    if (objectList != null)
                        objectListItemCollection = objectList.GetItems();
    
    
                    if (objectListItemCollection != null && objectListItemCollection.Count > 0)
                    {
                        tableForExcel = new DataTable();
    
                        //Use only one approach of the below two as per your requirement
    
                        //#Approach1
                        //Here all fields will be included in excel including hidden fields
    
                        tableForExcel = objectListItemCollection.GetDataTable();
    
                        //#Approach2
                        //One approach where you can remove hidden fields from displaying in excel
    
                        foreach (SPField objectField in objectListItemCollection[0].Fields)
                        {
                            if (!objectField.Hidden)
                            {
                                tableForExcel.Columns.Add(objectField.Title);
                            }
                        }
    
                        foreach (SPListItem item in objectListItemCollection)
                        {
                            DataRow row = tableForExcel.NewRow();
                            int position = 0;
    
                            foreach (SPField objectField in item.Fields)
                            {
                                if (!objectField.Hidden)
                                {
                                    row[position] = Convert.ToString(item[objectField.Title]);
                                    position++;
                                }
                            }
                            tableForExcel.Rows.Add(row);
                        }
    
                        if (tableForExcel != null)
                            exportToExcel(tableForExcel,"Report");
                    }
                }
            }
        });
    }
    
    We will call exportToExcel(tableForExcel, fileName), this method have two parameters:
      tableForExcel : data table we have created with list data fileName : provide the name for excel which you want
    This will give you a excel file direct download facility.
    
    private static void exportToExcel(DataTable tableForExcel, string fileName)
    {
        if (tableForExcel != null)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";
    
            System.Web.HttpContext.Current.Response.ClearContent();
    
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    
            string tab = "";
    
            //Adding column header in excel 
    
            foreach (DataColumn dataColumn in tableForExcel.Columns)
            {
                System.Web.HttpContext.Current.Response.Write(tab + dataColumn.ColumnName);
    
                tab = "\t";
            }
    
            System.Web.HttpContext.Current.Response.Write("\n");
    
            int i;
    
            foreach (DataRow dr in tableForExcel.Rows)
            {
                tab = "";
    
                for (i = 0; i < tableForExcel.Columns.Count; i++)
                {
                    System.Web.HttpContext.Current.Response.Write(tab + dr[i].ToString());
    
                    tab = "\t";
                }
    
                System.Web.HttpContext.Current.Response.Write("\n");
            }
    
            System.Web.HttpContext.Current.Response.End();
    
            System.Web.HttpContext.Current.Response.Redirect(SPContext.Current.Web.Url.ToString());
        }
        else
        {
            //Your code here
        }
    }
    

    Wednesday, March 16, 2016

    Retrieve items from list using JSOM


    This blog demonstrates how to connect to a list and retrieve specific items based on filter/query using JSOM.

    <script>
        var ListItem;
    
        function getTheList(employee) {
    
            clientContext = new SP.ClientContext.get_current();
    
            //get web object from current context
            var web = clientContext.get_web();
    
            //Provide list name and fetch the list
            var myList = web.get_lists().getByTitle('LIST_NAME');
    
            //write a query to fetch records based on filter
            var query = new SP.CamlQuery();
            query.set_viewXml('<View><Query><Where><Eq><FieldRef Name="EmployeeName"/>
                <Value Type="Text">' + employee + '</Value></Eq></Where></Query></View>');      
    
            //fetch list items based on query formed in above statement
            ListItem = myList.getItems(query); 
    
            //Load the object
            clientContext.load(ListItem,'Include(EmployeeName)'); 
    
            //Final step to execute the query to get details for loaded objects
            clientContext.executeQueryAsync(Function.createDelegate(this, this.mySuccessFunction),
                 Function.createDelegate(this, this.myFailFunction));
    
            return false;
        }
    
        //This method will be called on success of executeQueryAsync
        function mySuccessFunction(sender, args) 
        {    
            var listItemEnumerator = ListItem.getEnumerator();
            while (listItemEnumerator.moveNext())
            {
                  var item = listItemEnumerator.get_current();
                      
                  var employee = item.get_item('EmployeeName');
                  //Your code goes here..
            }
        }
    
        //This method will be called on failure or on any exception thrown in executeQueryAsync
        function myFailFunction(sender, args) 
        { 
            alert(args.get_message() + "\n" + args.get_stackTrace()); 
        }
    
    </script>
    

    Retrieve custom fields only from list using CSOM


    This blog demonstrates how to retrieve/print only custom fields (user created) from a list using CSOM.

    Add two references to your visual studio solution
    Microsoft.SharePoint.Client.dll &
    Microsoft.SharePoint.Client.Runtime.dll

    
    string siteURL = "http://server/sites/site";
    ClientContext context = new ClientContext(siteURL);
    Web oWebSite = context.Web;
    
    context.Load(oWebSite);
    context.ExecuteQuery();
    
    //Get the list by title
    List employeeList = oWebSite.Lists.GetByTitle("Employee");
    CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml = "";
    ListItemCollection listItems = employeeList.GetItems(camlQuery);
    
    context.Load(employeeList);
    context.Load(listItems);
    context.Load(employeeList.Fields);
    context.ExecuteQuery();
    
    foreach(Field field in employeeList.Fields)
    {
        if(!field.FromBaseType)
             Console.WriteLine("{0} - {1} - {2}",field.Title, field.InternalName, field.Hidden);
    }
    

    Monday, March 14, 2016

    Delete specific file from attachment of a list item programatically

    Consider you have a listitem with multiple files added as attachments. Now you need to delete a specific file from those attachments programmatically,
    follow below steps:

    
          public static void DeleteAttachment(int itemId, string fileName)  
          {   
              using (SPSite site = new SPSite("http://server/sites/sitename"))  
              {  
                  using (SPWeb web = site.OpenWeb())  
                  {  
                      SPListItem listItem = web.Lists.TryGetList("Employees").GetItemById(itemId);  
     
                      List fileNames = new List();  
                      
                      if(listItem.Attachments.Count > 0){
                          //Store all file names from attachment collection
                          foreach (string fileName in listItem.Attachments){  
                               fileNames.Add(fileName);  
                          }  
                      }
    
                      if(fileNames.Count > 0 && fileNames.Contains(filename)){  
                          listItem.Attachments.Delete(fileName);                        
                      }  
                       
                      listItem.update();
                  }   
              }                     
          } 
    

    Now make a call to the method
    
          int itemID = 10;
          string filename = "address.docx";
          
          DeleteAttachment(itemId, fileName);