Friday, April 8, 2011

jQuery - Using jQuery to attach regular expression validation(no special character to be added in Title field) to a SharePoint list form field

Write the below code on the New Form of the SharePoint list.

<script type='type/javascript'>
  
  _spBodyOnLoadFunctionNames.push("attachToTitleField");
  
  function attachToTitleField() {
   var titleField = $('input[title=Title]'); //Find title field on the form
   
   //Add a DIV element to provide a place for an error message from the RegEx validation
   titleField.parent().append("<div id='GilesH_titleValidation'></div>");
  
  //Use jQuery to attach the validateAlphanumeric function on keyup
  titleField.keyup(function() {
   validateAlphanumeric(titleField.val());
  });
 }

 function validateAlphanumeric(stringValue) {
  
  //Allows alphanumeric only for the 1st character
  //after the 2nd character, alphanumeric and spaces allowed upto 255 characters
  var regExpressionValue = /^[0-9A-Za-z][0-9A-Za-z\s]{0,255}$/; 
  var re = new RegExp(regExpressionValue);
   
  if (stringValue.match(re)) {
   //alert("Successful match"); //Debug
   
   //Allow Save
   $('a[id=Ribbon.ListForm.Edit.Commit.Publish-Large]').attr("style", "display:inline-block;"); //Show Ribbon Save Button
   $('input[id*=SaveItem]').attr("disabled",""); //Re-enable Form Save Button
   
   //Blank Error Message
   $('div[id*=GilesH_titleValidation]').text(""); //Blank custom error message
  } else {
   //alert("No match"); //Debug
   
   //Stop Save
   $('a[id*=Ribbon.ListForm.Edit.Commit.Publish-Large]').attr("style", "display:none;"); //Hide Ribbon Save Button
   $('input[id*=SaveItem]').attr("disabled","true"); //Disable Form Save Button
   
   //Provide Error Message
   $('div[id*=GilesH_titleValidation]').text("The title you have entered is invalid. Only alphanumeric characters and spaces are allowed.");
  }
 }

 </script>


N.B: Add an extra <DIV> element next to the Title field to notify the user of what is going on.

Monday, April 4, 2011

LINQ - Dynamic sort with LINQ

Dynamic sorting using LINQ. City class is defined below.

public class City
{
   public string Name { get; set; }
   public string Country { get; set; }
}
The collection is initialised using this code
List<City> cities =
           new List<City>
           {
               new City{ Name = "Sydney", Country = "Australia" },
               new City{ Name = "New York", Country = "USA" },
               new City{ Name = "Paris", Country = "France" },
               new City{ Name = "Milan", Country = "Spain" },
               new City{ Name = "Melbourne", Country = "Australia" },
               new City{ Name = "Auckland", Country = "New Zealand" },
               new City{ Name = "Tokyo", Country = "Japan" },
               new City{ Name = "New Delhi", Country = "India" },
               new City{ Name = "Hobart", Country = "Australia" }
           };

A typical example of applying a sort will be to write such a query.
var collection =
   from c in cities
   orderby c.Country
   select c;



Here we are sorting the collection on country. Note this is static in nature.Code above can only sort by country. If we want to sort by city name then  we have to write another query and maybe use a conditional construct such as if or switch and write a method which takes in a parameter. While this will work, it is not the best way to do it. LINQ gives us the ability to make our code dynamic. we can provide sort functionality for the query by writing a method which takes in a Func<TElement, TKey> delegate. This delegate is used by the OrderBy extension method. 

public static void Sort<TKey>(List<City> cities, Func<City, TKey> selector)
{
   var sortedCollection =
       from c in cities
       orderby selector(c)
       select c;
   foreach (var item in sortedCollection)
   {
       Console.WriteLine(item.Name);
   }
}


This method can be called by passing in the cities collection which has been initialised earlier.
Sort(cities, c => c.Name);
we  can also sort by country without changing my query. To sort by country we just need to call my sort method like this.
Sort(cities, c => c.Country);

Saturday, February 12, 2011

Sharepoint - Empty Recycle Bin


Introduction:
With SharePoint User level recycle bin(that is displayed in Quick Launch), there is no way to ‘Empty’ the recycle bin in a single go. We have this option in Site Collection Recycle Bin. May be this is done deliberately to prevent users from deleting all items by accident! This is definitely a fallback from developers perspective.
Description:
A way to Empty  the recycle bin without going through the pain of manually deleting each of the files or selecting the files and clicking on the ‘Delete Items’ button.
·         Open your SharePoint Recycle Bin Page by clicking on the Recycle Bin icon on the Quick Launch.
·         Simply copy the below JavaScript statement into the address bar and click Enter.
javascript:emptyItems();
Note
Be careful as all of the items will not be to sent to Site Collection Recycle Bin. This a good tip for development phase.

Thursday, February 3, 2011

SharePoint 2010 - Object Model Code on External List - BDC Exception Solution


When you're working with the Object Model Code on an external list in SharePoint 2010 you might stumble upon the following problem:
Microsoft.BusinessData.Infrastructure.BdcException: The shim execution failed unexpectedly - Proxy creation failed. Default context not found..
---> Microsoft.Office.SecureStoreService.Server.SecureStoreServiceException: Proxy creation failed. Default context not found.
This is caused by the fact that there is no default SPServiceContext, meaning SPServiceContext.Current is always null. The problem is that, for example, when you are working with methods like listitems.getdatatable() you need a current context, since the underlying code will use SPServiceContext.Current
To solve this issue you can create a code block that will fill the current SPServiceContext:












using (var site = new SPSite("http://localhost"))
{
// Get context for the site.
var context = SPServiceContext.GetContext(site);
// Assign context in SPServiceContext.Current
using (var scope = new SPServiceContextScope(context))
{
...
listitems.getdatatable()
}
}
After closing the using codeblock your current SPServiceContext will be empty again.

Friday, January 14, 2011

Hello World Webpart

Select New Project… from the Startup page to display the New Project dialog box. Expand the SharePoint node and select 2010 to display the available project templates, as shown in Figure 1.
Figure 1: Available project templates


Visual Studio 2010 offers templates to support the most common SharePoint development projects. Select the Visual Web Part template and click OK to start the SharePoint Customization Wizard. The wizard prompts you for the URL of the SharePoint site to be used for deployment and debugging and lets you choose between farm and sandboxed solution types.
Farm solutions deploy to the SharePoint farm and have full access to the SharePoint API and all SharePoint resources. In contrast, sandboxed solutions deploy to the site collection, have limited access to the SharePoint API, and can only access data within the site collection. This lets farm administrators allow sandboxed solutions, which won't impact the entire farm, to be deployed to the server. Visual Web Parts can be deployed only in farm solutions, so the sandboxed option isn't available in this case.
After you create the project, the Visual Web Part opens in the default Source view. Click the Design tab to switch to a WYSIWYG view. Regardless of which view you prefer, you can drag and drop controls from the toolbox onto the designer.
Now I'll build a typical "Hello World" Web Part. Click the designer near the top and type "My Hello World Web Part." You'll notice you have all the text tools, such as font size and color, in the menu. Under the text, drag a label and button control onto the designer. Figure 2 shows what the designer will look like so far.
Figure 2: The designer so far

Double-click the button to display the code behind the form. Add a using directive to access the SharePoint object model (a reference to the Microsoft.SharePoint.dll assembly is included in all SharePoint projects).
using Microsoft.SharePoint;

Next, add the following code to the button event handler Button1_Click. This code gets the current user for the SharePoint site and sets the label to the LoginName.

SPUser user = SPContext.Current.Web.CurrentUser;
Label1.Text = user.LoginName;

With the code now complete, set a breakpoint in the first line of the event handler. It's time to deploy the Web Part and check whether it works as expected. Press F5 to instruct the project system to build the assembly, package the feature, and deploy the solution to the SharePoint site. In addition, the debugger will be attached and the browser will launch to display the SharePoint site.
When the browser launches, you're taken to the home page of the site you specified during project creation. Click on the Site Actions menu at the top left of the page, and choose More Options. In the dialog page that appears, select the item Web Part Page and click Create. Enter HelloWorld as the Name, and leave the Layout Template selected as the default. Change the Document Library to Shared Documents and click the Create button. In the header section of the new page, click Add a Web Part to display the Web Part picker. In the Categories section, select Custom, and in the Web Parts section select the Web Part VisualWebPart1. Click the Add button to add the Web Part to the page, and then click the Stop Editing button on the SharePoint ribbon. Figure 3 shows the Web Part displayed on the HelloWorld page in the browser.
Figure 3: The HelloWorld page

Issue(can be encountered)

Error : 
image

Solution:
For example, you may consider custom document library to store the images for your solution, etc.
However, sometimes we need to get rid from sandboxed solution. Then we need to change the project type into non-sandboxed solution. To change project type to non-sandboxed solution,
1. Click on project property
2. Set Sandboxed Solution = False.
image





Sunday, January 9, 2011

SharePoint 2010 - Best Practices Document: Document Library


These are the things you really must do for every document library:
  1. Require Check Out on any document library where multiple users might make changes.
    • Check out is supported by, but not enforced on, document libraries unless you make it that way!
  • Add the Checked Out By column to the default view of the library.
    • Those way users can see easily who has a document checked out. If you hover over the Checked Out icon, it tells you in a tip, but that's not exactly a "discoverable" little gem.
  • Train users how to check out, check in, and discard check out.
    • Be sure they understand that the changes they make can't be seen by other users until checked in.
    • Do they understand the purpose of Keep document checked out after checking in? They check in the document to make their changes visible, but maintain an editorial lock to make more changes.
    • If there is a required column (property/attribute/metadata) that's blank, the document can't be checked in. Train users how to deal with this. This is particularly challenging if you're using Internet Explorer (IE) to upload documents. You can upload them, but they won't be visible to others until checked in, and they can't be checked in until required columns are complete. So after uploading, open the SharePoint document library in IE and fill in those columns! What solutions have YOU found in your organization to this problem? I've yet to uncover a really great answer. DO YOU HAVE ONE?
  • Create a permission level that gives someone the Override Checkout permission.
    • Take the burden off of yourself and your IT team to check documents in when users forget to do so before going on vacation.
    • Train your "check in managers" and your users so that they know what it means when a document has been checked in "on behalf" of someone else. If that someone else was using Microsoft Office 2007's SharePoint Drafts folder, there are likely to be changes in the local copy of the document that were not included when the document was checked in. At some point, the two versions (the server's copy and the user's local copy) will need to be reconciled.
  • Decide whether to use versioning.
    • If you want to restrict who can see drafts, use minor versions. Most of the time your processes will require that. If not, there's no real point in using minor versions.
  • If you're using versioning, set retention limits.
    • By default, SharePoint keeps all versions, and these aren't bitwise differential versions—they're the full version. With large documents, even a small but active library can eat up your database in a hurry!
  • Configure views that will help users navigate libraries effectively and find the documents they require.
    • Use folders only if you need to scope unique permissions on documents or if you need to make a subset of documents easily offline-able by Microsoft Outlook.
    • If your library has more than 2,000 items, be sure you remove the out-of-the-box default view, which shows all items. Add views with filters so that no view returns more than 2,000 items. Paging and grouping doesn't count. You must use a filter. (BTW, in its sneak peek of SharePoint 2010, Microsoft announced that SharePoint 2010 will have large-list support, so this won't need to be done much longer.)
Then there are things that take a bit more time and configuration but really pay off:
  1. Create content types for documents that belong in a library, and upload a template for that document into the content type. Users can then click the NEW button on the library, choose the document type, and a new document with the right template appears.
  2. Push navigation aids to users: Add Favorites to users' Internet Explorer (Group Policy Shortcut Preferences) and Network Places (XP) or Network Locations (Vista), which can be created by an administrator (separately for XP and Vista), uploaded to file shares, then distributed by copying into users' systems (%userprofile%\nethood in XP and %appdata%\Microsoft\Windows\Network Shortcuts in Vista).
  3. Integrate custom columns (metadata) into Microsoft Word 2007 documents using Quick Parts. You can "link" content in your document with SharePoint metadata.

Wednesday, January 5, 2011

SQL - to call a sp in another sp


Inside your procedure X you can do something like :

"EXECUTE PROCEDURE Y (ID) RETURNING_VALUES RESULT;"

but you can store all the code from your procedures into one using IF :

" IF (X1 HAPPENS) THEN
EXECUTE PROCEDURE Y(ID)
ELSE IF (X2 HAPPENS) EXECUTE PROCEDURE Z(ID)
ELSE IF (X3 HAPPENS) EXECUTE PROCEDURE W(ID);