September 4, 2013

Add webpart to existing pages and add custom property meta data values to webparts through utility

Webparts adding to existing page and their custom property values which are meta data.
What i have done here is created powershell script to get taxonomy values like term store. powershell script will ask for central admin URL and Termstore name.
   1:  Add-PSSnapin Microsoft.SharePoint.PowerShell
   2:  #read parameters from command line
   3:  $CurrentDir= Split-Path -parent $MyInvocation.MyCommand.Definition
   4:  $timeStamp = (Get-Date).ToString("yyyyMMddhhmmss")
   5:  $logFile = $CurrentDir+ "\install_" + $timeStamp + ".log"
   6:  start-transcript -path $logFile -noclobber
   7:  $url = Read-Host "Enter Central admin url" 
   8:  #$url = "http://br66:14209/"
   9:  #$site = Get-SPSite -Identity "http://br66:14209/"
  10:  $web = Get-SPWeb $url
  11:  $taxonomySession = Get-SPTaxonomySession -Site $web.Site
  12:  $termStoreName = Read-Host "Enter TermStore Name"
  13:  $termStore = $taxonomySession.TermStores[$termStoreName];
  14:  Write-Host $termStore.Name $termStore.Id

   1:  foreach($item in $termStore.Groups)
   2:  {
   3:  Write-Host $item.Name
   4:  foreach($term in $item.TermSets)
   5:  {   
   6:   if($term.Name -eq "Site Section")
   7:   {
   8:    Write-Host $term.Name
   9:    $group = $term
  10:   Write-Host ": " $group.Name $group.Id 
  11:   foreach($termSetUnit in $term.Terms)
  12:   {
  13:    if($termSetUnit.Name -eq "Test and Measurement")
  14:    {
  15:     Write-Host $termSetUnit.Name   
  16:     foreach($termset1 in $termSetUnit.Terms)
  17:     {
  18:      Write-Host $termset1.Name
  19:      $TermName = $termset1
  20:      Write-Host ": " $TermName.Name $TermName.Id
  21:     }
  22:    }
  23:   }
  24:   
  25:   }
  26:  }
  27:  }
With this one text file will generate and copy and paste values in config file

   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <ContentDeploymentConfig  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   3:   <SourceSite>http://br66:50001</SourceSite>
   4:   <LastRunTime>2013-01-01T12:00:00Z</LastRunTime>
   5:   <FeatureId>6717c859-64c8-4f7a-bfc0-873256087ac8</FeatureId>
   6:   <TaxonomyStoreID>0ded38c7-c349-4638-8ce8-e564fdd44922</TaxonomyStoreID>
   7:   <TaxonomySetID>ddb6225b-471c-4a6c-853f-bf4686dc88e6</TaxonomySetID>
   8:   <TaxonomyProductGUID>Products|9b34e73d-d4c2-4680-bd8c-5343f4b66463</TaxonomyProductGUID>
   9:   <TaxonomyServiceGuid>Services|bc612c4e-3267-4c6f-9ff1-0e99726e802f</TaxonomyServiceGuid>
  10:   <Countries>
  11:    <Japan>ja-jp</Japan>
  12:    <China>zh-cn</China>
  13:    <poland>pl-pl</poland>
  14:    <Russia>ru-ru</Russia>
  15:    <Germany>de-de</Germany>
  16:    <Spain>es-es</Spain>
  17:    <Brazil>pt-pr</Brazil>
  18:    <UnitedStates>en-us</UnitedStates>
  19:   </Countries>
  20:  </ContentDeploymentConfig>
Above red marked values i got from script.
After getting this values add webparts to existing pages of site.
Your page should be checked out above spmgr else it will not do checked out if it is written inside.

   1:  if (pageCategory.CheckOutType == SPFile.SPCheckOutType.None)
   2:                              {
   3:                                  pageCategory.CheckOut();
   4:                              }
   5:  SPLimitedWebPartManager spmgr = sourceProductsWeb.GetLimitedWebPartManager(pageCategory.Url.ToString(), PersonalizationScope.Shared);
   6:                              string exportedWebPartXml = string.Empty;
   7:                              if (WebpartTitle == "EngagementProductLinks")
   8:                              {
   9:                                  exportedWebPartXml = new StringReader(sourceSite.RootWeb.GetFileAsString(sourceSite.RootWeb.Url + "/_catalogs/wp/EngagementProductLinks.webpart")).ReadToEnd();
  10:                              }
  11:                              else if (WebpartTitle == "RightColumnPromotions")
  12:                              {
  13:                                  exportedWebPartXml = new StringReader(sourceSite.RootWeb.GetFileAsString(sourceSite.RootWeb.Url + "/_catalogs/wp/RightColumnPromotions.webpart")).ReadToEnd();
  14:                              }
  15:                              XmlTextReader reader = new XmlTextReader(new StringReader(exportedWebPartXml));
  16:                              System.Web.UI.WebControls.WebParts.WebPart importedWp = spmgr.ImportWebPart(reader, out outmessage);
  17:                              String spmgrWebPartTitle = string.Empty;
  18:                              if (spmgr != null)
  19:                              {                                
  20:                                  for (int j = 0; j < spmgr.WebParts.Count; j++)
  21:                                  {
  22:                                      spmgrWebPartTitle = spmgr.WebParts[j].Title;
  23:                                      if (spmgrWebPartTitle != WebpartTitle)
  24:                                      {
  25:                                          if (spmgr.GetZoneID(spmgr.WebParts[j]) == "ContactsZone")
  26:                                          {
  27:                                              countwebparts++;
  28:                                          }
  29:                                      }
  30:                                      if (spmgrWebPartTitle == WebpartTitle)
  31:                                      {
  32:                                          if (spmgr.GetZoneID(spmgr.WebParts[j]) == "ContactsZone")
  33:                                          {
  34:                                              sourceProductsWeb.AllowUnsafeUpdates = true;
  35:                                              spmgr.DeleteWebPart(spmgr.WebParts[j]);
  36:                                              pageCategory.Update();
  37:                                              sourceProductsWeb.AllowUnsafeUpdates = false;                                            
  38:                                          }
  39:                                      }
  40:                                      
  41:                                      if (spmgrWebPartTitle.Equals("Promotion Right Column"))
  42:                                      {
  43:                                          if (spmgr.GetZoneID(spmgr.WebParts[j]) == "ContactsZone")
  44:                                          {
  45:                                              sourceProductsWeb.AllowUnsafeUpdates = true;
  46:                                              WriteLog("found");
  47:                                              spmgr.DeleteWebPart(spmgr.WebParts[j]);
  48:                                              pageCategory.Update();                                                                                      
  49:                                              sourceProductsWeb.AllowUnsafeUpdates = false;                                           
  50:                                          }                                        
  51:                                      }
  52:                                  }
  53:                              } 
  54:  sourceProductsWeb.AllowUnsafeUpdates = true;                             
  55:  try
  56:              {
  57:                  if (pageCategory.CheckOutType == SPFile.SPCheckOutType.None)
  58:                  {
  59:                      pageCategory.CheckOut();                }               
  60:                  
  61:                  importedWp.ChromeType = PartChromeType.None;
  62:                  spmgr.AddWebPart(importedWp, "ContactsZone", index);
  63:                  spmgr.SaveChanges(importedWp);
  64:                  PropertyInfo[] SiteSecitonProperty = importedWp.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
  65:                  foreach (PropertyInfo sitesection in SiteSecitonProperty)
  66:                  {
  67:                      if (sitesection.Name == "SiteSectionTaxonomy")
  68:                      {
  69:                          sitesection.SetValue(importedWp, GUID, null);
  70:                          spmgr.SaveChanges(importedWp);
  71:                      }
  72:                      else if (sitesection.Name == "TermStoreID")
  73:                      {
  74:                          string TermStoreguid = ContentDeploymentConfigObj.TaxonomyStoreID;
  75:                          System.Guid guid = new Guid(TermStoreguid);
  76:                          sitesection.SetValue(importedWp, guid, null);
  77:                          spmgr.SaveChanges(importedWp);
  78:                      }
  79:                      else if (sitesection.Name == "TermSetID")
  80:                      {
  81:                          string TermSetguid = ContentDeploymentConfigObj.TaxonomySetID;
  82:                          System.Guid guid = new Guid(TermSetguid);
  83:                          sitesection.SetValue(importedWp, guid, null);
  84:                          spmgr.SaveChanges(importedWp);
  85:                      }
  86:                      else if (sitesection.Name == "Text")
  87:                      {
  88:                          sitesection.SetValue(importedWp, GUID, null);
  89:                          spmgr.SaveChanges(importedWp);
  90:                      }
  91:                  }                
  92:                  pageCategory.CheckIn(" Added Web Part " + importedWp.Title);                               
  93:              }
  94:              catch (Exception ex)
  95:              {
  96:                  WriteLog("Error " + ex.Message + "Page is " + pageCategory.Title);
  97:                  WriteLogFile(false, ex.Message + sourceProductsWeb.Url.ToString() + "/" + pageCategory.Url.ToString() + " giving error in site ");
  98:                  if (pageCategory.CheckOutType == SPFile.SPCheckOutType.Online)
  99:                  {                    
 100:                      pageCategory.CheckIn("Checkin");
 101:                  }               
 102:              }
 103:                              sourceProductsWeb.AllowUnsafeUpdates = false;

Above code is to add webparts and properties value to webparts.
If you have any questions you can reach out our SharePoint Consulting team here.

Get User's Properties from Active Directory through profile synchronization.

​User's Property in Active directory are there like City, Job, Birthday, Hire Date etc.
what i have done here is displaying current week's birthday(i.e Sunday to satureday) and hire date with total years of joining from active directory through userprofile synchronization.
Before i write code here, make sure that user profile does contains properties which you need, If it is not there than add that property. Also user must be there, user profile synchronization service must be started

   1:  SPSecurity.RunWithElevatedPrivileges(delegate()
   2:              {
   3:                  using (SPSite site = new SPSite(SPContext.Current.Site.RootWeb.Url))
   4:                  {
   5:                      using (SPWeb web = site.OpenWeb())
   6:                      {
   7:                          try
   8:                          {
   9:   
  10:   
  11:                              SPServiceContext spServiceContext = SPServiceContext.GetContext(site);
  12:                                                                                  
  13:   
  14:   
  15:                              UserProfileManager profileManager = new UserProfileManager(spServiceContext);
  16:                              if (profileManager == null)
  17:                                  return;
  18:                              
  19:                              startDate = DateTime.Now;
  20:                              while (startDate.DayOfWeek != DayOfWeek.Sunday)
  21:                              {
  22:                                  startDate = startDate.AddDays(-1);
  23:                              }
  24:                              endDate = startDate.AddDays(6);                            
  25:                              startdate = startDate.Day;
  26:                              startmonth = startDate.Month;
  27:                              enddate = endDate.Day;
  28:                              endmonth = endDate.Month;
  29:                              IEnumerator profileEnumerator = profileManager.GetEnumerator();
  30:                              while (profileEnumerator.MoveNext())
  31:                             
  32:                              {
  33:                                  UserProfile userProfile = profileEnumerator.Current as UserProfile;
  34:                                  if (SPContext.Current != null)
  35:                                  {
  36:                                      string userLoginName = userProfile["AccountName"].ToString();
  37:                                                                                               
  38:                                  }
  39:                                  if (userProfile == null)
  40:                                      return;
  41:                                  DataRow drbirthday = dtBirthday.NewRow();
  42:                                  DataRow drAnniversary = dtAnniversary.NewRow();
  43:                                  if (userProfile[PropertyConstants.Birthday].Value != null)
  44:                                  {
  45:                                      BirthdayDate = (DateTime)userProfile[PropertyConstants.Birthday].Value;
  46:                                      if ((BirthdayDate.Day >= startdate && BirthdayDate.Month == startmonth) && (BirthdayDate.Day <= enddate && BirthdayDate.Month == endmonth))
  47:                                      {
  48:                                          drbirthday["Name"] = userProfile[PropertyConstants.PreferredName].Value.ToString();
  49:                                          drbirthday["Date"] = BirthdayDate.Month + "/" + BirthdayDate.Day;
  50:                                          drbirthday["fullstring"] = Convert.ToString( drbirthday["Date"]) + "-" + Convert.ToString( drbirthday["Name"]);
  51:                                          dtBirthday.Rows.Add(drbirthday);
  52:                                          birthDayData.Text = birthDayData.Text + (birthDayData.Text == string.Empty? string.Empty: "; ") +Convert.ToString(drbirthday["fullstring"]);
  53:                                      }                                   
  54:                                  }
  55:                                  if (userProfile[PropertyConstants.HireDate].Value != null)
  56:                                  {
  57:                                      AnniversaryDate = (DateTime)userProfile[PropertyConstants.HireDate].Value;
  58:                                      if ((AnniversaryDate.Day == date && AnniversaryDate.Month == month ))
  59:                                      {
  60:                                          int todayyear = DateTime.Today.Year;
  61:                                          int Anniyear = AnniversaryDate.Year;
  62:                                          int totalAnniYear = todayyear - Anniyear;
  63:                                          drAnniversary["Name"] = userProfile[PropertyConstants.PreferredName].Value.ToString();
  64:                                          drAnniversary["Years"] = totalAnniYear;
  65:                                          drAnniversary["fullstring"] = Convert.ToString(drAnniversary["Name"]) + "-" + Convert.ToString(drAnniversary["Years"] + " years");
  66:                                          dtAnniversary.Rows.Add(drAnniversary);
  67:                                          AnniDayData.Text = AnniDayData.Text + (AnniDayData.Text == string.Empty? string.Empty: ", ") + Convert.ToString(drAnniversary["fullstring"]);
  68:                                      }                                    
  69:                                  }
  70:                              }
  71:   
  72:   
  73:                          }
  74:                          catch (Exception ex)
  75:                          {
  76:                              Common.ErrorLog(ex.Message + Environment.NewLine + ex.StackTrace, "GetUserBirthdayAnniversary", Microsoft.SharePoint.Administration.TraceSeverity.Unexpected);
  77:                          }
  78:   
  79:   
  80:                      }
  81:                  }
  82:              });
This will helps to get user's properties from Active Directory.

If you have any questions you can reach out our SharePoint Consulting team here.

Unable to load workflow actions from server SharePoint Designer 2010

Problem:

When trying to open any workflow in SharePoint Designer, Error gets fired like:

Unable to load workflow actions from the server….

While checking ULS logs, below exception was found:

SOAP exception: System.ArgumentException: An item with the same key has already been added. at
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at
System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) at
Microsoft.SharePoint.SoapServer.WebPartPagesWebService.GetWorkflowActionsFromFeatureElements(UInt32 currentLcid) at
Microsoft.SharePoint.SoapServer.WebPartPagesWebService.FetchLegalWorkflowActions()

Looking to exception details it becomes clear that this error is something related with duplication.

Solution:

Check Farm Level Solutions:
Browse to Central administration ->Click System Settings ->Click Manage Farm Solutions.

Then,

Check Site Collection Level Solutions:
Browse to Site collection ->Click Site Actions ->Site Settings ->Solutions (under Gallery).

Put both of the browser windows side-by-side and see if you have anything activated at both scopes, means there is any solution which is deployed at farm level and the same solution is also uploaded and activated to solutions gallery at site collection level. If you find this, deactivating the particular solution at site collection level should do the trick to open workflows in SharePoint Designer.


If you have any questions you can reach out our SharePoint Consulting team here.