SharePoint 2010 / 2013 ASP.NET 4.0

Saturday, September 20, 2014

Design Patterns Videos - (By Derek Banas)


I know, Its very difficult and tedious process to find information on internet.
I came across some very nicely explained videos on OOPS and Design patterns by Derek Banas. I would like to share the video links


https://www.youtube.com/playlist?list=PLF206E906175C7E07


Hope this helps.

Sunday, May 27, 2012

SharePoint Interview Questions and Answers: Basics

My next series of posts will be related to SharePoint Interview questions and answers. This will help most of you guys. What I am gonna do is - Simply take any topic in SharePoint and provide the list of questions and answers asked by the interviewer. I have some good amount of experience in interviewing the people, cause in my career many time I was on the interviewer's chair than interviewee.

Lets start with the SharePoint Basics:

1. What is Ghosting?
- page ghosting is an optimization used with site pages in which a single page template can be used to process multiple page instances across many different site. A page template, such as default.aspx, is compiled into an assembly dynamic-link library (DLL) and loaded into memory just once per Web application. When a user customizes a site page by using the SharePoint Designer and then saves those changes, a customized version of the page definition is stored in the content database.

2. SPVirtualPathProvider
- WSS stores storing customized versions of .aspx files and .master files inside the content database and retrieving them on demand when they are needed to process an incoming page request.
SPVirtualPathProvider is able to retrieve an ASP.NET page file from the content database, such as default.aspx, and then pass it along to the ASP.NET page parser.

3. Difference between Site pages and Application pages.
- Pages that support user customization are known as site pages. home page (default.aspx) is a site page. It supports user customization by using tools such as the SharePoint Designer.
Application page does not support customization. The standard Site Settings page (settings.aspx) is a good example of an application page. It can be accessed from any site, yet it does not support customization.
Application pages are deployed as physical files on the file system of the front-end Web server in a directory at the following path:
SharePoint 2007: c:\program files\common files\microsoft shared\
web server extensions\12\TEMPLATE\LAYOUTS {12 hive}
SharePoint 2010: c:\program files\common files\microsoft shared\
web server extensions\14\TEMPLATE\LAYOUTS 
{14 hive}
4. Why SafeControls entry required in web.config in SharePoint
- It determines what controls a user might place on a customized page. For example, imagine a scenario in which a site administrator tries to mount an attack by adding a server-side control to a site page and parameterizing it in a certain way. Safe mode allows the farm administrator to determine which controls can be used in pages that are processed in safe mode.

5. What are the Featutes?
- Features provide a mechanism for defining site elements and adding them to a target site or site collection through a process known as feature activation. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows. A feature consists of a directory created within a special WSS system directory:

c:\program files\common files\microsoft shared\web server extensions\12\TEMPLATE\Features
The directory for a feature contains one or more XML-based files that contain Collaborative Application Markup Language (CAML). Each feature directory contains a manifest file named feature.xml that defines the high-level attributes of the feature, such as its Id, Title, Description, Version, Scope, Hidden and ImageUrl. It also contains one or more additional XML files (elements.xml) that define the actual elements that make up the feature.
Feature Scopes:
The Scope defines the context in which the feature can be activated and deactivated. The feature we are creating has a scope equal to Web, which means it can be activated and deactivated within the context of the site. If you assign a Scope value of Site, your feature will then be activated and deactivated within the scope of a site collection. The two other possible scopes for defining a feature are WebApplication scope and Farm scope.
Feature EventReceivers:
Create a class that inherits from the SPFeatureReceiver class. As you can see, you handle events by overriding virtual methods in the base class such as FeatureActivated and FeatureDeactivating. There are also two other event handlers that fire when a feature is FeatureInstalled or FeatureUninstalled

6. What is site column?
- A site column is a reusable column definition that can be used across multiple lists. A site column defines the name for a column, its underlying field type, and other characteristics such as the default value, formatting, and validation. Advantage is that you can update the site column in a single place and have that update affect all the lists where the site column has been used.

7. What is Content Type?
- A content type is a flexible and reusable WSS type definition that defines the columns and behavior for an item in a list or a document in a document library.
You can also existing list columns to the list content types on the list. Also when you add columns directly to a list, and that list contains multiple content types, you can specify whether you want the new column to be referenced in all the content types on that list.

8. SharePoint Lists.
- At the heart of the core WSS architecture is the infrastructure for defining list types and provisioning list instances to store content. Document libraries, which play a vital role in creating WSS business solutions.
Following are the List Types. I have highlited some list types, which are majorly used in SharePoint Development:
List Type
Description
Document library
Used for collaborating on documents with support for versioning, check-in and check-out, and workflow. Includes support for deep integration with Microsoft Office.
Form library
Used to store XML documents and forms for use with Microsoft Office InfoPath.
Wiki page library
Used for collaborative Web pages based on wiki pages, which are dynamically generated and collaboratively edited Web pages.
Picture library
A specialized document library enhanced for use with pictures. Includes support for slide shows, thumbnails, and simple editing through Microsoft Office Picture Manager.
Announcements
Used for simple sharing of timely news with support for expiration.
Contacts
A list for tracking people and contact information, with support for integration into Microsoft Office Outlook and other WSS-compatible contacts applications.
Discussions
A simple list for threaded discussions with support for approval and managing discussion threads.
Links
A list for managing hyperlinks.
Calendar
A list for tracking upcoming events and deadlines. Includes support for integration and synchronization with Office Outlook.
Tasks
A list of activity-based items that can integrate with workflow.
Project tasks
An enhanced tasks list with support for Gannt chart rendering and integration with Microsoft Office Project.
Issue tracking
A list for tracking issues and resolution, with support for prioritization.
Custom list
An empty list definition for extending with custom columns, or created using Microsoft Office Excel spreadsheets.

SharePoint Object model code to access any list:
SPList list = null;
using (SPSite site = new SPSite("http://siteurl"))
{
      using (SPWeb web = site.OpenWeb())
{
string listName = "SampleList";
list = web.Lists[listName];
// list = web.GetList("/Lists/ SampleList"); This method is // useful, as no code change required when the list Title // changes.

SPListItem newItem = list.Items.Add();
newItem ["Title"] = "First Item";
newItem.Update();  
// You can use newItem.SystemUpdate(); if you don’t want  // update modified date and version.
}
}

To get specific results within a list, you can use the SPQuery object as follows: 
query.ViewFields = @"<FieldRef Name='Title'/><FieldRef Name='Expires'/>";query.Query =@"<Where><Lt><FieldRef Name='Expires' /><Value Type='DateTime'><Today /></Value></Lt></Where>";
SPList list = site.Lists["SampleList"];
SPListItemCollection items = list.GetItems(query); 
SPSiteDataQuery class can return items from many different lists through an entire site collection. hence queries run with the SPSiteDataQuery class are sometimes referred to as cross-site queries.
I have added some of the question which might help you guys...
I will update same post with more useful question and answers immediately...

Wednesday, April 25, 2012

Avoiding JavaScript and CSS stylesheet caching problems in sharepoint

Good news - Our application got new branding in this release, which changed my perception as a developer to see SharePoint applications. SharePoint is not only about C# and CAML other things like JS, CSS and HTML also plays major role in your application.

We mainly work on the business logic of the application but this time got chance to work with UI designers, and Changing look and feel of SharePoint is not a easy task as lots of tweaking is needed to overwrite existing styles dynamically applied by the SharePoint.

So let me introduce you the structure of our application, All JS, Stylesheets and images are placed inside the _layouts [14 hive\Layouts] folder. 
UI designer made some changes to apply branding on homepage and gave update files to me. I have merged all the files properly and deployed the application on the server. but changes are not reflected and UI is breaking. Called my fellow UI designer showed the issue. She performed hard refresh (CTRL + F5) this resolved all the issues. 
Root cause is the Browser caching for js and css files.
This raised another question in my mind I can perform hard refresh but in Production we cannot tell every user to perform hard refresh.

So here is the solution to above problem...
To avoid browser caching a file even after it is updated, simple change the linking URL format

<link href="/_LAYOUTS/ProjectName/mystyles.css" rel="stylesheet" type="text/css">link>
<script src="/_LAYOUTS/ProjectName/myscript.js" type="text/javascript"> script>


To:

<link href="/_LAYOUTS/ProjectName/mystyles.css?rev=<build-version>" rel="stylesheet" type="text/css">link>
<script src="/_LAYOUTS/ProjectName/myscript.js?rev=<random number>" type="text/javascript"> script>

Update this numbers whenever your file is updated, to avoid facing the same issue of not seeing updated CSS and JavaScript files by default.


Tuesday, April 10, 2012

ASP:Button OnClientClick and OnClick not working

Sometimes you face really strange scenarios in Development, I faced a very strange issue about Event handlers while development of simple application. It proves that its not always Developers fault for coding defects.

I was creating a Search module in our application where I want call OnClientClick event for validation and if the validation returns true then perform search on DataSource using OnClick event of the Search button.

I have created a JavaScript function for validation and called that method in OnClientClick event
function ValidateSearch()
{
    var flag = true;
    // JavaScript code for validation
    return flag;
}
following is the ASP.Net code for Search button.
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="ValidateSearch()" />

With above code it should call ValidateSearch() method first on click of Search button and based on the return value, it should call the Server-Side event.

Everything is OK, but above code didn't work, [Don't give up in such cases] 
I tried some other alternative like...

1) <asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="javascript:return ValidateSearch();" />

2) <asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="return ValidateSearch();" />

but still no Success.

Solution:
We have to explicitly return the result after checking the functions return value. 

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="if (!ValidateSearch()) { return false;};" />

Hope this helps you.

Tuesday, March 27, 2012

Add List Items with users identity (Created By) when using RunWithElevatedPriviledges delegate

We faced a situation when we have to elevate the read only users permission to add/update the list items in SharePoint list. To accomplish this we usually go for the RunWithElevatedPriviledges delegate, but the only disadvantage of this approach is if we add/update any item within this delegate, it will save that record with 'System Account' identity.

Following code can be used to overwrite the 'System Account' identity with current user's identity, So list item will display 'Created By' or 'Modified By' columns value as current user.

SPUser user = SPContext.Current.Web.CurrentUser;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
    {
        using (SPWeb web = site.OpenWeb())
        {
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists["TempList"];
            SPListItem listItem = list.AddItem();
            listItem["Title"] = string.Format("Hey {0}", user.LoginName);
            listItem["Editor"] = user;  // Modified By                    
            listItem["Author"] = user;  // Created By
            listItem.Update();
            web.AllowUnsafeUpdates = false;
        }
    }
});
 

Friday, March 9, 2012

Simplest way to get the strong name of an assembly

I found very interesting post which describes how to get strong name of the assembly without even opening the properties window of that assembly. I saw many fellow-developers are still not aware of this simple option that may make their life at least a bit easier, hence sharing this post.

Old Method:

Open the assembly in the GAC (c:\Windows\Assembly) and view its properties. Then form the strong name with assembly name, version and public key token.


Simplest method:

Open the assembly, select the assembly you need the strong name for, then from the Edit menu choose Copy Display Name menu item


Tuesday, March 6, 2012

Session State Service Configuration in SharePoint 2010

To enable ASP.NET session state, log on the Central Admin
Server using Farm Admin Account, and Either Run PowerShell command 
Enable-SPSessionStateService -DefaultProvision

to create service application with default
state. By default, this will create service application database with
“SessionStateService_<GUID>”, on the same database server where farm
configuration database is located using windows credentials of the logged in
user.

Or
 
Enable-SPSessionStateService -DatabaseServer YourDBServerName
-DatabaseName YourDBName

to create service application
with specific database name on non-SharePoint configuration database server.
For more details and additional parameters,
Reference link: http://technet.microsoft.com/en-us/library/ff607857.aspx




By enabling Session State Service on your farm,
It would create database on specified server:  SessionStateService_<GUID>


It would create SharePoint Server Session State Service in
Manage Service Applications, please make sure it is showing ‘Started’.


It would add module in all web applications on farm, Check
following entry in web.config:
<add name=”Session”
type=”System.Web.SessionState.SessionStateModule” />

<sessionState mode=”SQLServer” timeout=”60″
allowCustomSqlDatabase=”true” sqlConnectionString=”Data Source=<DatabaseServarName>;Initial
Catalog=SessionStateService_<GUID>;Integrated
Security=True;Enlist=False;Connect Timeout=15″ />


You have to manually update Web.Config file for the specific
SharePoint web application on all servers in the farm.  - <pages
enableSessionState=”true”


By performing above steps you can configure Session State service in your Web Application. Now 
you can user Sessions in ShrePoint without ant issues...

Sunday, September 25, 2011

Disable automatic activation of SharePoint features in Visual Studio 2010.

When we write our custom solutions for SharePoint 2010, we must know that all our features will be activated automatically on every time we deploy the solution over the SharePoint site selected at project creation time.



This is the default configuration that we have inside SharePoint 2010 tools for Visual Studio 2010. When you are doing development of a custom event receiver that manage activation or deactivation events of a SharePoint feature. In this specific sample, we cannot debug our code.

To solve this problem, you can modify this configuration and select to don't activate your features every time you have to deploy your solution. To do this, simply you have to open the project properties page through the "Solution explorer" toolbox, select the "SharePoint" tab and choose the configuration named "No Activation".
 

As we can disable the automatic activation of our features, we also have the possibility to create custom configurations in which we can insert deploy and retract operations, app-pool recycles, features activation and command execution of pre/post deploy actions.

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters.


If you receive the following error in Visual Studio while packaging WSP:

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters

then simply move all your projects from

C:\Users\YOUR_USERNAME\Documents\Visual Studio 2010\Projects\

to root drive

C:\Projects

Visual studio does not allow absolute path that exceeds 260 characters. so use short filenames when you create any WSP package and create your project on root directory to avoid long absolute paths.

Wednesday, September 21, 2011

Inbuilt method to Check if List Exist in SharePoint 2010.

In SharePoint 2007, one of the mostly required methods but not provided by Microsoft:
Checking if SharePoint List exists on Site or not?
If we directly use spWeb.Lists[“<ListName>”] and if list does not exist then it will throw an exception. To avoid such exceptions I have created following extension method:
public static bool IsListExists(this SPWeb spWeb, string listName)
{
    try
    {
        return spWeb.Lists.Cast<SPList>().Any(list => string.Compare(list.Title, listName, true) == 0);
    }
    catch (Exception ex)
    {
        ex.LogException("List does not exist", CommonConstants.EVENT_SOURCE, spWeb, spWeb.CurrentUser);
        return false;
    }
}
Now Microsoft is woke up, In SharePoint 2010 they have provided an inbuilt method method in the SPListCollection .Simply use this method instead of looping all the lists and check its existence.

SPList sampleList = spWeb.Lists.TryGetList("SampleList");
if (sampleList != null)
{
    // Code Block goes here
}

Hope this helps you...