April 30, 2012

Using HttpContext.GetGlobalResourceObject in webpart development

We found interesting issue during working with global resource files this week.

Problem:
Event if we are using HttpContext.GetGlobalResourceObject, web part was rendering data in English even if site language is other than English!

If we switch to edit mode, it was working sometime, but most of the time it was showing English text.

Root cause:
We tried creating a new application page and placed a webpart there, it was strange that it was working properly in the application page.

We finally found that at the time of reading resources through  HttpContext.GetGlobalResourceObject web part was not aware of the current UICulture

Solution:
Before:

   1:  var strLinkText = HttpContext.GetGlobalResourceObject("file", "key");
After:​

   1:  var strLinkText = HttpContext.GetGlobalResourceObject("file", "key",SPContext.Current.Web.UICulture);

Conclusion
Finally after passing third argument from SPContext.Current.Web.UICulture it worked properly
If you have any questions you can reach out our SharePoint Consulting team here.

April 23, 2012

Creating your first data cube.

SQL Server 2005/2008 comes along with the Business Intelligence Development Studio (also known as BIDS) which is used for creating projects related to analysis services, integration services, report server and report models (used to design reports on client side). In order to get started with BIDS to build your first analysis services project, you need to have the following SQL Server components installed: SQL Server Database Engine SQL Server Analysis Services (SSAS) Business Intelligence Development Studio A good working data warehouse Below are the steps to be followed to create the cube 

Create a new Analysis Services project

For creating a new project in BIDS, you’ll find the Business Intelligence Development Studio (BIDS) in Start > Microsoft SQL Server 2005/2008 folder. Once you’re in the business intelligence development studio, click File > New > Project from where you could create a new Analysis Services Project. Give it any name you like and click on ok. 

Define a data source

To define a data source, you'll use the Data Source Wizard. You can launch this wizard by right-clicking on the Data Sources folder in your new Analysis Services project. The wizard will walk you through the process of defining a data source for your cube, including choosing a connection and specifying security credentials to be used to connect to the data source. 

Defining a Data Source View

A data source view is a persistent set of tables from a data source that supply the data for a particular cube. BIDS also includes a wizard for creating data source views, which you can invoke by right-clicking on the Data Source Views folder in Solution Explorer. You can select from existing tables and set relations between them or enter in your own statements using “Edit Named Query”.
Now you can move further either creating Cube using Cube Wizard which automatically creates Dimensions to be used in the cube or by creating a Dimensions and using it in the Cube.

Creating Dimensions

BIDS also provides wizard for creating dimensions. It helps in defining the key columns and attributes to be in used within a cube. 

Creating Cubes

Cube wizard appears within BIDS for creating cubes where in measurement group tables are to be defined. Here option to either select from existing dimensions or create new dimensions is provided.

Deploying and Processing a Cube

To deploy the cube you just created, select Build > Deploy. This will deploy the cube to your local Analysis Server, and also process the cube, building the aggregates for you. BIDS will open the Deployment Progress window which will keep you informed during deployment and processing.

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

Best Practice: Maintaining scripts in your SharePoint project


Introduction

Branding is the most important part of any SharePoint project. If you are planning to deliver branding in your release, you have to make sure your developer team is proactive to deliver quality branding from early stage of the project. In most of the branding project, jQuery and JavaScript becomes must-have part. Here, we will discuss practices that can be followed to ensure quality deliverables.

Practice
  • Manage script files
    From the very starting stage of your project, split your all JavaScript code in three files.
    • jQuery.min.js - This will contain jQuery reference and should be reference first in order.
    • jQuery.plugins.js - This should contain all custom plugins we used in it.
    • ProjectName.js - This should contain all your custom code written to get your project pages work properly.
  • Choosing plugins for your project
    • Download plugin bundle to your local computer.
    • Generally plugin will contain sample html files, jQuery and plugin script files.
    • First thing to check is jQuery version you are using in your project and the one which is used in the plugin.
    • If they are different, replace their jQuery.min.js with the one we are using.
    • Properly test the sample provided in plugin in all browsers you are planning to support.
    • Once browser and version compatibility matches paste plugin's min.js at end of jQuery.plugins.js file.
    • Implement plugin specific mark up wherever applicable.
    • Always use projectName.js to initialize plugin.
    • Repeat above process when you choose to add any jQuery plugin
  • Resolving CONFLICTS!
    Another challenging part is, jQuery ready not working or custom plugin you are using is disturbing your site's CSS. Here are thoughts on the same:
    • Always use _spBodyOnLoadFunctionNames.Push("yourFunctionName") to initialize your scripts in page load.
    • Always use only necessary CSS from what plugin CSS has provided and prefix class or ID in CSS as application. For example if a generic class .clear is used and you are calling plugin using $('#news') you should replace that with #news .clear. Do this for all CSS you include for the class.
Final thoughts
Here we've pointed out some of the best practices. Like this post? You would like to add/correct something? please provide your feedback on the same. 

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

April 17, 2012

Performance analysis: Use SPList.ItemCount instead of SPList.Items.Count

Here is the code that can measure performance between two:

   1:  Stopwatch sw = new Stopwatch();
   2:   
   3:              using (SPSite site = new SPSite("http://site/"))
   4:              {
   5:                  using (SPWeb web = site.OpenWeb())
   6:                  {
   7:                      SPList list = web.GetList("/Lists/list");
   8:                      long totalMemory = 0;
   9:                      long totalCollectionCount = 0;
  10:                      Console.WriteLine("Good test");
  11:                      totalMemory = GC.GetTotalMemory(false);
  12:                      totalCollectionCount = GC.CollectionCount(0);
  13:                      sw.Start();
  14:                      Console.WriteLine("item count:{0} ", list.ItemCount);
  15:                      sw.Stop();
  16:                      Console.WriteLine("Total time taken:{0}", sw.Elapsed);
  17:                      Console.WriteLine("TotalMemory:{0}", GC.GetTotalMemory(false) - totalMemory);
  18:                      Console.WriteLine("CollectionCount:{0}", GC.CollectionCount(0) - totalCollectionCount);
  19:   
  20:                      GC.Collect();
  21:   
  22:                      Console.WriteLine("\nBadTest");
  23:                      totalMemory = GC.GetTotalMemory(false);
  24:                      totalCollectionCount = GC.CollectionCount(0);
  25:                      sw.Start();
  26:                      Console.WriteLine("item count:{0} ", list.Items.Count);
  27:                      sw.Stop();
  28:                      Console.WriteLine("Total time taken:{0}", sw.Elapsed);
  29:                      Console.WriteLine("TotalMemory:{0}", GC.GetTotalMemory(false) - totalMemory);
  30:                      Console.WriteLine("CollectionCount:{0}", GC.CollectionCount(0) - totalCollectionCount);
  31:   
  32:                      Console.WriteLine("Press Any key to exit...");
  33:                      Console.ReadKey();
  34:                  }
  35:              }
Results of your testing will depend upon items in list for Items.Count but it will be constant for Items.ItemCount

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

April 9, 2012

Command line parser like stsadmin in sharepoint console app


In our recent console application we decided to provide sharepoint Consultant administrators similar experience like stsadmin while providing custom features for administration and analysis. So we used an open source command line parser (codeplex) in order to implement command line parsing.

It has been proven a good choice. Here is how we can easily use it.

Source code:

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using CommandLine;
   5:  using CommandLine.Text;
   6:  using Microsoft.SharePoint;
   7:  using Microsoft.SharePoint.WebPartPages;
   8:   
   9:   
  10:  namespace SPAdmin
  11:  {
  12:      class Program
  13:      {
  14:          static Options options = new Options();
  15:          static StringBuilder fileOutput;
  16:          static void Main(string[] args)
  17:          {
  18:              ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));
  19:              if (!parser.ParseArguments(args, options))
  20:                  Environment.Exit(1);
  21:   
  22:              if (string.IsNullOrEmpty(options.operation))
  23:              {
  24:                  Console.WriteLine(options.GetUsage());
  25:                  Console.WriteLine("Press any key to exit...");
  26:                  Console.ReadKey();
  27:                  Environment.Exit(1);
  28:              }
  29:   
  30:              switch (options.operation.ToLower())
  31:              {
  32:                  case "Operation1":
  33:                      DoOperation1();
  34:                      break;
  35:                  case "Operation2":
  36:                      DoOperation2();
  37:                      break;
  38:              }
  39:   
  40:              Console.WriteLine("Press any key to exit");
  41:              Console.ReadKey();
  42:          }
  43:          private static void DoOperation1()
  44:          {
  45:             
  46:          }
  47:          private static void DoOperation1()
  48:          {
  49:             
  50:          }
  51:          private sealed class Options
  52:          {
  53:              [CommandLine.Option("o", "operation",
  54:                  Required = true,
  55:                  HelpText = "Name of operation\n ")]
  56:              public string operation;
  57:            
  58:   
  59:              [HelpOption(HelpText = "Dispaly this help screen.")]
  60:              public string GetUsage()
  61:              {
  62:                  var help = new HelpText("Test");
  63:                  help.AddOptions(this);
  64:                  return help;
  65:              }
  66:          }
  67:   
  68:      }
  69:   
  70:   
  71:  }

Details:
1. Create a new console app. (If you have CSK templates installed, you can create new sharepoint console app project.)
2. For defining options, add options class as an inner class to your Program.cs
3. In main method, parse the passed parameters.
4. try it with SPAdmin -o "operation1" and see what happens
Add options as you need! Nice and clean way to implement various operations.

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

Console application - accessing all webparts of a publishing page

Introduction:

Recently, we have been working on a sharepoint console app that finds invalid metadata terms assigned to web part properties. To get started we were trying to get all web parts on a publishing page.

Problem​:

There were several CQWP on page which were showing as error webparts when you get them using LimitedWebPartManager.

Solution:

Since CQWP and other publishing site web parts uses HttpContext.Current, we have to create a fake object in order to get it working properly. Here is the code that was included before GetLimitedWebPart call:


   1:  if (HttpContext.Current == null)
   2:  {
   3:  HttpRequest request = new HttpRequest("", web.Url, "");
   4:  HttpContext.Current = new HttpContext(request,
   5:  new HttpResponse(new StringWriter()));
   6:  HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
   7:  WindowsPrincipal wP = new WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
   8:  HttpContext.Current.User = Thread.CurrentPrincipal = wP;
   9:  }​
If you have any questions you can reach out our SharePoint Consulting team here.
Thanks​

April 6, 2012

Powershell: Get all web parts on a publishing page

There are lots of scripts available on web already for this. You must be wondering why am I posting this one?


When I tried various scripts on net to find web part on page, it gave me all content editor web parts on publishing page as error web part type.


After searching so much on internet I come through this link​ through which I was able to inspect correct type of web part. Here is the script:


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy")


$site = new-object Microsoft.SharePoint.SPSite "http://br41:19685/products/a-z-product-list"
$web = $site.OpenWeb()
$pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$pages = $pWeb.PagesList
$file=$web.GetFile("Pages/sas-pm.aspx")
if($file.Exists)
{
$manager = $file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
$wps = $manager.webparts
$wps | select-object @{Expression={$pWeb.Url};Label=”Web URL”},@{Expression={$fileUrl};Label=”Page URL”}, DisplayTitle, IsVisible, @{Expression={$_.RepresentedWebPartType.Name};Label=”Type”}
}
else
{
Write-Host "page not found"
}


Happy powershell scripting

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

April 2, 2012

How to force browser to clear cache for the Style sheet and Java Script

While googling on to the internet we may found so many solutions for forcing browser to clear the cache for the Stylesheet and javascript using code programatically.

But if we want to do it without any programming using IIS(Interner Information Server)?.

Follow given below steps to do this.

1.From the Start menu, click Administrative Tools, and then click Internet Information Services (IIS) Manager.

2.In the tree view on the left side, find your application.

3. Select the Output Caching menu item.




4. In the right column, click Add in the Action menu. You can add your output caching rule here.




5. In the File name extension field, for example, type .css, and then select User-mode caching and then click on Advanced button.



6. select the Query string variable(s) check box. And enter the appropriate variable(s) in the Query string variable(s) text box as *.



7. Follow this same procedure for javascript , add .js instead of .css in step 5.




Happy coding

Cheers!!!

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