Sunday 21 April 2013

To find users existence in both SharePoint & Active Directory (AD)


                  In the last week, we got a problem over SharePoint User Profile Sync Service some user details are not ported properly, or missing from AD. Hence, we have users, with partially updated details so need to list those users, for this we could use this handy power shell script.


[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
clear;
$siteUrl = Read-Host "Enter the User Profile Url :: ";
$site = new-object Microsoft.SharePoint.SPSite($siteUrl);
$sw = New-Object System.IO.StreamWriter("D:\\ProfileDetails.txt");
$sw.WriteLine("User Profile Url :: "+$site.Url);
Write-Host "User Profile Url :: " $site.Url;
$sc = [Microsoft.Office.Server.ServerContext]::GetContext($site);
Write-Host "Status", $sc.Status;
$sw.WriteLine("Status :: "+$sc.Status);
$userProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($sc);
Write-Host "Total Users : " $userProfileManager.Count;
$sw.WriteLine("Total Users :: "+$userProfileManager.Count);
$enumerator = $userProfileManager.GetEnumerator();
$totalUserCount = 0;
while( $enumerator.MoveNext() -eq $true )
{
 $currentUserProfile = $enumerator.Current;
  $propertiesCollection = $currentUserProfile.ProfileManager.PropertiesWithSection;
  $userid = $null;
  if( $currentUserProfile -ne $null -and $propertiesCollection -ne $null )
  {
    $userid = $usrid = $currentUserProfile["AccountName"].tostring().split("\")[1];
[string]$usrName = "FirstName :: " + $currentUserProfile["FirstName"].toString() + " LastName :: " + $currentUserProfile["LastName"].toString();
$userName = $currentUserProfile["PreferredName"].toString();
    Write-Host "User Id :: " $usrid " User Name :: " $userName;
Write-Host $usrName;

$sw.WriteLine("User Id :: "+$usrid+" User Name :: "+$userName);
$sw.WriteLine($usrName);    
$objSite = new-object Microsoft.SharePoint.SPSite($siteUrl)
$objWeb = $objSite.OpenWeb();
try
{
$byUser = $objWeb.EnsureUser($usrid);
Write-Host $userid " exists both in AD & SharePoint" -ForegroundColor Green;
$sw.WriteLine($userid+" exists both in AD & SharePoint");
}Catch [System.Exception]
{
Write-Host $userid " doesn't exist in AD or SharePoint" -ForegroundColor Red;
$sw.WriteLine($userid+" doesn't exists in AD or SharePoint");
}
  }
}
$sw.Close();

Idea Behind:

Use ensureUser() method which will uses the following steps to ensure a user :
     1. Its first checks the User's ID from AD
     2. Get SPPrincipalInfo from Web App.
     3. If the SPPrincipalInfo from step 2 is null, try to get the user instance from AD again, Get the SPPrincipalInfo from AD (GC).

If any step fails, ensureUser will throw "Specified User Cannot be found".

Happy Coding :)



Tuesday 9 April 2013

2 More Code Snippets for SharePoint 2010


Hi all, here am about to discuss the usage of two APIs in Microsoft.SharePoint.dll (location: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI).
Using Microsoft.SharePoint.Administration;
Yesterday we had a discussion that our App should run on both SharePoint Foundation and SharePoint Server. For that thing, we need to detect the SharePoint products installed in a machine, as we are already aware of through Microsoft.SharePoint namespace we can manipulate the objects such as Sites, Webs, Lists, etc., Here we have to access the farm object, using Microsoft.SharePoint.Administration. Please, find this handy code, to do that thing.
Idea Behind:
For each of the SharePoint Product, MS had a GUID
// B2C0B444-3914-4ACB-A0B8-7CF50A8F7AA0 :SharePoint Server 2010 Standard Trial
// 3FDFBCC8-B3E4-4482-91FA-122C6432805C :SharePoint Server 2010 Standard
// 88BED06D-8C6B-4E62-AB01-546D6005FE97 :SharePoint Server 2010 Enterprise Trial
// D5595F62-449B-4061-B0B2-0CBAD410BB51 :SharePoint Server 2010 Enterprise
Hence, checking whether these guids are installed in our machine, will detect whether it’s a SharePoint Server machine.
Code:
Guid[] serverGuids = { new Guid(“B2C0B444-3914-4ACB-A0B8-7CF50A8F7AA0″),
newGuid(“3FDFBCC8-B3E4-4482-91FA-122C6432805C”),
newGuid(“88BED06D-8C6B-4E62-AB01-546D6005FE97″),
newGuid(“D5595F62-449B-4061-B0B2-0CBAD410BB51″) };
// If a Server ID cannot be detected we are running on Foundation.
boolisServer = SPFarm.Local.Products.Any(productGuid =>serverGuids.Contains(productGuid));
if (isServer)
{
Console.WriteLine(“You are running on SharePoint Server!!”);
}
else
{
Console.WriteLine(“You are running on SharePoint Foundation!!”);
}
Point to Remember:
The below will list out the SP products installed,
IEnumerable<Guid>mySP_Products = SPFarm.Local.Products;
Using Microsoft.SharePoint.WebPartPages;
For this, I need to discuss about a defect, which we faced at the last week, as we are showing the SharePoint Native Document Library, nothing but a page named AllItems.aspx [AllItems view] in an iframe of our App, as below

Wait, for the next set of items, even we passed IsDlg=0 for this page, next paging onwards, able to see, the ribbon, and Quick Launch too, as below

Solution:
The document container, which we are seeing is nothing but ListViewWebPart, as on editing the page, able to view, the properties for that web part as Asynchronous Update so on setting the value to true, able to get the page, without ribbon & quick launch. As we are having many doc libraries, we need the code, to do that,
C# Way:
SPSitesiteObj = new SPSite(your_siteurl);
SPWebwebObj = siteObj.OpenWeb(your_weburl,true);
SPLimitedWebPartManagerwebPartMgr = webObj.GetLimitedWebPartManager(“doc_lib_name/forms/AllItems.aspx”,WebParts.PersonalizationScope.Shared);
// get the XsltListViewWebPart…
// assumes the XsltListViewWebPart is the first and only one webpart present on that page
XsltListViewWebPartlvwp = (XsltListViewWebPart)webPartMgr.WebParts[0];
// set the webpart’sasync property.
lvwp.AsyncRefresh= true;
// save the changes
webPartMgr.SaveChanges(lvwp);
PowerShell Way:
functionenableAsync($siteUrl)
{
[Microsoft.SharePoint.SPSite]$siteObj = New-Object Microsoft.SharePoint.SPSite($siteUrl);
[Microsoft.SharePoint.SPWeb]$webObj = $siteObj.OpenWeb();
[string]$webPartUrl = -join($webObj.ParentWeb.Title,”/Forms/AllItems.aspx”);
Write-Host “WebPartUrl :: ” $webPartUrl;
[Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager]$webPartManager = $webObj.GetLimitedWebPartManager($webPartUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);
[Microsoft.SharePoint.WebPartPages.XsltListViewWebPart]$lstViewWebPart = [Microsoft.SharePoint.WebPartPages.XsltListViewWebPart]$webPartManager.WebParts[0];
if($lstViewWebPart.ASyncRefresh -eq $false)
{
$lstViewWebPart.ASyncRefresh = $true;
$webPartManager.SaveChanges($lstViewWebPart);
Write-Host “Doc Lib titled — ” $lstViewWebPart.Title ” is async enabled now.”;
}else
{
Write-Host “Doc Lib titled — ” $lstViewWebPart.Title ” is already async enabled.”;
}
}
Happy Coding :)

Friday 5 April 2013

Space Utility Tool


Problem Statement :

In SharePoint 2010, if we want to view the usage of data i.e., to enumerate how many # of list items being present in each list of a web application/site collection, is a tedious task which includes to customize a view that too works for a single site only. And if we go for C# way, the time for execution the entire site collection is heavy on both the SP server and client object models. For this, a handy SP PowerShell Script is being written, which does the job in no matter of time.

clear;
function getLastPart($url)
{
 $tempUrl = $url.Replace('/', ';')
 $val = $tempUrl.split(";");
 return $val[$val.Length - 1];
}
$TotalLists = 0;
$TotalListItems = 0;
$TotalItems = 0
$mySiteUrl = Read-Host "Enter the Url :: ";
$lstPart = getLastPart($mySiteUrl);
$mySiteUrl|out-String;
$SiteCollection = Get-SPSite $mySiteUrl;
$fileName = DateTime.Now;
$sw = New-Object System.IO.StreamWriter("D:\\Neran\ListInfoLogs\" +$fileName+ ".txt");
ForEach ($Site in $SiteCollection.AllWebs)
{
    $sw.writeline("<------------------------------------------------------------------->");
    $sw.writeline("Site Url :: " +$Site.Url);
    $ListCount = 0;
    $TotalItems = 0;
    ForEach ($List in $Site.Lists)
    {  
     $sw.writeline($List.Title+ " :: "+ $List.ItemCount);
     $TotalItems += $List.ItemCount
      $ListCount += 1;
        }
    $TotalListItems += $TotalItems;
    $TotalLists += $ListCount;
    $sw.writeline("Total # of Lists in Site "+ $Site.Url +" :: " +$ListCount);
    $sw.writeline("Total # of List Items in Site " + $Site.Url +" :: " +$TotalItems);
    $sw.writeline("<------------------------------------------------------------------->");
}
Write-Host "Total number of Lists: " $TotalLists;
Write-Host "Total number of ListItems: " $TotalListItems;
$sw.writeline("<------------------------------------------------------------------->");
$sw.writeline("Total # of Lists in Site Collection "+ $mySiteUrl +" :: " +$TotalLists);
$sw.writeline("Total # of List Items in Site Collection " +$mySiteUrl +" :: " +$TotalListItems);
$sw.writeline("<------------------------------------------------------------------->");
$sw.Dispose();
$sw.Close();


How to Use/Execute the Code :
1) Download the script and copy it to any of your local folder (say D:\\PS Scripts\)
2) Open the SP 2010 Management Shell ( Start -> All Programs -> MS SP 2010 products -> SharePoint 2010 Management Shell)
3) Navigate to the folder D:\\PS Scripts\ that contains the script
4) Execute the script by typing “.\SpaceUtility.ps1″
5) Prompts for the SP Site Collection Url :: (Enter the Url)
6) The console will provide you the results and the same will be written in the file named
  D:\\PS Scripts\Last_Part_Of_Your_Url.txt
Uses :
This script will be useful for SP Admins during Migration of Data from one server to another and at times of upgrading the SP 2007 to SP 2010.

Thursday 4 April 2013

ASync Methods in C#


Hi there, as we all have the habit of prioritizing our daily tasks, and some things (which are boring and repetitive ones), we postponed them for the later time, like that we can prioritize the tasks in .net programming  too,  with the help of these “ASync Methods”, as we all know about the primary difference between synchronous and asynchronous calls, Once again, will refresh that, we can have synchronous calls when we expecting for an output from the called method, but in case of asynchronous calls we may wait for the output or we can perform the other actions not by waiting.

“The primary scenario is the threads which usually takes more time to execute and also their output is not a main concern, will be designed as ASync Methods.”
2 Use Cases here which I came across recently about, the real usage of these ASync Methods,
Use Case: 1
You are uploading the document from UI (website) that document which gets replicated in different repositories [say 3 libraries], each library will take around 3 secs, to create that new document  in theirs. From the first creation of the document in the first library itself, the UI should be responsive, as an alert with ‘Creation Done/Failed!!’ So the remaining document libraries can be updated, later so here, we can use the above said postponement thing.
Use Case: 2
As you all had an experience of auditing the method calls, [i.e., just a record for the later purpose, how much times an method is used by whom n all]. Here the main or actual functionality of the method is needed for the UI or other applications, the audit purpose calls, whether it’s an insert to db or writing to flat file, is not the actual functionality of the method. Hence we can give this auditing work to the ASync Methods.
Syntax / Usage:
In C#, Asynchronous calls are made by using delegate. A delegate is an object that wraps a function. That delegate object has got BeginInvoke() and EndInvoke() methods which calls the wrapped up function asynchronously.
1. Say, you have methods named UserFeed & PublicFeed,
public string UserFeed(string userid,string filters){
                string userfeedResult = getuserfeed();//getting feed logic from DB  — main functionality
                AuditLog(userid,”USERFEED”, userfeedResult); // for audit purpose call
                return userfeedResult;  }
2. public string PublicFeed(string userid,string filters){
                string pubfeedResult = getPublicFeed(); //getting feed logic from DB  — main functionality
                AuditLog(userid,”USERFEED”, pubfeedResult);  // for audit purpose call
                Return pubfeedResult;
}
3. Private void AuditLog(string usrid,string method,string result) { // db insert }
The above said 2 methods, have a call for AuditLog(), which we can have it as ASync Call, like below,
4. delegate void AsyncAuditLog(string userid, string consumedMethod, string feedresult);   //declare a delegate with same param list as that of our AuditLog() method.
5. Replace the call for AuditLog() method as follows,

public string UserFeed(string userid,string filters){
                string userfeedResult = getuserfeed();//getting feed logic from DB  — main functionality
               AsyncAuditLog asyncAudiLogInvoke = new AsyncAuditLog(AuditLog);
               IAsyncResult result = asyncAudiLogInvoke.BeginInvoke(userID, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), consumedStatus, null, null);
                return userfeedResult;
}
 Inspite of Audit DB insert, our methods will return the result as quick as it’s fetched. The AuditLog() will happens in another thread.
PS : By this way you can save 100 millisecs. [verified], but it depends on you to get the call back value, and verify them.
Cons of ASync Methods:
As ASync methods are cunning, and become tortuously tricky to follow when applied in a real application, which naturally makes, any decompilation a bit of challenge. Debugging too, a little bit tedious here, as we not know about the nature of the compiler’s implementation for the ASync Method handling hence threads with alternate ids may get logged into your logs.
Happy Coding  :)

web programming in asp.net (Code Snippets - 1)


Here am sharing the two small code snippets which every web programmer should know.

Code – I
Btw, have u think of throwing a file output rather than Response.Write(“Hello”); from the browser. Use the following code for this purpose.
string outputFilePath = Server.MapPath(“Feed.xml”);
Response.ContentType = “text/xml”;
Response.AddHeader(“Content-Disposition”, “attachment;filename=\”" + outputFilePath + “\”");
Response.TransmitFile(outputFilePath);
Response.End();
Code – II
Already you may aware of the JSON format, In order to convert a C# Generic List to JSON string and vice-versa.  Follow the below steps
1) Add reference to System.Web.Extensions in your project.
// Assume that you have a generic list as shown below,
// List<Student> studentList = GetStudentList();
2) Use Serialize method in JavaScriptSerializer class for serializing generic list to JSON string.
// System.Web.Script.Serialization.JavaScriptSerializer studentSerializer =  new System.Web.Script.Serialization.JavaScriptSerializer();
3) Use Serialize method to convert patient list to JSON string.
// string JStr = studentSerializer.Serialize(studentList);
4) Now, the json string can be set to generic list of type patient as shown below,
//   List< Student > nList = new List< Student >();
//  nList = studentSerializer.Deserialize<List< Student > >(JStr);
Happy Coding :)

Configuring PowerGUI in SharePoint 2010!!

Hi all, as the post’s title suggest, this blog is all about Configuring the PowerGUI, tool in the SharePoint Environment. Last night,  we were about to deliver an urgent task. The task is to Create 3 more columns in the existing SharePoint lists. As we are having batch to accomplish this task, since we all knew about the worries in executing the batch. So, I thought of going PowerShell Way of accomplishing this task. As it involves, various site’s opening, within that various lists opening, the script will get a giant-size, In PS, the only problem is code maintainability., (that too scrolling up & down in a normal text-editor :( ).  So thought of using better editor, as per google’s first suggest, i intended to use thePowerGUI (so called my savior).
Before Using any tool, remember this quote,
“You have to learn the rules of the game. And then you play better than anyone else.”
this means have to configure the tool, before start using them. Hence the configuration goes as follows ::
1) Download the tool from the link ::https://powergui.org/downloads.jsp
2) Install it.
3) Open the tool & start using it (usually a sample Hello World script).
4) But our need is to configure them to SharePoint environment (or) we can say to enable SharePoint   CmdLets in PowerGUI.
1)  Open a command prompt with elevated permissions.
2)  Browse to C:\Windows\Microsoft.NET\Framework64\v2.0.50727
3)  Execute the InstallUtil.exe with the following command line parameters:
InstallUtil /LogToConsole=true C:\Windows\assembly\GAC_MSI\Microsoft.SharePoint.PowerShell\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Powershell.dll
5) All are working fine, but still we’ll get an annoying error, in the first step of using(yes that too with our familiar SPSite(“site-url”) object’s declaration :( ).
Error ::
“Microsoft SharePoint is not supported with version 4.0.21006.1 of the Microsoft.Net Runtime”.
Solution ::
If I got any errors (of type out-of-coverage) means, I’m having the habit of commenting that errr lines (mostly in web.config while hosting ;) ). Similarly, here too you can find the .config file named ScriptEditor.exe.config under the installed path, say “D:\Program Files (x86)\PowerGUI”
containing the lines ::
1.        <?xml version=”1.0″ encoding=”utf-8″ ?>
2.       <configuration>
3.       <startup useLegacyV2RuntimeActivationPolicy=”true”>
4.       <supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.0″ />
5.       <supportedRuntime version=”v2.0.50727″ />
6.       </startup> (vow, a smaller .config file for a beautiful tool. )
Try to comment the line 4 , for which version not supported 4.0 and Save.
Re-Open the tool and Continue, running your SP cmdlets with this tool.
Reason Behind ::
1) Based on the release notes of PowerGUI 3.2.0.2237 it seems they added .net 4.0 support natively. Not sure if it was supposed to be backwards compatible or not, but at first glance its not.
2) SP 2010 Object Model is built on .NET 3.5. This will not change. .NET 4.0 was not ready when building SharePoint 2010, so .NET 3.5 was the next best thing. Moreover, .NET 2.0 & .3.5 are based on same CLR but .NET 4.0 is having new CLR with DLR (Dynamic Language Runtime), a runtime environment that adds a set of services for dynamic languages to the CLR. Still, DLR is not yet having side-by-side execution.