Friday, September 6, 2013

Javascript Popup

string script = "<script language='javascript'>alert('Fields are Empty')</script>";
      Page.ClientScript.RegisterClientScriptBlock(GetType(), "Register", script);

Wednesday, July 3, 2013

Get All Sites in a SharePoint form


Get All Sites in a SharePoint form

            SPFarm farm = SPFarm.Local;
            SPWebService service = farm.Services.GetValue<SPWebService>("");
            foreach (SPWebApplication webapp in service.WebApplications)
            {
                foreach (SPSite site in webapp.Sites)
                {                
                    foreach (SPWeb web in site.AllWebs)
                    {
                        Console.WriteLine(web.Url);                       
                    }
                }
            }

Tuesday, July 2, 2013

SharePoint Site Accessed users list

SharePoint Site Accessed users list



 foreach (SPWeb web in siteCol.AllWebs)
                                {                                   
                                    DataTable dtUsers = new DataTable();
                                    dtUsers = web.GetUsageData(SPUsageReportType.user, SPUsagePeriodType.lastMonth, 400, DateTime.Now);
                                    if (dtUsers != null)
                                    {
                                        foreach (DataRow rows in dtUsers.Rows)
                                        {
                                            Allrecords.Add(rows["User"] + "|" + rows["Most Recent Day"] + "|" + web.Url);
                                            //Most Recent Day
                                            // Console.WriteLine(rows["User"] + "|" + rows["Most Recent Day"]);
                                        }
                                        foreach (DataColumn col in dtUsers.Columns)
                                        {
                                            Console.WriteLine(col.ColumnName);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine(web.Url);
                                    }
                                    
                                }

Monday, July 1, 2013

Get active directory user details c#, (Get All Active directory domains in a Network & All Enabled users from Active Directory) to CSV

Get All Active directory domains in a Network .

ArrayList Doamin = new ArrayList();
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                Forest currentForest = Forest.GetCurrentForest();
                DomainCollection domains = currentForest.Domains;
                foreach (Domain objDomain in domains)
                {
                    Doamin.Add(objDomain.Name);
                              
                }    
            });




===========================see more code==============================

All Enabled users from AD.

public static void GetAllInactivePersonsNEm()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {               
                //StreamWriter SW;
                //SW = File.AppendText("C:\\ADall_InactivePrsns_NEm.csv");
                //SW.WriteLine("User Name, Email , Domain Directory");
                Forest currentForest = Forest.GetCurrentForest();
                DomainCollection domains = currentForest.Domains;
                try
                {
                    foreach (Domain objDomain in domains)
                    {
                        Console.WriteLine("---Domain--" + objDomain.Name + "------");

                        string lDAPName = "LDAP://" + objDomain.Name;
                        DirectoryEntry entry = new DirectoryEntry("LDAP://" + objDomain.Name);
                        DirectorySearcher Dsearch = new DirectorySearcher(entry);

                        Dsearch.Filter = "(&(objectClass=user)(objectCategory=Person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
                        try
                        {
                            foreach (SearchResult sResultSet in Dsearch.FindAll())
                            {
                                DirectoryEntry de = sResultSet.GetDirectoryEntry();
                                Console.WriteLine(GetProperty(sResultSet, "cn"));

                                //String ObjEmail = (GetProperty(sResultSet, "mail"));
                                //if (!String.IsNullOrEmpty(ObjEmail))
                                //{
                                   // SW.WriteLine(GetProperty(sResultSet, "cn").Replace(",", " ") + "," + GetProperty(sResultSet, "mail") + "," + entry.Path.ToString());
                                //}
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
                catch (Exception ex)
                {
                }
               // SW.Close();
                Console.WriteLine("AD aAtive Document Write Completed..4..");               
                Console.ReadLine();
            });
        }


        public static string GetProperty(SearchResult searchResult, string PropertyName)
        {
            if (searchResult.Properties.Contains(PropertyName))
            {
                return searchResult.Properties[PropertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

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);