Pages

Sunday 26 August 2012

Binding Data from SharePoint List to DataTable/ Grid View

Please Check the below complete code to bind SharePoint list items to a DataTable/ Gridview. In this post, we are using the list named "Employee" with 5 column: Title, Birthday, Male, Position, Salary. At first, we need to create an empty DataTable with its column
       

 protected DataTable dataTableInitiate()
      {
            DataTable dt = new DataTable();
            DataColumn col = dt.Columns.Add("ID", typeof(string));
            col.AutoIncrement = true;
            col.AutoIncrementStep = 1;
            col.AutoIncrementSeed = 1;
            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("Birthday", typeof(string));
            dt.Columns.Add("Male", typeof(string));
            dt.Columns.Add("Position", typeof(string));
            dt.Columns.Add("Salary", typeof(string));                     
            return dt;
      } 


For binding the item from the SharePoint list to the DataTable that we have just created:
       

protected DataTable bindToDataTable(SPListItemCollection itemCol)
      {
            DataTable dt = dataTableInitiate();
            if (itemCol.Count > 0)
            {
                foreach (SPListItem item in itemCol)
                {
                    DataRow dr = dt.NewRow();
                    dr["ID"] = int.Parse(item["ID"].ToString());
                    dr["Title"] = item["Title"] != null ? item["Title"].ToString() : string.Empty;
                    dr["Birthday"] = item["Birthday"] != null ? item["Birthday"].ToString() : string.Empty;
                    dr["Male"] = item["Male"].ToString() == "True" ? "Yes" : "No";
                    dr["Position"] = item["Position"] != null ? item["Position"].ToString() : string.Empty;
                    dr["Salary"] = item["Salary"] != null ? item["Salary"].ToString() : string.Empty;                    
                    dt.Rows.Add(dr);
                }
            }
            return dt;
       } 


We've completed copying data from SharePoint list items to DataTable. We'd like to bind data from this DataTable to the GridView control.
       

protected void bindToGrid()
        {
            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Employee"];
            SPListItemCollection items = list.Items;
            DataTable dt = new DataTable();
            dt = bindToDataTable(items);
            grid.DataSource = dt;
            grid.DataBind();
        }


Hope this helps!

Retrieve SharePoint List Data and bind this to a dropdownlist

To bind the drop down list data with a field from the SharePoint list you can use the below code methods:-
Method 1
       
if (!Page.IsPostBack)
        {
            using (SPSite site = new ("http://yoursharepointsite"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["NameOfYourList"];
                    dropSite.DataSource = list.Items;
                    dropSite.DataValueField = "Title"; // List field holding value - first column is called Title anyway!
                    dropSite.DataTextField = "Title"; // List field holding name to be displayed on page 
                    dropSite.DataBind();
                }
            }
        }



Method 2:- Using SPDataSource


Thursday 31 May 2012

User Information List

To see a site collection's hidden user information list append /_catalogs/users/simple.aspx onto the end of the site collection url.

Example:

http://sp2010:80/_catalogs/users/simple.aspx

Or you can change the MembershipGroupId to 0 to get all the users.

Tuesday 1 May 2012

SharePoint: Differences Between Global and Web Application Targeted Solution Deployment

SharePoint solutions are either deployed globally or targeted to a particular web application. The decision of which is made automatically by the SharePoint Solution framework depending on the contents of the solution manifest. Certain items in the solution manifest such as SafeControl entries result in modifications to a Web application’s web.config file. Only when a solution manifest does NOT contain any of these types of entries will the solution be globally deployed.


The deployment process behaves differently based on the type of deployment for the solution, and these differences have caused me quite a headache. Here are my findings that I think any SharePoint developer or administrator should be aware of when performing solution deployments.


Globally Deployed Solutions
When a solution is deployed globally, all SharePoint application pools, including Central Administration’s, are recycled automatically. This can be good and bad. This is good because any GAC installed DLL that has been upgraded needs to be reloaded. This can be bad though with regards to the availability of your entire SharePoint Farm.


In my particular case, I am working with a SharePoint administrator to deploy a globally deployed solution that is used by only a single web application. It is fine for this web application to be unavailable, as we have cleared it with our change control process and made announcements of the downtime, but we haven’t announced to users of the other SharePoint web applications in the Farm that their sites will be coming down along with it. So be forwarned.




Web Application Targeted Solutions I have become fond of web application targeted solutions because they offer me a workaround to the above availability problem. When a web application targeted solution is deployed or retracted, only the application pools of the targeted web applications are recycled.


Enterprise Farm Strategies When upgrading solutions, the upgradesolution stsadm command only gets you so far. I’ve found it is best to fully retract and remove the old solution and then add and deploy the new solution in order to be sure your upgraded features actually take.


Avoid the -allcontenturls switch – When deploying and retracting a web application targeted solution, deploy or retract it only to those web applications that will use it … thus preventing unnecessary recycling of application pools. I was being lazy in my retraction script and instead of specifying the particular web application url, I used the -allcontenturls switch to retract my solution, hoping SharePoint would be smart enough to recycle only the application pools of the web applications the solution was actually retracted from. Bad assumption. They all get recycled.




A Big Gotcha that Got Me If you are upgrading a web application targeted solution using the retract, remove, add, deploy strategy mentioned above and your web application scoped Features have associated Feature Receivers, then you must recycle the Central Administration application pool after removing the old solution and before adding the new solution if you intend to use the Central Admin Web application features page to activate your solution’s Features. In this case, it is the Central Administration application pool that executes your web application scoped Feature Receivers, and if not recycled, it will continue to use the loaded cached old versions of assemblies updated by your solution.


The same also goes for powershell. If within a powershell console you deactivate a Feature having a Feature receiver, the assembly containing the Feature receiver will be loaded and cached by the powershell App domain. After retracting, removing, adding, and redeploying the solution in the same powershell console, it will still be the previous version of the assembly that is cached. If you were to attempt to script the activation of your Feature, your updated Feature receiver’s code is never executed, rather the previous version from the cached assembly is used. To get around this dilemma, you can either increment your assembly version or start a new powershell console before deploying and activating your updated solution’s Features.


Wednesday 18 April 2012

List of SharePoint 2010 Training Videos

Following is a list of SharePoint 2010 videos from simple to complex...
       
Introduction to SharePoint

Videos,
Very high-end, introductory. 
microsoft sharepoint

Learning Snacks,
Introductory, What's new.
microsoft learning

       
 
E-Learning Clinics, Free two-hour clinics, one for Developers, one for IT Pros. microsoft learning
       
For IT Professionals

Getting Started for IT Pros,
Install, Backups, Architecture, Optimization, more...
Technet

"How Do I" Videos,
SMS messaging, Granular restore, Managed metadata service, more...
Videos are listed at the bottom of the page.
Technet


Advanced IT Pro Training,
Architecture, Search, Management, more...
Technet
       
 
SharePoint 2009 Conference videos, Mostly demonstrative, from the 2009 conference, links to the conference. msdn
       
For Developers

SharePoint Training,
New database schema for Lists, Site-level workflow, PerformancePoint Services, Sandboxed solutions, Claims-based authentication, Best Practices, Migrating old solutions to 2010, more (with many labs)...
channel 9

Get Started Developing on SharePoint 2010,
Web Parts, Server-side and client-side object models, Silverlight, more...
msdn

Advanced SharePoint Developer Training,
Business Continuity Services, Communities, Application Lifecycle Mgmt., more...
msdn

Office 2010 Developer Videos,
Access Web Databases, Word Services, Excel Services, client-side BCS, more...
msdn

Office 2010 Training Course,
InfoPath, Office Web Services, Open XML, more (with many labs):
channel 9

Various topics, 
So much information here; www.msdev.com is a wonderful site! SharePoint, BI, Visual Studio, SQL Server, Office, more...
msdev

Various topics,
Almost 200 developer videos in the SharePoint Developer Center. Many videos are over 60 minutes.
bing
       
 
And of course... our most loveble friend :) SharePoint videos, google

SharePoint 2010 Feature Changes Document Titles in Search Results

SharePoint 2010 has a interesting feature which you may not know about. It's called Optimistic Title. It's part of the Office Search engine within SharePoint. What it does is determine a new, hopefully more relevant title for your documents to be displayed in your search results based on document properties or the actual contents of the document (i.e. Text within the file). As you might expect this is closely tied to the Office document formats such as Word, PowerPoint, Excel, OneNote, and Visio. Your end users may report that the titles that they see for search results differ greatly from the file name or the actual title of the document. This is particularly evident with PowerPoint files where the name of the first slide is often used. The behavior is not entirely predictable. Different results can be expected from Office 2007 and Office 2010 created files and even those created in earlier versions of Microsoft Office.

If you want to change this functionality you need to actually go and edit the registry on your Search role server(s) within your SharePoint farm, restart the osearch14 service and then do a full crawl. The key you want to modify is the EnableOptimisticTitleOverride. The default setting is 1. Change it to 0 to disable the feature.

Monday 16 April 2012

Javascript Remove a parameter from the query sring if found in current url

This Javascript function removes the supplied parameter from the query string if it is present in the current url. This is done by converting the query string into an array of parameters and values, then rebuilding the final string to exclude the parameter supplied to the function. The browser is then redirected to the current page with the new query string.
       
function removeParameter(parameter)
{
   //Get Query String from url
   fullQString = window.location.search.substring(1);
   
   paramCount = 0;
   queryStringComplete = "?";

   if(fullQString.length > 0)
   {
       //Split Query String into separate parameters
       paramArray = fullQString.split("&");
       
       //Loop through params, check if parameter exists.  
       for (i=0;i<paramArray.length;i++)
       {
         currentParameter = paramArray[i].split("=");
         if(currentParameter[0] == parameter) //Parameter already exists in current url
         {
            //don't include existing (will be appended to end of url)
         }
         else //Existing unrelated parameter
         {
            if(paramCount > 0)
               queryStringComplete = queryStringComplete + "&";
           
            queryStringComplete = queryStringComplete + paramArray[i];
            paramCount++;
         }
       }
   }
   
   window.location = self.location.protocol + '//' + self.location.host + self.location.pathname + queryStringComplete;
}

       
 

Javascript Get the value of the specified Query String Parameter

This Javascript function checks the address of the current page for the supplied query string parameter. If found, the value of the parameter is used, if the parameter is not found, false is returned. See also: checkParemeterExists(), which returns true or false if the specified parameter is found or not.
       
function getParameter(parameter)
{
   fullQString = window.location.search.substring(1);
   paramArray = fullQString.split("&");
   
   found = false;
   for (i=0;i<paramArray.length;i++)
   {
     currentParameter = paramArray[i].split("=");
     if(currentParameter[0] == parameter)
        return currentParameter[1];
   }
   return false; //Not found
}
       
 

Javascript Check if Query String Parameter Exists in current URL

This Javascript function checks if the parameter supplied exists in the query string. If the parameter supplied is found in the query string of the current URL, the function will return true. If the parameter is not found, false is returned. See also: getParameter() - This function returns the value of the parameter if found, and false if it is not found which can be used instead of the checkParameterExists() function below
       
function checkParemeterExists(parameter)
{
   //Get Query String from url
   fullQString = window.location.search.substring(1);
   
   paramCount = 0;
   queryStringComplete = "?";

   if(fullQString.length > 0)
   {
       //Split Query String into separate parameters
       paramArray = fullQString.split("&");
       
       //Loop through params, check if parameter exists.  
       for (i=0;i<paramArray.length;i++)
       {
         currentParameter = paramArray[i].split("=");
         if(currentParameter[0] == parameter) //Parameter already exists in current url
         {
            return true;
         }
       }
   }
   
   return false;
}

       
 

Friday 13 April 2012

Customize sharepoint notification bar


Sharepoint 2010 site provides an area called notification bar. This bar appears when you open Edit control box. Using sharepoint client side API, you can use it. Just paste the below code in content editor web part.


<script type="text/javascript">
var notifyid;
function CreateNotification() {
notifyid = SP.UI.Notify.addNotification(" My HTML Notification ", true, "My Tooltip", "HelloWorld");
alert("Notification id: " + notifyid);
}
function RemoveNotification() {
SP.UI.Notify.removeNotification(notifyid);
}
</script><input onclick="CreateNotification()" type="button" value="Create Notification"/> <br/><input onclick="RemoveNotification()" type="button" value="Remove Notification"/>

Change display name of sharepoint user


You can use below powershell command to change sharepoint user display name.


Set-SPuser -identity "User name" -DisplayName "Display Name" -web Web url


Note: for AD user username would be like domain name\username. For FBA user it would be like i:0#.f|providername|username (You can get the exact username from My Settings page.

In case you get access denied while changing the display name, run powershell as administrator/Farm admin. You can get this option by pressing shift key then right click on Sharepoint powershell management console icon.


The password supplied with the username was not correct sharepoint


Recently I encountered an error while creating web application from central admin site

"The password supplied with the username was not correct. Verify that it was entered correctly and try again".

The reason is that administrative password may have been modified but SharePoint farm is still using the old administrative credential.

To fix this issue execute below stsadm command:


stsadm -o updatefarmcredentials -userlogin <domain\username> -password <newpassword>

Tuesday 27 March 2012

The Best Way to Add Custom JavaScript and jQuery to SharePoint

During extensive SharePoint user interface customization you'll likely encounter a scenario where you need to make a web part or user control do something it was not intended to do or have a look that cannot be accomplished using the CSS hooks provided out-of-the-box. The solution is to create a custom master page and include a reference to a JavaScript file where you can modify the Document object. While straight JavaScript will do, I prefer to use the jQuery JavaScript library, which is far more robust, easier to use, and allows for plugins. Follow the steps below to add jQuery to your master page.
       
Go to jquery.com and download the latest jQuery library to your desktop. You want to get the compressed production version, not the development version.
Open SharePoint Designer (SPD) and connect to the root level of your site's site collection.
In SPD, open the "Style Library" folder.
Create a folder named "Scripts" inside of the Style Library.
Drag the jQuery library JavaScript file from your desktop into the Scripts folder.
In the Scripts folder, create a new JavaScript file and name it (e.g. "actions.js").
Open your master page file in SPD.
Within the <head> tag of the master page, add a script reference to the jQuery library just above the content place holder named "PlaceHolderAdditonalPageHead" (and above your custom CSS references, if applicable) as follows:
<script src="/Style%20Library/Scripts/{jquery library file}.js" type="text/javascript"></script>
Immediately after the jQuery library reference add a script reference to your custom scripts file as follows:
<script src="/Style%20Library/Scripts/actions.js" type="text/javascript"></script>
       
 
Your custom master page now includes jQuery and a reference to your custom scripts file where you can add jQuery scripts. SharePoint includes a number of JavaScript files throughout the site, so be careful that the scripts you add do not conflict with SharePoint's; the jQuery library itself does not conflict with SharePoint.

The Best Way to Add Custom CSS to SharePoint

To thoroughly customize your SharePoint site, you'll need to use a custom CSS. SharePoint offers a way to specify a single CSS file to use via the "Master page" settings for the site. However, using this approach still limits you to customizing only those IDs and classes that are included on the pages by SharePoint. Moreover, using this setting applies to both site and system pages, which may not be desirable. With these downsides in mind,Follow the steps below to include a custom CSS file in your master page.
       

1. Open SharePoint Designer (SPD) and connect to the root level of your site's site collection.
2. In SPD, open the "Style Library" folder.
3. Create a new CSS file and name it (e.g. "customstyles.css").
4. Open your master page file in SPD.
5. In the  tag add a link to your custom CSS just above the content place holder named "PlaceHolderAdditonalPageHead" as follows:
<link href="/Style%20Library/customstyles.css" rel="stylesheet" type="text/css" />

       
 
Your custom master page is now using your new CSS file in addition to all of the CSS files SharePoint uses out-of-the-box. The idea is that you are taking advantage of the "cascading" property of cascading style sheets by layering your custom styles on top of what SharePoint creates in order to alter the SharePoint look-and-feel as desired—like a skin.

How to Create a Custom SharePoint Master Page

The first step in customizing your SharePoint site is to create a custom master page. The following steps will help you do just that (please note there are differences indicated between SP 2007 and SP 2010).
       

1. Open SharePoint Designer (SPD) and connect to the root level of your site's site collection.
2. In SPD, open the "_catalogs" folder, then open the "masterpage" folder.
3. Identify the out-of-the-box (OOTB) most like your ultimate design.
    i)(SP 2007) If your SharePoint's site design is to be fixed-width and centered on the page, select BlueBand.master and copy it.
   ii)(SP 2007) If your SharePoint's site design is to be a liquid layout that fills the page regardless of the user's screen resolution, select default.master and copy it.
  iii)(SP 2010 beta) You want v4.master.
4. In SPD, right-click on the master page you want to duplicate and select "Copy," then paste it back into the same folder.
5. Rename the new file something project-specific.  For instance, if this master page is to be used on the sales portal, you might rename the new master page SalesPortal.master.
6. Publish and approve the new master page.
7. In your browser, navigate to your site's Site Settings page.  Under the "Look-and-Feel" column click "Master page."
8. Select your new master page as the site master page (the need to set the system master page will vary by project).  Save the settings change.
   
Your site is now using the new master page you created. From here you modify the master page to your liking, including adding custom CSS and custom JavaScript and jQuery.

Covariance and Contra variance in .Net 4.0 Framework

Covariance and Contra variance in Delegates: There has always been confusion for me to understand the concept of Covariance and Contra variance. And today when I scaled down to this definition and example to understand them, it has become really easy to understand it. So here I am sharing with you all. Covariance: In earlier versions of Visual C#, a delegate method must be exactly matched to a delegate signature. To create a successful match, the parameter type and the return type of the delegate method must be identical to the parameter type and the return type of the delegate signature. When we talk about covariance in .net, we say it permits a method to have a more derived return type than what is defined in the delegate. In Visual C# 2005, you may notice that more than one match can be established when you work in an inheritance context. In this scenario, delegate behavior may change.

When you compile and run this code sample in the Microsoft .NET Framework 2.0, you receive a result of "String". In the .NET Framework 2.0, both the M method in the base class and the M method in the derived class can be matched to the delegate signature. However, overload resolution rules decide that the one method in the most specific class wins the match. In this example, the method that is in class B wins the match. Covariant type parameters enable you to make assignments that look much like ordinary polymorphism. Polymorphism enables you to assign an instance of derived class to a variable of type base class. Similarly, because the type parameter of the IEnumerable interface is covariant, you can assign an instance of IEnumerable to a variable of type IEnumerable, as shown in the following code.

This gave an error “Cannot implicitly convert type” in Framework 2.0. But it is compiles without error in Framework 4.0. The List class implements the IEnumerable interface, so List implements IEnumerable. The covariant type parameter does the rest. Contra variance: When a delegate method signature has one or more parameters of types that are derived from the types of the method parameters, that method is said to be contra variant. As the delegate method signature parameters are more specific than the method parameters, they can be implicitly converted when passed to the handler method. Contra variance therefore makes it easier to create more general delegate methods that can be used with a larger number of classes

Now have you ever imagine that IComparer and IComparer are one and the same. It is possible in Framework4.0 because the interface IComparer has become IComparer. The “in” indicates that the parameters are restricted to occur only in input positions. Let’s go for an example to explain the contra variance in Framework4.0.

To weigh animals, we will create WeightComparer which will implement IComparer interface; which in turn will enable us to use the Sort() method on list object.

Now we will check by adding making a list of animals and sorting it and making a list of elephants and sorting it using the Sort() method of IComparer.

In the above code prior to .Net 4.0 Elephants list could not have been sorted it gives error “Cannot convert from 'WeightComparer' to 'System.Collections.Generic.IComparer”. Above samples have cleared the concepts of covariance and contra variance; also have explained the enhancement in these concepts in .Net Framework 4.0.

Error occurred in deployment step 'Add Solution': Property 'SiteUrl' contains an invalid URL

While deploying custom BDC from visual studio, we may receive error "Error occurred in deployment step 'Add Solution': Property 'SiteUrl' contains an invalid URL".

Workaround:
1. Edit feature template file say Feature1.Template.xml
2. add following property under <properties> element
<Property Key='SiteUrl' Value='http://your_site_url'/>

Tuesday 20 March 2012

Gmail in C#

Use C# to send mail using Google’s Gmail. If you’ve ever wanted to send email using your Gmail account then take a look.


       
using System.Net;
using System.Net.Mail;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Please Enter UserId: ");
            string username = Console.ReadLine();

            Console.WriteLine("Please Enter password ");
            //Console.OutputEncoding = Encoding.Unicode;

            string password = ReadPassword();

            Class1 gmail = new Class1(username,password);
            MailMessage msg = new MailMessage("From Address", "To Address");
            msg.Subject = "This is test mails from .net Program";
            msg.Body = "This is the test Email using system.net namespace within a .net program";
            gmail.Send(msg);
        }
        public static string ReadPassword()
        {
            string password = "";
            ConsoleKeyInfo info = Console.ReadKey(true);
            while (info.Key != ConsoleKey.Enter)
            {
                if (info.Key != ConsoleKey.Backspace)
                {
                    Console.Write("*");
                    password += info.KeyChar;
                }
                else if (info.Key == ConsoleKey.Backspace)
                {
                    if (!string.IsNullOrEmpty(password))
                    {
                        // remove one character from the list of password characters
                        password = password.Substring(0, password.Length - 1);
                        // get the location of the cursor
                        int pos = Console.CursorLeft;
                        // move the cursor to the left by one character
                        Console.SetCursorPosition(pos - 1, Console.CursorTop);
                        // replace it with space
                        Console.Write(" ");
                        // move the cursor to the left by one character again
                        Console.SetCursorPosition(pos - 1, Console.CursorTop);
                    }
                }
                info = Console.ReadKey(true);
            }


            // add a new line because user pressed enter at the end of their password
            Console.WriteLine();
            return password;
        } 
    }
    public class Class1
    {
        public string Username { get; set; }
        public string Password { get; set; }

        public Class1(string username, string password)
        {
            Username = username;
            Password = password;
        }

        public void Send(MailMessage msg)
        {
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(Username, Password);
            client.Send(msg);
        }
       
    }
}
       
 

Friday 2 March 2012

Full trust proxy in SharePoint sandbox solution


You know that sandbox solution in SharePoint 2010 has certain limitation like
·         It doesn’t allow using web services.
·         You can’t access SharePoint web controls
·         It won’t allow executing code that runs under elevated privileges etc…
So, basically sandbox solution provides restricted environment to execute your code for specific SharePoint site.

What if you want to execute a web service inside a sandbox solution? The solution is to write a full trust proxy. Let’s solidify this requirement by creating a web part that gets the data from a web part. I’m going to write a simple sandbox solution that displays xml string returned from Lists.GetList(“your list name”) method.

There are three parts of this code.
·         Create a proxy: This will execute your sharepoint web service and return xml
·         Register full trust proxy.
·         Write a web part

Create a proxy
1.      Add a class library project to your solution say “RVProxy”.
2.      Add a class file inside it say “ServiceHelper.cs”.
3.      Copy and paste below code to your ServiceHelper.cs file

       
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.UserCode;
using System.Xml;

[assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]
namespace RVProxy
{
    public class ServiceHelper:SPProxyOperation
    {
        public override object Execute(SPProxyOperationArgs args)
        {
            if (args != null)
            {
                ListArgs lstArg = args as ListArgs;
                string listName = lstArg.ListName;
                RVListOperation.Lists lst = new RVListOperation.Lists();
                lst.PreAuthenticate = true;
                lst.Credentials = System.Net.CredentialCache.DefaultCredentials;
                XmlNode node = lst.GetList(listName);
                return node.InnerXml;
            }
            else
            {
                return null;
            }
        }
    }

    [Serializable]
    public class ListArgs:SPProxyOperationArgs
    {
        public ListArgs(string listName)
        {
            this.ListName = listName;
        }
        public string ListName
        {
            get;
            set;
        }

    }
}

In the above code, note that assembly has been tagged with attribute [assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]. This tells the compiler to execute the assembly in partially trusted environment.

Class ServiceHelper inherits SPProxyOperation class. Implement its Execute() method. This method contains all the code that runs under trusted mode.

Class ListArgs serves as an input argument sent to the proxy. Don’t forget to decorate this class with attribute  [Serializable]


Now your proxy is ready. You need to register this as full trust proxy.
Register full trust proxy
1.      Put the “RVProxy” dll into the GAC.
2.      Register this dll as full trust proxy. You can either register this using powershell script or using SharePoint object model. I’ll explain the second one here
a.       Create a windows application
b.      Use below code to register, unregister or view registered assemblies:
Register
       
private void RegisterFullTrustProxty(string assemblyName, string typeName)
        {
            label1.Text = "";
            lblRegisteredProxy.Text = "";
            SPUserCodeService service = SPUserCodeService.Local;
            if (service != null)
            {
                SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(assemblyName, typeName);
                service.ProxyOperationTypes.Add(getEventLogItemCreationOperation);
                service.Update();
                label1.Text = "Updated successfully!";
            }
            else
            {
                label1.Text = "Update failed!";
            }
        }
For e.g RegisterFullTrustProxty("RVProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d35956c4346f2f1"
, "RVProxy.ServiceHelper"
);

Unregister
private void UnregisterFullTrustProxty(string assemblyName, string typeName)
        {
            label1.Text = "";
            lblRegisteredProxy.Text = "";
            SPUserCodeService service = SPUserCodeService.Local;
            if (service != null)
            {
                SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(assemblyName, typeName);
                service.ProxyOperationTypes.Remove(getEventLogItemCreationOperation);
                service.Update();
                label1.Text = "Removed succesfully!";
            }
            else
            {
                label1.Text = "Remove failed!";
            }
        }

View all registered assemblies
private void ViewAllRegisteredProxy()
        {
            label1.Text = "";
            lblRegisteredProxy.Text = "";
            SPUserCodeService service = SPUserCodeService.Local;
            if (service != null)
            {
                int count = service.ProxyOperationTypes.Count;
                lblRegisteredProxy.Text = "Proxy count: " + count.ToString() + Environment.NewLine ;
                foreach (SPProxyOperationType item in service.ProxyOperationTypes)
                {
                    lblRegisteredProxy.Text += "AssemblyName: " + item.AssemblyName + Environment.NewLine + "TypeName: " + item.TypeName + Environment.NewLine;
                }
            }
        }

Write the web part
You have created the proxy as well as registered as a full trust proxy. Now it’s time to utilize this proxy in your web part code. I’m pasting here a sample code that utilizes the above proxy:


       
[ToolboxItemAttribute(false)]
    public class DemoPart : WebPart
    {
        Label lbl = new Label();
        Button btnTest = new Button()
        {
            Text = "Get List"
        };
        public DemoPart()
        {
            btnTest.Click += new EventHandler(btnTest_Click);
        }

        void btnTest_Click(object sender, EventArgs e)
        {
            string assemblyName = "RVProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0d35956c4346f2f1";
            string typeName = "RVProxy.ServiceHelper";
            string listInfo = SPUtility.ExecuteRegisteredProxyOperation(assemblyName, typeName, new  ListArgs("Tasks")).ToString();
            lbl.Text += listInfo;
        }
        protected override void CreateChildControls()
        {
         
            lbl.Text = "Hi Ranvijay, here is your web part under sandbox solution.<br /><br />";
         
            Controls.Add(lbl);
            Controls.Add(btnTest);
        }

Note: The proxy runs under SPUserCodeService.exe service. So, every time you make changes to your proxy and redeploy the dll to GAC, you will need to restart the “SPUserCodeV4”. To stop use "net stop SPUserCodeV4" and to start use "net start SPUserCodeV4"


SharePoint chart using excel services


Sometimes there is a need to display chart embedded in excel sheet. SharePoint provides REST API for this. Here are the steps to display excel chart.

       

1.      Upload your excel file into the document library say “Shared Documents”.
2.      Add a content editor web part to the page where you want to display the chart.
3.      Now edit the HTML source of content editor web part and put below content

<img src="/_vti_bin/ExcelRest.aspx/Shared Documents/Book1.xlsx/Model/Charts('Chart 1')" alt=""/>​

Note: please verify the service by typing the url in browser something like
http://<your server>/_vti_bin/ExcelRest.aspx/Shared Documents/Book1.xlsx/Model/Charts('Chart 1')

“Chart 1” is the name of chart. You can set the name of the chart as follows:
a.       Open excel sheet.
b.      Click on the chart.
c.       Go to Layout menu. You will see the Chart Name box at the top right ribbon.

4.      Save the content editor web part. This should render your chart. For details about the REST API please follow Sample URL For Excel Services REST API

Why SharePoint site's first load is very slow

The sharepoint site is very slow when we access it first time. After that the response time is good. The reason is compilation and caching which takes time after application pool is recycle. To handle this we need to warm up the server whenever recycle happens. Here is a good link that explains about server warm up: http://blogs.msdn.com/b/joelo/archive/2006/08/13/697044.aspx 


So the idea is to schedule a job that pings the server whenever reset occurs.

Popular Posts