Tuesday, November 5, 2013

Listing All Users in AD C# & ASP.Net

In a previous Post I described the code to get all the users in User Information List using Client Object Model.


In this post I will demonstrate listing all the AD users using C#. You need to add references to System.DirectoryServices and System.DirectoryServices.AccountManagement for this purpose.

Check the example below:

public class Example
{

   public List<ADUsers> ListAllADUsers()
        {
             List<ADUsers> users = new List<ADUsers>() ;


             using (var ctx= new PrincipalContext(ContextType.Domain, "your domain name"))
             {
                 using (var PSearcher= new PrincipalSearcher(new UserPrincipal(ctx)))
                 {
                     foreach (var account in PSearcher.FindAll())
                     {

                         string Name = Convert.ToString(account.DisplayName);
                         string SAMAccountName = Convert.ToString(account.SamAccountName);
                         string EmailAddress = Convert.ToString(account.UserPrincipalName);
                         users.Add(new ADUsers() { Name = Name, SAMAccountName=                                                                                      SAMAccountName, Email = EmailAddress });
                     }
                 }
             }
            return users;
        }
}
 public class ADUsers
    {
      
        public string Name { get; set; }        
        public string SAMAccountName { get; set; } 
        public string Email { get; set; }

    }

The method ListAllADUsers() returns the list of all the users in AD with Full Name, Domain Name and Email Address for each user.

Tuesday, October 29, 2013

Redirect to Another Page On Clicking OK in JavaScript Alertbox

Page Redirection after client script does not show the popup or alert box added to the code using ClientScript.RegisterStartupScript 

Example:

this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Operation Completed')", true);

 Response.Redirect("~/default.aspx"); 


In this code you will not get the alertbox and will be simply redirected to default.aspx page.

Modify the code like below

this.Page.ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Operation Completed.');window.location='default.aspx';", true);  

This will show the alertbox and upon clicking OK you will be redirected to default.aspx page                  

Thursday, October 24, 2013

SharePoint Storage Metrics


Problem

Are you having a quota limit exceeded problem and you want to know which site or list/library is consuming all the storage. Increasing the quota does not help? 

Resolution:

Storage Metrics

You can trace the sites that are using maximum storage on the server.
Storage Metrics provide a summarized report of how storage for the site collection is being used across Site Collections and Sites. This helps administrators and owners to quickly identify content that can be archived or removed in order to remain within their allocated quotas.
To begin using Storage Metrics select Site Actions, and then click Site Settings.
From Site Settings select Storage Metrics under Site Collection Administration or simply enter the following URL
http://siteColl/_layouts/storman.aspx 
 It will show complete report of the site usage.
 You can drill-down to building block level by clicking the title of the items in the report.

Storage Metrics shows wrong size of the list item or Document

The storage metrics shows a huge size of the documents ( that is not the actual size) due to its previous versions that are stored in its Content Database. 
As an example http://siteColl//Documents/abc.pptx this file has an actual size of 55.6 MB  and has 300 versions available so it takes a total quota size of 300 x 55.6 MB data. 
If this is the issue with a single document library or a list or lets say a few of them you can simply limit the maximum versions according to need (I set it to 5) for that library. But we actually need a permanent solution for the issue as there are a lot of documents available. 
A hotfix from Microsoft is available on  http://support.microsoft.com/kb/2687339  Apply this hotfix on your server. Or you can write custom code in Powershell or Server Object model to update the maximum version of the libraries or lists to desired numbers and updating all the list items.


Limiting the versions of document libraries and list while enabling versioning is a huge plus.




Wednesday, October 23, 2013

IE Crash When Adding a new List Item in to a List in Datasheet View

I came across an issue from one of the clients regarding Internet Explorer crash when user tried to a new list item in to a custom list. This list had many fields of around all field types including four to five Person or Group fields.

Reported Problem:
1. Can attach documents to existing rows, but cannot add a new row for a new item without Internet Explorer freezing. 
a. Click Debug and receive an “Unhandled win32 exception in iexplore.exe (10940)” error message
How it happens:
1. Either click New to add a new row in the Datasheet view, or go to the bottom of the datasheet and start populating fields in a blank row.
After populating all fields, and tabbing, the progress (activity) indicator above the clock will change from blank to green bars going back and forth. THEN, Internet explorer returns an error message, “Unhandled win32 exception in iexplore.exe (10940)”.

Resolution: 

SharePoint 2010 List Datasheet View has a known bug of this type, Microsoft  provides a hotfix (Click for Official Link to the Hotfix) named " Office 2010 hotfix package (Stslist-x-none.msp): October 30, 2012" for this issue. Download and update your server for the issue if it occurs for all lists. 

In my case, a similar list worked fine created from its template. The problem was just with the list. The last solution was to create a backup for the list and check all the field that possibly could cause the Problem 

Delete all the fields with Calculated field type and Person and Group field type  one by one and try testing the list again,I found out that a Person or Group field was responsible for the issue, I recreated it, stopped related workflow, cleared browser Cache but it was none of my use.

At last I found out that the field allowed multiple user selection, disallowing multiple selection (not needed in my case) resolved the issue.

I hope this helps :)





Tuesday, October 22, 2013

Creating a lookup field in SharePoint List Programmatically


        private void CreateList(SPWeb web)
        {
            SPListCollection lists = web.Lists;
            SPList list = lists.TryGetList("Child List");
            if (list == null)
            {
                lists.Add("Child List", "Example child list "  , SPListTemplateType.GenericList);
                list = web.Lists["Child List"];
                list.OnQuickLaunch = true;

          #region CreatingListFields
            if (list != null)
            {
                SPFieldText txtField = null;

                // Rename Title Field
                txtField = (SPFieldText)list.Fields["Title"];
                if (txtField != null)
                {
                    txtField.Title = "Text Field";
                    txtField.Update();
                }

               // Creating a lookup field
               SPList targetList= web.Lists.TryGetList("Parent List");
               if (targetList != null)
               {
                   list.Fields.AddLookup("Child Lookup Field Name", targetList.ID, false);
                   SPFieldLookup lookup = (SPFieldLookup)list.Fields["Child Lookup Field Name"];
                   lookup.LookupField = targetList.Fields["ParentListFieldName"].InternalName;
                   lookup.AllowMultipleValues = false;
                   lookup.Update();
               }             

                list.Update();
            #endregion

                // Add a default View to the List
        
            #region DefaultView 
            SPView view = list.DefaultView;
            view.RowLimit = 30;
            view.Title = "All Items";
            view.Update();
            list.Update();
            #endregion
        }
}


   

Thursday, October 3, 2013

"Cannot complete this action. Please try again" - Client Object Model

While using Client Object Model to access a list item I jumped into a strange error :) I should Say ! I went like "Cannot complete this action. Please try again" I reviewed the whole code and was blank at the end... I Googled whole day and found no option other than Thread.Sleep(toUnlimitedTime) as I tested :) At the end desperately  I reviewed my CamlQuery and there it goes!!! I missed adding </Query> ending tag in the query. And the error was gone :) Hard work Huh!!

Web web = ctx.Web;
            ctx.Load(
                web,
                website => website.Title,
                website => website.HasUniqueRoleAssignments);
            ctx.ExecuteQuery();
            List list = ctx.Web.Lists.GetByTitle("MyList");
            CamlQuery query = new CamlQuery();      
                string que = @"<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>xyz</Value></Eq></Where></Query></View>";
                query.ViewXml = que;
                SP.ListItemCollection coll = list.GetItems(query);
            ctx.Load(coll, items => items.Include(item => item,                                              
                                                  item => item.Id,
                                                  item => item.HasUniqueRoleAssignments,
                                                  item => item.DisplayName));
            ctx.ExecuteQuery();

 

Wednesday, May 15, 2013

Project Server 2010 error opening project "Project is read only"


When Project Professional is attempting to open a project from Project Server 2010, it will look at the status of local cache for that project. The local cache will override the server version.
Sometimes the users are unable to open the project from Project Server despite of deleting local cache.
Resolutions are of course:
1.      Delete the local cache using the Project Professional > File > Options > Save > Clean Up Cache
2.      PWA > Server Setting > Force Check-in Enterprise Objects > Check In the appropriate project.
3.      A third & important option – Note the folder location of the cache location in the step above. Usually it will be C:\Users\username\AppData\Roaming\Microsoft\MS Project\14\Cache\. There are subfolders in this “Cache” directory in the form of {xxx-xxx-xxx}.PROD.Domain\Username. You need to delete this {xxx} folder BUT you have to close Project Pro first as it locks the cache folders from being deleted.

Error: "The Managed Metadata Service or Connection is currently not Available”


"The Managed Metadata Service or Connection is currently not available. The Application Pool or Managed Metadata Web Service may not have been started. Please Contact your Administrator."
  1. Open Central Administration by going Start | All Programs | Microsoft SharePoint 2010 Products | SharePoint 2010 Central Administration.
  2. Click on Manage Service Application which is available in Application Management section.

  3. When you click on Managed Metadata Service application, sometimes you may get the following error:

  4. Go and check whether the Managed Metadata Service has been started.
  5. Click on Application Management in the quick launch.
  6. Click on Manage services on server under Service Applications section.
  7. Check whether the Managed Metadata Web Service is started; if not then click on Start.

  8. Do an IISRESET.
  9. Now you could be able to see the Managed Metadata Service properties as shown in the following figure:

  10. If you still face the same issue, go to IIS and check whether the Application pool for the metadata service is started (Note: Check the account in which the application pool for the metadata service is running. Sometimes if the password for the account is changed, you will get the same issue.).
Thus in this article you have seen how to resolve the following error "The Managed Metadata Service or Connection is currently not available. The Application Pool or Managed Metadata Web Service may not have been started. Please Contact your Administrator."

replace default farm administrator


How can we replace default farm administrator to any other account or vice - verse ? Please let me know the steps required to perform this task if possible or if not possible please provide an alternative.
Even though it's possible it's not a good idea doing that, I'll recommend if possible to reinstall SharePoint, do it again, do it right!
However if you decide to change it, here is the instructions, they are provided without any guarantee!
Go to Central Administration -> Security, click the Configure Service Accounts link under General Security head. Then select Farm Account from the doprdown list. Make sure the account you use have all the permissions. You need those permissions:
The server farm account is used to perform the following tasks:
Configure and manage the server farm.
Act as the application pool identity for the SharePoint Central Administration Web site.
Run the Microsoft SharePoint Foundation Workflow Timer Service.

Type av account:
Domain user account.

Additional permissions are automatically granted for the server farm account on Web servers and application servers that are joined to a server farm.
The account is added to the following SQL Server security roles:
dbcreator fixed server role
securityadmin fixed server role
db_owner fixed database role for all SharePoint databases in the server farm

SQL Server Reporting Services - rsReportServerDisabled error


SQL Server Reporting Services - rsReportServerDisabled error

A while ago I had to test a report created with SQL Server 2000 Reporting Services.  After installing Reporting Services and uploading the reports, went I attempted to access them I was shown the following error message.
Error rsReportServerDisabled : The report server cannot decrypt the symmetric key used to access sensitive or encrypted data in a report server database. You must either restore a backup key or delete all encrypted content and then restart the service
C:\Program Files\Microsoft SQL Server\80\Tools\Binn> rsactivate -r -c"C:\Program Files\Microsoft SQL Server\MSSQL\Reporting Services\ReportServer\RSReportServer.config"
After which, everything worked just fine.

Unknown error occurred while adding user to farm admins

Error message when you add a user into a Farm Administrators group in SharePoint Foundation 2010 or in SharePoint Server 2010: "An unexpected error has occurred"
You add a user into a Farm Administrators group in SharePoint Foundation 2010 or in SharePoint Server 2010. In this case, you receive the following error message:
An unexpected error has occurred.
This issue occurs when you are not a local administrator.
To work around this issue, you must be a member of both the following groups on the server that is hosting the SharePoint Central Administration Web site:
·         Farm administrators group
·         Local administrators group

Check ULS logs for the error from administrative tools ->Event Viewer ->Windows logs -> Application -> trace the error in SP Foundation -> “Local administrator privilege is required to update the Farm administrator’s Group”
Add the user to local admins and logoff then log on

SharePoint Central Admin Accessibility (Unknown error Occurred) Application Server Administration job failed for service instance

 Application Server Administration job failed for service instance Microsoft.Office.Server.Search.Administration.SearchServiceInstance (GUID).


Reason: Logon failure: unknown user name or bad password

Techinal Support Details:
System.ComponentModel.Win32Exception: Logon failure: unknown user name or bad password at Microsoft.Office.Server.Search.Administration.SearchServiceInstance.SynchronizeDefaultContentSource(IDictionary applications)
at Microsoft.Office.Server.Search.Administration.SearchServiceInstance.Synchronize()
at Microsoft.Office.Server.Administration.ApplicationServerJob.ProvisionLocalSharedServiceInstances(Boolean isAdministrationServiceJob)

So you might have changed search service account manually, if you have changed farm admin account please run script mentioned in following article
this is the procedure to update farm admin account
How to change service accounts and service account passwords in SharePoint Server 2010

To change the passwords for service accounts in SharePoint Server 2007 and in Windows SharePoint Services 3.0, follow these steps.

Note If the Microsoft SQL Server service uses a domain account, and the password for that domain account is either expired or invalid, make sure that you update the password for the domain account first.
1.      Update the password for the account that is used by the Central Administration application pool. To do this, follow these steps:
a.      On all servers in the server farm, open a command prompt, type the following line, and then press Enter:
cd %commonprogramfiles%\Microsoft Shared\Web server extensions\14\Bin
b.      Do one of the following:
§  On the server that hosts the Central Administration website, type the following line at the command prompt, and then press Enter:

stsadm -o updatefarmcredentials -userlogin DomainName\UserName -password NewPassword
§  On all other servers in the server farm, type the following line at the command prompt, and then press Enter:

stsadm -o updatefarmcredentials -userlogin DomainName\UserName -password NewPassword -local
c.       Restart Internet Information Services (IIS) 6.0. To do this, type the following line at the command prompt, and then press Enter:
iisreset /noforce
2.      Verify that the Administration Application Pool Credential Deployment job definition is no longer displayed on the Timer Job Definitions page of SharePoint 3.0 Central Administration. To do this, follow these steps:
 .        Open SharePoint 3.0 Central Administration, click Operations, and then click Timer job definitions under Global Configuration.
a.      Verify that the Administration Application Pool Credential Deployment job definition is no longer displayed in the list.

Note If the Administration Application Pool Credential Deployment job definition is displayed in the list, wait until it disappears from the list.
3.      Update the password for the application pool account that is used by web applications on the server farm. To do this, type the following line at a command prompt on every server on the server farm, and then press Enter:
stsadm -o updateaccountpassword -userlogin DomainName\UserName -password NewPassword -noadmin
4.      Update the password for the account that is used to run the Windows SharePoint Services Help Search service. To do this, type the following line at a command prompt on every server on the server farm, and then press Enter:
stsadm.exe -o spsearch -farmserviceaccount DomainName\UserName -farmservicepassword NewPassword
5.      Update the password for the default content access account that is used by the Windows SharePoint Services Help Search service. To do this, type the following line at a command prompt on every server on the server farm, and then press Enter:
stsadm.exe -o spsearch -farmcontentaccessaccount DomainName\UserName -farmcontentaccesspasswordNewPassword
6.      If you are running SharePoint Server 2007, you must also follow these steps:
 .        Update the password for the account that is used by every Shared Services Provider (SSP) on the server farm. To do this, type the following line at a command prompt on every server on the server farm, and then press Enter:
stsadm.exe -o editssp -title SharedServicesProviderName -ssplogin DomainName\UserName -ssppassword NewPassword
a.  Update the password for the account that is used to run the Office SharePoint Server Search service. To do this, type the following line at the command prompt, and then press Enter:
stsadm.exe -o osearch -farmserviceaccount DomainName\UserName -farmservicepasswordNewPassword
b.  If the server farm is configured to use single sign-on, update the password for the account that is used by the Microsoft Single Sign-On Service. To do this, follow these steps:
1.      Click Operations in SharePoint 3.0 Central Administration, and then click Service accounts under Security Configuration.
2.      Under Windows service, click Single Sign-On Service.
3.      Under Configurable, specify the password, and then click OK.
c.       Update the password for the default content access account that is used by the Office SharePoint Server Search service. To do this, follow these steps:
0.      Open SharePoint 3.0 Central Administration, and then click the link to the SSP web application under Shared Services Administration.
1.      Under Search, click Search settings, and then click Default content access account.
2.      Specify the password to use for the content access account, and then click OK.

Changing the SharePoint 2010 Admin Password in Window Based Authentication Mode, Reporting Service Account Configuration

(Changing the Password without configuring the steps for services below will cause “Service Unavailable Error” while “Page cannot be Displayed Error” if AppPool is not started.)
It is caused because either the password for the farm admin has expired or the user had changed the password.
1.      Change the Admin Password by Pressing Alt+Ctrl+Dlt -> Change a Password
2.      Go to Run -> Services.msc or Start -> Administrative Tools ->Services
3.      Go to the Services that use that admin account as log on
4.      Change the Password of all the Services using that account
5.      Restart the service if it was running already or if you want to start it.
6.      Go to IIS Manager ->Application Pools
7.      For each application pool running with the admin account
8.      Set the Password for admin
9.      Repeat the process for all the App Pools
10.  Reset IIS Web Server from cmd -> iisreset –noforce or restart it manually.
Reporting Service Account Configuration
1.                  The account must be part of administrators in the AD and on the local system if it is a  farm solution
2.                  From Services in Administrative Tools change the Logon admin to new Reporting service account
3.                  Change Reporting Service account in RSConfig.exe or config tool
4.                  Ensure backup of encryption key
5.                  In the Database menu on the left  ->Change Database -> Choose an existing report server Database -> Next
6.        
7.                  Choose the report server DB
8.                  Press next and complete the process then apply all changes and Exit.
9.                  Grant full permissions to the user to SQL Server
10.              Log off the system and log on again to ensure implementation of the changes
11.              Reporting Service integration in Central Admin
12.              Change user and Password on Every Report