Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, June 5, 2011

CrossListQueryInfo and CrossListQueryCache gotchas

CrossListQueryInfo class which comes with the Microsoft Publishing infrastructure makes use of object caching techniques to query the requested data from the cache instead from the database. Remember to use this facility only if your code runs against a MOSS server and not on a WSS server. As this makes use of  object cache stored in WFE servers, it avoids to database input/output and network latency between the WFE's and database server.

Although it uses SPSiteDataQuery internally,the very first request using CrossListQueryCache takes more time than SPSiteDataQuery. Practically it includes the time for querying, caching and returning the values. But subsequent queries fetch results in a flash and no where comparable with SPSiteDataQuery.

Interesting fact is that this CrossListQueryCache and QueryInfo will not work in a Console line tool, it badly depends on the context. If you are really trying this interesting query technique in a web part, whenever you implement any change in your webpart and trying to debug. Apart from doing the IISReset/App pool recycle, don't forget to flush the object cache

A sample CrossListQueryCache
public DataTable GetDataTableUsingCrosslistQuery(SPSite site)
{
CrossListQueryInfo clquery = new CrossListQueryInfo();
clquery.RowLimit = 100;
clquery.WebUrl = site.ServerRelativeUrl;
clquery.UseCache = true ;
clquery.Lists = "";
clquery.Webs = "";
//clquery.Query = "";
clquery.Query = "569";
clquery.ViewFields = "";
CrossListQueryCache cache = new CrossListQueryCache(clquery);
DataTable results = cache.GetSiteData(site);
return results; 
}

Tuesday, September 28, 2010

Show communicator status in your custom application pages

When ever we show a username in a custom application page or in a custom web part, adding that small presence aware icon before the user name will be a value addition to the end users which allows to see the person's availability.

An ActiveX control called NameCtrl in Name.Dll is responsible to retrieve the user status and rendering.

Use the following snippet, get the string and render it on your custom page to make the presence aware work for you. Ensure Ows.Js is referenced in your master page, this javascript is responsible for instantiating the ActiveX control and rendering.

public static string GetIMStatusForUser(string personEmail, string personName)
{
string statusJS = String.Format("<span><img border=\"0\" height=\"12\" width=\"12\" src=\"/_layouts/images/blank.gif\" onload=\"IMNRC('{0}')\" id=\"IMID\"
ShowOfflinePawn=1><a href=\"mailto:{0}\">{1}</a></span>",
personEmail,personName);
return statusJS
}

Thursday, August 5, 2010

SharePoint 2010 SPSite : System.IO.FileNotFoundException

Can any one spot an error in the following snippet. Following snippet tries to open a SPSite, SPWeb and tries to open a List to get it item count. All objects exist in the server and this code was built with VS 2010 for SharePoint 2010 in x86 Debug mode.

I ended up with the following exception

System.IO.FileNotFoundException was unhandled
Message=The Web application at http://Foo could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
Source=Microsoft.SharePoint
StackTrace:
at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Administrator\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:


After a couple of minutes I got things straight. There was a mistake in the build, as a basic rule while developing for SharePoint 2010 all your build should be in x64 mode not in x86 mode.

Basic mistake, but it hurts and the error message is not really helping...

Tuesday, July 20, 2010

Load testing SharePoint pages using JMeter

Recently I found myself in search of an open source web load testing tool to do testing and to measure my SharePoint application's home page performance. Apache Jmeter a feature rich tool to prepare a load test which helped to arrive at the statistics.
JMeter Java desktop application which comes in an executable jar file and can be downloaded from here. Obviously you need java runtime(JRE) to start this jar file.
open the bin folder and open ApacheJMeter.jar file from windows explorer
Right click the Test Plan and add a Thread group

Provide the applicable values


Thread group configuration
  • Name - Give a name to store all settings in a jmx file.
  • Number of Threads - Number of concurrent users to hit the page
  • Ramp-Up Period - Thread acceleration period If the number of threads used is 10 and the ramp-up period is 20 seconds,it will take 20 seconds to create those 10 threads.i.e,one new thread in every two seconds, want to create all threads in a single shot, put zero in this
  • Forever - this option tells to keep sending requests to the tested application indefinitely. If disabled, JMeter will repeat the test for the number of times entered in the Loop Count box.
  • Loop Count - the number of times it has to repeat the test, it is effective only if the Forever check box is unchecked
  • Scheduler - want to specify the start and end time of the test, you have an option here
Once the Thread Group is configured add a Sampler called "HTTP request"



Provide the server name, port number, method etc


HTTP Request configuration
  • Server Name or IP - the server name or the IP address of the machine running the application being tested.
  • Port Number - the port number used by the web application
  • Protocol - the protocol used, either HTTP or HTTPS.
  • Method - the request method, either GET/POST/PUT or other options.
  • Path - the relative path to the page you want to hit
  • Follow Redirects - follows redirections sent by the Web application, if any.
  • Use KeepAlive - if checked, sends the Connection = Keep-Alive request header. By default, an HTTP 1.1 browser uses Keep-Alive as the value of the Connection header. Therefore, this checkbox should be checked.
  • Parameters - the list of parameters sent with this request. Use the Add and Delete buttons to add and remove parameters.
  • Send a file with a request - simulate a file upload to the Web application, good to test a large file upload through POST request scenario
  • Retrieve all images and Java Applets - download embedded content.
Add a couple of listeners "View results as Table" & Spline visualizer to see the load test results



Now save the project and run the Test, you will be seeing the samples in your configured listeners, here you can find the time taken for each thread sample hit and status of the request served by Server, number of bytes transfered and start time of the samples
Results in a Table


Result in Spline visualizer


Now fiddle with your code to tweak the performance.

Thursday, April 29, 2010

How to get NT AUTHORITY\Authenticated Users group using .NET object model

Yes obviously I can hard code a string constant for the value and use the string "NT AUTHORITY\Authenticated Users but I hate hard coding values if the object model is rich enough to provide me a way.

Following method will return NT AUTHORITY\Authenticated Users group as a string

public static string GetNTAuthenticatedUsers()
{
return new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null).Translate(typeof(NTAccount)).Value;
}

Monday, October 12, 2009

C# vs Objective C

Got a chance to mess with Objective C and Cocoa framework. Following are some typical thoughts when comparing with C# and .NET framework

• In Objective C keyword "self" is used instead of "this" of C#
• Memory allocation happens through "alloc", there is no "New" keyword in Objective C
• There is no Garbage Collector to collect objects out of scope, proper release/disposal of resources is essential in Objective C.
• Header files are imported instead of include (i.e #import statements are used instead of traditional #include statements)
• The spec of a class is divided in two parts interface and implementation, interface portion contains declaration class, variables and related methods. This interface normally lives in .h files
• Implementation portion has the actual code for the methods declared in interfaces. This implementation normally stays in .m files. So all classes are like an C# interface and its implementation, declaration and actual code is segregated.
• A class declaration starts with @interface compiler directive and ends with @end directive.
• Object references are pointers. Objective C supports both strongly typing and weak typing. Strong typing always happen with pointer declaration
• There are two types of methods, Instance methods & Class methods, Instance methods require an instance of the class to initiate the call and Class methods are much similar to Static methods in C#
• An instance method is marked with the dash(-) as prefix before the return type and signature of the method.for e.g, -(void)Insertsome:id(anobject)
• An Class method is marked with the plus(+) as prefix before the return type and signature of the method.for e.g, +(void)Insertsome:id(anobject)
• NULL in C# becomes nil in Obj C
• Calling a method is known as messaging,a message is the method signature and its parameters. All messages are enclosed in square brackets [ and ]
• A property declaration starts with @property directive followed by data type and property name.( Eg:- @property BOOL flag;)
• @synthesize compiler directive is used to instruct the compiler to generate methods according to the specification in the declaration
• C# Interfaces are called as Protocols in Objective C
• .XIB files are used to store UI related settings, i.e., if we design a form using the IDE that will be stored as a xib file. In Apple world people still use the legacy name .nib file(that is the legacy name still in use)
• In Objective C a solution is called as a Bundle.

Thursday, August 27, 2009

Including quotes in verbatim strings

As we all know C# supports two types of strings: regular and verbatim strings. Escape sequence character such as backslash is not processed within this verbatim string sequence except quote-escape-sequence("). I recently stumbled across this C# basic string rule


So to encode a xml fragment like this

string s="[formbody xmlns="http://www.Foo.com/FormBody"][/formbody]"

We should have to write as follows using verbatim character and Quote escape sequence

string s = @"[FormBody xmlns=""http://www.Foo.com/FormBody""][/FormBody]";

but C# handles this quote-escape-character as regular escape sequence internally


So beware while using verbatim strings and escape sequences altogether especially in cases of handling XML/HTML strings in C# code

For more Check the C# language Specification