Thursday, June 20, 2013

Get Site Collection Owners / Administrators report with storage in MB's export to .CSV Programatically.

Get Site Collection Owners / Administrators report with site storage  in MB's export to CSV Programatically.


            SPSecurity.RunWithElevatedPrivileges(delegate
             {
                 try
                 {
                     string siteUrl = string.Empty;
                      
                    StreamWriter SW;
                    SW = File.AppendText("c:\\SiteCollAdminList_Usage.csv");
                    SW.WriteLine("Site Url, Site Storage (MB), Adnin Name, E-Mail");
                   

                    String ConfigValues = ConfigurationSettings.AppSettings["WebAppsName"];

                    String[] ObjWebapps = ConfigValues.Split('|');
                    foreach (String WebappsName in ObjWebapps)
                    {
                        SPWebApplication webapp = SPWebApplication.Lookup(new Uri(WebappsName));
                        foreach (SPSite siteCol in webapp.Sites)
                        {
                            siteUrl = siteCol.Url;
                            SPSite site = new SPSite(siteUrl);
                            SPWeb web = site.OpenWeb();

                            FullControlUsers = new StringBuilder();
                            foreach (SPRoleAssignment roleAssignment in web.RoleAssignments)
                            {
                                if (roleAssignment.Member is SPUser)
                                {
                                    foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                                    {
                                        if (roleDefinition.Name.Equals("Full Control"))
                                        {
                                            if (roleAssignment.Member.LoginName != null)
                                            {
                                                if (roleAssignment.Member.LoginName.Contains('#') || roleAssignment.Member.LoginName.Contains('.'))
                                                {
                                                    String ObjSplitUsers = roleAssignment.Member.Name.ToString();
                                                    //FullControlUsers.Append(ObjSplitUsers + ";");
                                                  
                                                    SW.WriteLine(siteUrl.Replace(",", " ") + "," + site.Usage.Storage / (1024 * 1024) + "," + ObjSplitUsers + "," + roleAssignment.Member.LoginName);
                                                }
                                                else
                                                {
                                                    String ObjSplitUsers = roleAssignment.Member.Name.ToString();
                                                    //FullControlUsers.Append(ObjSplitUsers + ";");
                                                  
                                                    SW.WriteLine(siteUrl.Replace(",", " ") + "," + site.Usage.Storage / (1024 * 1024) + "," + ObjSplitUsers + "," + roleAssignment.Member.LoginName);
                                                }

                                            }
                                        }
                                    }
                                }
                                if (roleAssignment.Member is SPGroup)
                                {
                                    foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                                    {
                                        if (roleDefinition.Name.Equals("Full Control"))
                                        { //ContributeUsers = new StringBuilder();
                                            var group = (SPGroup)roleAssignment.Member;
                                            foreach (SPUser user in group.Users)
                                            {
                                                if (user != null)
                                                {
                                                   SW.WriteLine(siteUrl.Replace(",", " ") + "," + site.Usage.Storage / (1024 * 1024) + "," + user.Name + "," + user.Email);
                                                  
                                                }
                                            }                                       

                                        }
                                    }
                                }
                            }

                        }
                       
                    }
                   
                     SW.Close();

                 }
                 catch(Exception ex)
                 {
                  
                 }
             });
          
        

Wednesday, June 19, 2013

Upload Excel data into SharePoint Custom list Programatically. (Instead of Import Spread Sheet)

Upload Excel data into SharePoint Custom list Programatically.

Target Values:



Destination : Values added into SharePoint List:



Add  a  Microsoft.Office.Interop.Excel: reference (.dll) from .NET tab.


using (SPWeb web = new SPSite("SiteUrl/").OpenWeb())
            {
                string workbookPath = @"C:\Sample.xlsx";
                Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
                if (ExcelObj == null)
                {
                    //  ("ERROR: EXCEL couldn't be started!");                    
                }
                ExcelObj.Visible = true;

                Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(workbookPath, 0, true, 5,
  "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true);
                Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                for (int i = 1; i <= 3; i++)
                {
                       // Defining cells Range. I have 6(a,b,c,d,e,f).
                    Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A" + i.ToString(), "F" + i.ToString());
                    System.Array myvalues = (System.Array)range.Cells.Value;

                    string[] theArray = new string[myvalues.Length];
                    for (int j = 1; j <= myvalues.Length; j++)
                    {
                        if (myvalues.GetValue(1, j) == null)
                            theArray[j - 1] = "";
                        else
                            theArray[j - 1] = (string)myvalues.GetValue(1, j).ToString();

                      // after adding all cells values into the Array, Adding these into SharePoint Items
                        if (theArray[myvalues.Length-1] != null)   //  if (theArray[5] != null) // if u have 6 cells
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList lst = web.Lists.TryGetList("UploadExcelData");
                            SPListItem addNewItem = lst.Items.Add();

                            if (theArray[0] != null)
                            {     // Add Items here into the list                               
                                addNewItem["Title"] = (theArray[0]);                              
                            }
                            else { }

                            if (theArray[1] != null)
                            {  // Middle Name 
                                addNewItem["MName"] = (theArray[1]);                             
                            }
                            else { addNewItem["MName"] = ""; }

                            if (theArray[2] != null)
                            { //Last Name
                                addNewItem["LName"] = (theArray[2]);                                
                            }
                            else { addNewItem["LName"] = "";  }
                            if (theArray[3] != null)
                            { //Contact
                                addNewItem["Contact"] = (theArray[3]);                               
                            }
                            if (theArray[4] != null)
                            { // Contact1
                                addNewItem["Contact1"] = (theArray[4]);                              
                            }
                            if (theArray[5] != null)
                            { // Address
                                addNewItem["Address"] = (theArray[5]);                                
                            }
                                         // Updating Lookup Field
                            if (theArray[6] != null)
                             { //CountryLookup                                   
                                    
                                    int itemID = 0;
                                    SPList lstExamStatus = web.Lists.TryGetList("Country");
                                    SPListItemCollection lstItemColl = lstExamStatus.Items;
                                    foreach (SPListItem item in lstItemColl)
                                    {
                                        if (item["Country"].ToString() == theArray[6])
                                        {
                                            itemID = item.ID;
                                            break;
                                        }
                                    }
                                    if (itemID != 0)
                                    {
                                        addNewItem["CountryLookup"] = itemID;
                                    }
                                    else { addNewItem["CountryLookup"] = 5; }                             
                               }
                            addNewItem.Update();
                            lst.Update();                           
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                    
                }           
            }  

        }

      

Tuesday, June 18, 2013

Custom Errors Handling in SharePoint (Handling Errors in SharePoint )

Custom Errors Handling in SharePoint(Handling Errors in SharePoint) 


System.Diagnostics.EventLog.WriteEntry("My Errors: Webpart Error Report", ex.Message);

Lookup: Adding data into SharePoint Lookup column Programatically

Adding data into SharePoint Lookup column Programatically:


Logic:
For Updating Lookup field Item, it takes ID only.
Not a string type value:

Here CountryLookup is lookup field in UploadExcelData List:
Pic:1


It is Taking the values from Country List with field is Country.
Pic:2

Pic:3
Pic:4

=====================================================
 SPList lstExamStatus = web.Lists.TryGetList("Country");
            SPListItemCollection lstItemColl = lstExamStatus.Items;
            foreach (SPListItem item in lstItemColl)
            {
                if (item["Country"].ToString() == itemname)
                {
                    id = item.ID;
                    break;
                }
            }

 if (ID != 0)
  {
         addNewItem["CountryLookup"] = ID;
   }
----------------------------------------------------------------------------------------------------------------------
Note: itemname (India, England France). If you want to update India. itemname= "India";
===========================================================


========================================================
===========================@============================

Another Case:

Source List: ExamStatus: Title having columns (Pass, Fail...)
Destination: SureStep: Status Lookup field (from Exam Status).

  string lstExamStatus = "ExamStatus";
            string examStatusField_Title = "Title";                                   
            SPListItemCollection lstItemColl = web.Lists["SureStep"].Items;
            SPListItem item = lstItemColl.Add();
            item["Title"] = "FirstName-Ravikumar1"; // Optional not neccesary

        // get_ID() method to retrive perticular Id.

            int ID = get_ID(web, lstExamStatus, examStatusField_Title, "Pass"); //Pass (Item Name) Selected value from drop down
            if (ID != 0)
                item["Status"] = ID;
            item.Update();



        public static int get_ID(SPWeb web, string list, string field, string itemname)
        {
            int id = 0;
           SPList lstExamStatus = web.Lists.TryGetList("ExamStatus");
           SPListItemCollection lstItemColl = lstExamStatus.Items;
            foreach (SPListItem item in lstItemColl)
            {
                if (item.DisplayName == itemname)
                {
                    id = item.ID;
                    break;
                }
            }
            return (id);

SharePoint Form Disabled users to csv file. (Export data to .CSV)

 Export All Disabled users in a SharePoint Form:

Add App.Config files for All web Applications:
App.config: 

 <appSettings>
    <add key="WebAppsName"  value="http://WebappUrl1|http://web01:81|http://communities|http://Sp2010"/>
  </appSettings> 



string EmailID = string.Empty; string siteUrl = string.Empty; string fullname = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                try
                {
                  
                           // For CSV.
                    StreamWriter SW;
                    SW = File.AppendText("c:\\UserInfoListReport.csv");                   
                    SW.WriteLine("Site collection URL,  User, Full Name,  E-Mail");
                       // Reading Webapplication url's from config file
                    String ConfigValues = ConfigurationSettings.AppSettings["WebAppsName"];

                    String[] ObjWebapps = ConfigValues.Split('|');
                    foreach (String WebappsName in ObjWebapps)
                    {
                        SPWebApplication webapp = SPWebApplication.Lookup(new Uri(WebappsName));
                        foreach (SPSite site in webapp.Sites)
                        {
                            foreach (SPWeb web in site.AllWebs)
                            {
                                siteUrl = web.Url;

                                SPSite Objsite = new SPSite(siteUrl);
                                SPWeb objweb = Objsite.OpenWeb();
                                SPGroupCollection ObjAllGrps = objweb.Groups;

                               
                                String ObjUsername = String.Empty;
                                SPUser ValidsUser = null;
                                foreach (SPGroup ObjUsers in ObjAllGrps)
                                {
                                    foreach (SPUser Objuser in ObjUsers.Users)
                                    {
                                        try
                                        {
                                            String ObjLoginName = Objuser.LoginName;
                                            EmailID = Objuser.Email;
                                            fullname = Objuser.Name;
                                            if (ObjLoginName.Contains("|"))
                                            {
                                                ObjUsername = ObjLoginName.Split('|')[1].ToString();
                                            }
                                            else
                                            {
                                                ObjUsername = ObjLoginName;
                                            }
                                            ValidsUser = objweb.EnsureUser(ObjUsername);
                                        }
                                        catch (Exception ex)
                                        {

                                            if (ObjUsername.Contains(@"\"))
                                            {
                                                      // Writing into CSV file
                                                SW.WriteLine(Objsite.Url.Replace(",", " ") + "," + ObjUsername + "," + fullname + "," + EmailID);                                           
                                            }
                                            else
                                            {
                                            }

                                        }
                                    }
                                }

                            }
                        }                       
                    }

                 
                    SW.Close();
                
                }
                catch (Exception ex)
                {                   
                } 
            
            });