Wednesday, 4 December 2013

Silver Light Beginner Tutorial

How to Start with Silverlight
As we all know that Microsoft Silverlight is a cross-browser, cross-platform, and 
cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web. In order to work with Silverlight first you need to install the Silverlight plug-in. Please install the from Silverlight plug-in. To add Silverlight to your file, you need a reference to the  Silverlight.js file into your, a xaml file that contains the behavior of the Silverlight
and some JavaScript code to creates Silverlight plug-in instance.

Step - 1
If you are going to use Silverlight into your ASP.NET website, you need to add 
the reference of Silverlight.js file into your page (If you have master page, 
better to add the reference into it so that you don't need to add the reference 
to all your .aspx pages). Please note that the referecne of Silverlight should be placed between <head> and </head> tag and your code should look like
<script src="Silverlight.js" type="text/javascript"></script>Silverlight.js 
file can be found at this website too, however we suggest to get the latest from 
Microsoft website.
Step - 2
You need to create a placeholder for your Silverlight content inside your <body> </body> tag where you want your Silverlight content to appear. In general, you should create a div html element and specify its id property like this 
<div id="fundaSilverlightPluginHost"> </div>
Step - 3
Write the JavaScript code to call the initialization function of Silverlight object like this. You can write this code after your placeholder (Step-2).
        <script language="javascript" type="text/javascript">
          createSilverlightPlugin('fundaSilverlightPluginHost',               '300', '200','YourXamlFilePath.xaml')               
 </script>
                    
Here I am passing all the required value as a parameter. In this case the
1st parameter is the placeholder that I created in the 2nd step,
2nd parameter is the width of the Silverlight plug-in area
3rd parameter is the height of the Silverlight plug-in area
4th parameter is the .xaml file that specifies the behavior of the Silverlight object
Step - 4
Write JavaScript function to initialize the Silverlight object. In my case it looks
 like below. It can be placed inside the common JavaScript file of your website. In any case, this code must be rendered to the browse before last step (Step - 3) code otherwise browser may throw JavaScript  error. Its always better to place this code between<head> and </head>.
                    
function createSilverlightPlugin(placeHolder, width, height,           xamlfile)  {  
    // Retrieve the div element you created in the previous step.
    var parentElement = document.getElementById(placeHolder);
    Silverlight.createObject
    (
        xamlfile,               // Source property value.
        parentElement,          // DOM reference to hosting DIV tag.
        placeHolder,            // Unique plug-in ID value.
        {                       // Per-instance properties.
            width:width,        // Width of rectangular region of 
                                // plug-in area in pixels.
            height:height,      // Height of rectangular region of 
                                // plug-in area in pixels.
    inplaceInstallPrompt:false, // Determines whether to display 
                                // in-place install prompt if 
                                // invalid version detected.
    background:'#fecefe',       // Background color of plug-in.
  isWindowless:'false',    // Determines whether to display plug-in 
                                // in Windowless mode.
            framerate:'24',     // MaxFrameRate property value.
            version:'1.0'      // Silverlight version to use.
        },
        {
            onError:null,     // OnError property value -- 
                              // event handler function name.
            onLoad:null       // OnLoad property value -- 
                              // event handler function name.
        },
        null
    );            // Context value -- event handler function name.
}
                    

Step - 5
Now, you have the placehoder object and function to initialize the Silverlight 
object. Its time to write the behavior of the Silverlight object. So create a 
.xaml file and write below code. Please note that you need to specify this file path as a 4th parameter of Step - 3 initialization function.
<Canvas
   xmlns="http://schemas.microsoft.com/client/2007"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle Height="75" Width="200" Fill="LightGreen" Stroke=           "Red" StrokeThickness="2" Canvas.Left="5" Canvas.Top="5">        </Rectangle>
  <TextBlock Canvas.Left="85" Canvas.Top="20" FontSize="15"              FontFamily="Arial, Verdana" Text="HanuTechVision Silverlight        Tutorials" FontWeight="Bold" Foreground="Blue" TextWrapping=        "Wrap"></TextBlock>
  
</Canvas>
                    
Instead of writing above code into a separate .xaml file, you may write it into your .aspx page as well. In that case your code should look like below.
  <script type="text/xml" id="xamlScript2">
  <?xml version="1.0"?>
  <Canvas 
    xmlns="http://schemas.microsoft.com/client/2007" xmlns:x=           "http://schemas.microsoft.com/winfx/2006/xaml">
    <Rectangle Height="75" Width="400" Fill="Blue" Stroke="Red" 
        StrokeThickness="2" Canvas.Left="5" Canvas.Top="5">             </Rectangle>
          <TextBlock Canvas.Left="20" Canvas.Top="30" FontSize="20" 
      FontFamily="Arial, Verdana" Text="HanuTechVision Silverlight         Tutorials" FontWeight="Bold" Foreground="White" TextWrapping        ="Wrap"> </TextBlock>
  </Canvas>
</script>
                    
Notice that if you have written the .xaml code into your .aspx page, your Step - 3 code should be slightly changed as below. Here, instead of specifying the .xaml    file path in the 4th parameter of initialization function, you need to specify the        id of the .xaml code preceeded by #.
               <script language="javascript" type="text/javascript">
                   createSilverlightPlugin('divDemoSliverlight',                      '450', '100', '#xamlScript2')
                    </script>
                    


Step - 6
Thats it!, Just run your page in the browser and you should see a Silverlight banner like below. Acknowledgement: I have taken reference of Silverlight.net website in writing these articles.

ASP.NET MVC Tutorial part 2

ASP.NET MVC Tutorial Part I

A Look at MVC Request Response process

Now we already saw the MVC request life cycle but quite in the reverse direction. Let us try to see this formally.
  1. User sends the request in form of URL.
  2. UrlRoutingModule intercepts the request and starts parsing it.
  3. The appropriate Controller and handler will be identified from the URL by looking at the RouteTablecollection. Also any data coming along with the request is kept in RouteData.
  4. The appropriate action in the identified controller will be executed.
  5. This action will create the Model class based on data.
  6. The action will then pass on this created model class to some view and tell the view to prceed.
  7. Now the view will then execute and create the markup based on the logic and Model's data and then push the HTML back to the browser.
This life cycle above is defined for explanation and has omitted some technical details which involved a few more objects(like controller base class). Once the idea of MVC is understood I would recommend to dig deeper into the Request life cycle.

A Sneak Peak at Routing

Now we have said that the controller and action will be decided by the URL. So it is perhaps a good idea to look at a very simple example of this RouteTable entry so that we know what pattern of URL will invoked which controller and which action.
Here is the default entry in the RouteTable which is made in global.asax application_start event.
routes.MapRoute
(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Blog", action = "Index", id = UrlParameter.Optional 
);
Here in this above route, the name for the route is specified as Default. The second argument specifies the pattern of the URL that should lead to this route usage i.e. Any URL with pattern"SiteAddress/{controller}/{action}/{id}" will use this route. The final argument specifies that if this route will be used then a controller named Blog and an action Index will be invoked. id is optional meaning it could be present or not.
So the following URLs will invoke the respective actions and controllers.
Url: www.siteaddress.com
Controller: Blog
Action: Index
Url: www.siteaddress.com/Blog
Controller: Blog
Action: Index
Url: www.siteaddress.com/Blog/Create
Controller: Blog
Action: Create
Url: www.siteaddress.com/Blog/Delete/1
Controller: Blog
Action: Delete
Id: 1
Url: www.siteaddress.com/Category/Edit/1
Controller: Category
Action: Edit
Id: 1
So the above examples would perhaps make it clear that what URL will invoke which controller and which action. We can also define custom routes too. I am not talking about creating custom routes in this article but once routing is understood creating custom routes is fairly straight forward.

Using the code

Now we have seen some theory behind MVC architecture. Let us now create a simple application that will be invoked on a specific URL. The controller will be invoked and a Model class will be created. Then this Model will be passed to the view and the resulting HTML will be displayed on the browser.
Now the creation of ControllersModels and Views need some code to be written by the developer. Visual studio also provides some standard templates that provides several scaffolds out of the box. Now since this tutorial is mainly to look at the overall architecture of MVC and understanding how we can create our first MVC application we will use these templates and scaffolding. But it is highly recommended that some good book on MVC should be referred to get the full understanding of these.
Note: We will be creating an MVC 3.0 application and using Razor view engine for this exercise.
Let us go ahead and create a new MVC 3 Web Application.
Upon asked, let us select the Razor View Engine.

Now this template comes with a lot of predefined Controllers, models and view. Let us delete all this and just have three Folders named Models, Views And Controllers in this application.

Now let us start by defining our own route in the global.asax. Now the Controller that we want to access by default will be DemoController. We want the Index action of this controller to execute by default. We will also pass an ID which, if present will also be displayed on the page. So the route defined for this in the global.asaxwill look like:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Demo", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
} 
And now Let us add a Controller named Demo to this application. This can be done by right clicking the controller's folder and selecting Add Controller. Name this Controller as DemoController.
Now this controller comes with a default action Index. This action will be called if no action is specified for this controller. Let us show a simple message if this controller is invoked. We will use ViewBag for this. Viewbag is an object that is accessible in the View page and it should be populated in the Controller.
public ActionResult Index()
{
    ViewBag.UsageSample = 
            @"Please Use the Url 'Demo/Test' or 'Demo/Test/1' to see the Book Details";

    return View();
}
Note: We are not taking about the data transfer techniques like ViewBagViewData and TempData in this article. that topic requires some detailed discussion. We will perhaps discuss them later.
Now this code will simply put a string in the view bag and call the View. The return statement will expect a view named index present in a folder named Demo. We don't have that right now so let us create this view by right clicking the method name as:
This will then ask for more options for the view we need to add. For now lets not select any other option and just create the view.
Now in the view we will write the logic of extracting the data from ViewBag and showing it on the page.
<div>
        @ViewBag.UsageSample;   
</div>
And now if we try to run this application:
And so we have seen how the controller gets invoked from the the user request and then controller passes some data to the view and the view renders it after processing. But we have not yet added any model to it. Let us add a simple Model in this application. Let us define a simple model for a Book class in the models folder. We will then see how we can use instantiate this model and use this in our View.
public class Book
{
    public int ID { get; set; }
    public string BookName { get; set; }
    public string AuthorName { get; set; }
    public string ISBN { get; set; }
}
Now let as ad an action called Test in this DemoController and create an object of this Book Model. Once the object is created we need to pass this object in the view as:
public ActionResult Test()
{
    Book book = new Book
    {
        ID = 1,
        BookName = "Design Pattern by GoF",
        AuthorName = "GoF",
        ISBN = "NA"
    };

    return View(book);
}
the above code will create the model and pass it to the view. Now lets create a view that is capable of extracting the data from this model. This can be done by creating a strongly typed view as:

I have also chosen the scaffold template as "Details" so that all the boilerplate code in the view page to display these details is already generated.
And now we run the code we can see the details of the book which were extracted from the Model which was created in the controller, which was executed on parsing user's request URL.
And thus we have our very first MVC 3.0 application with razor view engine working.

Point of interest

This article was created as a tutorial for developer who are working in Web forms and are totally new to MVC world. Experienced MVC developers might find this article quite mundane. This article is actually more like a transcription of the first training that I conducted for MVC beginner's. I hope this article is little useful for beginner's.

ASP.NET MVC Tutorial for beginners

Introduction

In this article we will try to look at ASP.NET MVC architecture from a beginner's perspective. There are a plethora of articles available on the same topic. This article is yet another attempt of explain MVC in my own words.

Background 

ASP.NET MVC is the architectural pattern based on ASP.NET framework which provides a clean and elegant way of developing Web application. Before we can understand why MVC is in vogue we need to understand some limitation of Web forms first.

A Brief Discussion on Web Forms

let us discuss some limitation of web forms which are seen as drawbacks. I am sure many veteran developers will agree that these drawbacks can be put in check by following best practices and guidelines but none the less its a good idea to discuss them before looking at the ASP.NET MVC architecture.
  • ViewState: This is the heart of ASP.NET when it comes to the ability of ASP.NET to provide stateful abstraction over stateless HTTP protocol. But with great power comes great responsibility  If the ViewState is not managed properly then this would increase the size of the rendered web page a lot and this causing extra load.
  • Generated HTML: Server side controls are another strong selling points of web forms. They facilitate rapid application development without worrying too much about the client side HTML code. But since the use of client side technologies are increasing (javascript, jQuery etc.), the less control over generated markup is becoming bit of a problem.
  • Urls: In ASP.NET web forms the request URL points to physical files and the structure of the URL is not SEO friendly. Also, now is the time when URL structure is very important and clean URLs and control over URLs is very much desired.
  • Code Behind: Code behind model, in my opinion, is the best part of ASP.NET. It provides clear separation of concern. From a developers perspective having the code behind file provides a great way to write the server side logic without having to write code between the HTML markup.
  • Page Life Cycle: Although code behind model provides a great way for providing separation of concern, the page life cycle is little complex and should be fully understood. If a developer fails to understand the page lide cycle then there might be some unforeseen and undesired issues in the final application.
  • Test Driven Development support: Now is the time of being agile. When we follow agile methodology (scrum specifically), it id very important to define the "Done" in scrum. TDD helps in this. If all our test cases are passed then we can be sure that the "Done" is done. ASP.NET does not provide native support for TDD because it is kind of difficult to imitate the HTTP request and HTTP context.
Having said that(all the above points), I would also like to point that question of limitations of web forms is becoming blurred with every new release of ASP.NET web forms. A lot of these limitations are being curbed in Web forms. ASP.NET 4.0 added URL Routing, reduced ViewState, and a much better control of the HTML mark-up. A lot of other issues related to leaky abstractions in web forms can be solved by following best practices and design guidelines. And the TDD can be performed with the help of some tool.
So it is not a question of which is better. ASP.NET Web Forms and MVC are two different architectural styles. Forms focusing on rapid application development (and now getting a lot better with every new release). and MVC is for designing Web applications without the baggage that comes with forms and following good patterns.
A lot of deevlopers think that MVC is the new way of developing web application and Web forms is dead but strictly in my personal opinion, they both are two different architectural styles and no one supersedes other. We should choose the one based on our requirements and resources available. In fact the possibility of being able to mix both the styles is the best thing. We can use both these styles in a single application and get the best of both worlds.

A look at MVC 

MVC framework embraces the fact that the HTTP is stateless and thus no stateful abstraction will be provided by the framework. It is up to the developers to take care of managing the state in a MVC application.
In MVC architecture there are three major player. ModelView and Controller. we need to work on these creating these components to get our web application to work. Now before looking at these three in detail let us try to think how we can put server side contents in a HTML page. We will take a rather reverse approach to understand this. 
We need to put some server side data into an HTML markup before rendering it. Now this can easily be done in Web forms too where we used to put C# code in aspx markup. The only prerequisite for that is that we should have some object containing the value on the server side from which we can extract the data. That is what views does in MVC. they simply run and before rendering the markup they use some server side object to extract the data and create the complete HTML markup and render on client browser.
Now lets take a step back again, Now we need an object on server side. In MVC world this is model. We need an instantiated model and pass it to the view so that views can extract the data from this object and create the final HTML markup.
Now the question would be, who would instantiate these Models. These models will be instantiated in the controllers. Controller will instantiate the models and then pass the model to the view so that the view can use them to generate the markup.
But now the bigger question, How would the controller be invoked  The controller will be invoked on the user request. All the user requests will be intercepted by some module and then the request URL will be parsed and based on the URL structure an appropriate controller will be invoked.
So now that we know the basic flow let us try to define the Model, View and Controller formally.
  • Model: These are the classes that contain data. They can practically be any class that can be instantiated and can provide some data. These can be entity framework generated entities, collection, generics or even generic collections too.
  • Controllers: These are the classes that will be invoked on user requests. The main tasks of these are to generate the model class object, pass them to some view and tell the view to generate markup and render it on user browser.
  • Views: These are simple pages containing HTML and C# code that will use the server side object i.e. the model to extract the data, tailor the HTML markup and then render it to the client browser.

Tuesday, 5 November 2013

Sharepoint 2010 Workflows

Introduction

SharePoint 2010 introduces many new capabilities that are categorized into six different workloads, one of which is the composites workload. A key component of creating composite applications is SharePoint 2010’s ability to create custom workflows, allowing end users to attach behaviour to data.
Workflows in SharePoint Server 2010 enable enterprises to reduce the amount of unnecessary interactions between people as they perform business processes. For example, to reach a decision, groups typically follow a series of steps. The steps can be a formal, standard operating procedure, or an informal implicitly understood way to operate. Collectively, the steps represent a business process. The number of human interactions that occur in business processes can inhibit speed and the quality of decisions.

Workflow in SharePoint 2010

SharePoint Foundation 2010 workflows are made available to end-users at the list or document-library level. Workflows can be added to documents or list items. Workflow can also be added to content types. Multiple workflows may be available for a given item. Multiple workflows can run simultaneously on the same item, but only one instance of a specific workflow can run on a specific item at any given time. For example, you might have two workflows, called SpecReview and LegalReview, available for a specific content type, Specification. Although both workflows can run simultaneously on a specific item of the Specification content type, you cannot have two instances of the LegalReview workflow running on the same item at the same time.
The figure below illustrates the conceptual workflow architecture in SharePoint Foundation. Each content type, list, and document library in the farm is linked to the workflows added to it through the workflow association table. Each workflow has a workflow definition. This XML definition specifies the identity of the actual workflow assembly, and class within that assembly, as well as the location of any workflow forms the workflow needs to run.

SharePoint Workflow Life Cycle

The figure below illustrates the four stages of the SharePoint workflow life cycle. These stages allow for the assignment of workflows to content type, handle the different ways for starting workflows, and keep the workflow infrastructure flexible during execution. This custom life cycle is provided by the SharePoint-specific workflow hosting environment. During some of the following stages, forms can be used to gather additional user input as parameters, which are required for this stage to execute.


Thursday, 31 October 2013

ASP.NET Cookies

ASP.NET Cookies

Cookies provide the ability to store small amounts of data on a clients machine. It is often used to store
user preferences, session variables, or identity. When the user visits your Web site another time, the
application can retrieve the information it stored earlier. The browser is responsible for managing
cookies on a user system. Cookies can be created, accessed, and modified directly by script running on
the client and pass between the client and server during requests.
Writing Cookies
vb.net
Response.Cookies("userName").Value = "John" Response.Cookies("userName").Expires =
DateTime.Now.AddDays(1)
C#
Response.Cookies["userName"].Value = "John"; Response.Cookies["userName"].Expires =
DateTime.Now.AddDays(1);
Reading Cookies
vb.net
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value) End If
C#
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
Cookies can be either temporary or persistent. Temporary cookies are stored in the clients browser.
These cookies are saved only while your web browser is running. Persistent cookies, on the other hand,
are stored on the hard disk of the client computer as a text file. They stay on your hard disk and can be
accessed by web servers until they are deleted or have expired. These cookies can be retrieved by the
Web application when the client establishes another session with it.
Cookies are limited to 4096 bytes in size and are only capable of storing strings. Browsers also impose
limitations on how many cookies your site can store on the users computer. Most browsers allow only
20 cookies per site; if you try to store more, the oldest cookies are discarded.

SharePoint 2010 Vs 2013

SharePoint 2010 vs. 2013
  • From a document collaboration perspective, the structures of both versions are the same –so if you create a metadata architecture for documents in 2010 it should be fully upgradable to 2013.
  • The most significant upgrades in document management are in the user experience –including drag and drop to upload documents and the ability to edit managed metadata in a datasheet view.
  • The primary differences are in the social experiences, especially with discussion boards. The 2013 discussion board (with Community features enabled) creates and engaging “Facebook-like” activity stream, which is far more user-friendly than the same feature in SharePoint 2010. The added visual appeal is important because getting people to use the discussion board instead of commonly used “who you know” networks will take some planning and effort. If the software is engaging and familiar it will help with “stickiness.”
  • The other significant improvement is search, which you will see in the examples on the next few pages.
  

Monday, 30 September 2013

SharePoint Basic Interview Questions Part 3


SharePoint 2010 Interview Questions With Answers
 
1. Describe the potential components for both a single server, and multiple servers, potentially several tiered farms:
Ans single-server SharePoint Server 2010 environment leverages a built-in SQL Server 2008
Express database. The problems with this environment is scalability, not being able to install the with built-in database on a domain controller, the database cannot be larger than 4 GB, and you cannot use User Profile Synchronization in a single server with built-in database installation.
Multiple tier farms would be a three-tier topology, considered one of the more efficient physical and logical layouts to supports scaling out or scaling up and provides better distribution of services across the member servers of the farm.

2. How will you use Web Parts or other solutions Created in SharePoint 2007 in SharePoint 2010?
In SharePoint 2010 the 12 hive is now replaced by 14 hive, So we will rewrite and recompile any
code that refers to files and resources in “12? hive. In addition to we must recompile custom code written for Windows SharePoint Services 3.0 and Office SharePoint Server 2007 that does not run on IIS.

3. When would you use claims, and when would you use classic?
Classic is more commonly seen in upgraded 2007 environments whereas claims are the
recommended path for new deployments.

4. What is the difference between Classic mode authentication and Claims-based authentication?
As the name suggests, classic authentication supports NT authentication types like Kerberos,
NTLM, Basic, Digest, and anonymous. Claims based authentication uses claims identities against a against a trusted identity provider.

5. What is the advantage in using Windows PowerShell over stsadm in SharePoint 2010 ?
Unlike stsadm, which accept and return text, Windows PowerShell is built on the Microsoft .NET
Framework and accepts and returns .NET Framework objects. Windows PowerShell also gives you access to the file system on the computer and enables you to access other data stores, such as the registry and the digital signature certificate stores etc..

6. What are My Sites?
Specialized SharePoint sites personalized and targeted for each user.
 

7. What are content databases?
A content database can hold all the content for one or more site collections.
 

8. What is a site?
A site in SharePoint contains Web pages and related assets such as lists, all hosted within a site
collection.

9. What is a site collection?
A site collection contains a top-level website and can contain one or more sub-sites web sites
that have the same owner and share administration settings.

10. Differentiate zones?
Different logical paths (URLs meaning) of gaining access to the same SharePoint Web application
 

11. Importance of application pools?
They provide a way for multiple sites to run on the same server but still have their own worker
processes and identity.

12.  Define Web Applications in SharePoint?
An IIS Web site created and used by SharePoint 2010. Saying an IIS virtual server is also an
acceptable answer.

13. What are Terms and Term Sets?
A term is a word or a phrase that can be associated with an item.  A term set is a collection of
related terms.

14. How many of types of Term Sets?
There are Local Term Sets and Global Term Sets, one created within the context of a site
collection and the other created outside the context of a site collection, respectively.

15. What is a sandboxed solution?
Components that are deployed to run within the sandboxed process rather than running in the
production Internet Information Services (IIS) worker process.

16. Why are sandboxed solutions used?
Primarily because they promote high layers of isolation. By default they run within a rights-
restricted, isolated process based around Code Access Security (CAS). Isolation is possible to increase with activities like running the sandboxing service on only specific SharePoint 2010 servers.

17. What is a search scope?
A search scope defines a subset of information in the search index. Users can select a search
scope when performing a search.

18. What is query logging in SharePoint 2010?
Collects information about user search queries and search results that users select on their
computers to improve the relevancy of search results and to improve query suggestions.

19. Please describe what a Service Application is in SharePoint 2010.
Service applications in SharePoint 2010 are a set of services that can possibly be shared across
Web applications. Some of these services may or may not be shared across the SharePoint 2010 farm.

Examples are mentioned below:
  • Access Services
  • Business Data Connectivity service
  • Excel Services Application
  • Managed Metadata service
  • Performance Point Service Application
  • Search service
  • Secure Store Service
  • State service
  • Usage and Health Data Collection service
  • User Profile service
  • Visio Graphics Service
  • Web Analytics service
  • Word Automation Services
  • Microsoft SharePoint Foundation Subscription Settings Service

20. What is Access Services?
Allows users to edit, update, and create linked Microsoft Access 2010 databases that can be
viewed and manipulated by using an internet browser, the Access client, or a linked HTML page.

21. What is Visio Services?
Allows users to share and view Microsoft Visio Web drawings. The service also enables data-
connected Microsoft Visio 2010 Web drawings to be refreshed and updated from various data sources.

22.  What is Performance Point Services?
Allows users to monitor and analyze a business by building dashboards, scorecards, and key
performance indicators (KPIs).

23. What is the Secure Store Service (SSS)?
A secure database for storing credentials that are associated with application IDs
 

24. What is Excel Services?
Allows sharing, securing, managing, and using Excel 2010 workbooks in a SharePoint Server
Web site or document library. Excel Services consists of the Excel Calculation Services (ECS), Microsoft Excel Web Access (EWA), and Excel Web Services (EWS) components.

25. what is the difference between SQL clustering and mirroring?
Clustering provides a failover scenario whereby one or more nodes can be swapped as active
depending on whether a node goes down. In mirroring, transactions are sent directly from aprincipal database and server to a mirror database to establish essentially a replica of the database.

26.what are the monitoring features that are present in SharePoint 2010.
Diagnostic logging captures data about the state of the system, whereas health and usage data
collection uses specific timer jobs to perform monitoring tasks, collecting information about:
  • Performance Counter Fata
  • Event Log Data
  • Timer Service Data
  • Metrics For Site Collections and Sites
  • Search Usage Data

27. Explain how connections are managed with Service Applications.
A virtual entity is used that is referred to as a proxy, due to label in PowerShell.
 
 

CAML Brief Introduction



What is CAML Query
              The CAML language has been associated with SharePoint since the first version, SharePoint 2001, and SharePoint Team Services. It is based on a defined Extensible Markup Language (XML) document that will help you perform a data manipulation task in SharePoint. It is easy to relate a list to CAML if you compare it to a database table and query. When querying a database, you could get all of the records back from the table and then find the one that you want, or you can use a Structured Query Language (SQL) query to narrow the results to just the records in which you are interested.

Example:   CAML Query Basic Example:

<Query>
   <Where>
<!--Comparison Operators here-->
<Eq>
<FieldRef Name=”insertFieldNameHere” />
<Value Type=”insertDataTypeHere”>insertValueHere</Value>
 </Eq>
</Where>
<OrderBy>
<FieldRef Name=”insertFieldNameHere” />
<FieldRef Name=”insertFieldNameHere” />
</OrderBy>
</Query>

Using CAML query in SharePoint Programming:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace CamlQuery
{
class Program
{
static void Main(string[] args)
{ "string camlQuery =
"" +
"" +
"" +
"" +
"Chen" +
"" +
"" +
"";
SPSite site = new SPSite("http://SPS123/");
SPWeb testWeb = site.AllWebs["Budget Test Site"];
SPList bdcList = testWeb.Lists["List with BDC Lookup"];
SPQuery query = new SPQuery( );
query.Query = camlQuery;
SPListItemCollection filteredItems =
bdcList.GetItems(query);
Console.WriteLine("Found {0} items in query.",
filteredItems.Count);
foreach (SPListItem item in filteredItems)
{ Console.WriteLine("Found customer: {0} {1}",
item["Customer"],
item["Customer: LastName"]);
} Console.ReadLine();
} } }"
CAML Query Comparison Operators:
Tag Name  Meaning
Contains  Contains a given text value
Eq   Equal to
Geq   Greater than or equal to
Gt   Greater than
Leq   Less than or equal to
Lt   Less than
Neq   Not equal to
DateRangesOverlap  Compares dates in recurring events to determine if they overlap
IsNotNull  Is not null
IsNull   Is null

The following code is an example to extract the FieldRef name from a list by using a console application and the Microsoft Office SharePoint Server 2007 application programming interface (API):
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace SharePointUtils
{
class Program
{
static void Main(string[] args)
{
string siteUrl = args[0];
string listName = args[1];
string viewName = args[2];
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
SPList employeesList = web.Lists[listName];
SPQuery query = new SPQuery(employeesList.Views[viewName]);
System.Diagnostics.Debug.WriteLine(query.ViewXml);
Console.WriteLine(query.ViewXml);
Console.ReadLine();
}
}
}
Some important points about CAML Query:
->CAML query is used to perform operation on SharePoint list. ->CAML query's root element is Query.
->Where claause in CAML query is used for filter criteria. ->Order by element is used to set the elements in a specific order either by ascending or descending.
Retrieving List items from SharePoint list using CAML query.
Setting the row limit in CAML query result set.
We can set the row limit in a result set of caml query. This can be done by using SPQuery. SPQuery spqry = new SPQuery(); spqry.RowLimit = 20;
Questions about SharePoint CAML Query:
Write a caml query to get the customer details from SharePoint list called Customer.
How to fetch record from a sharepoint list using caml query, the condition is only active user record should come in result set.
What is the difference between caml query and linq in sharepoint?
Which is good caml query or linq ?
Can caml query is applicable on sharepoint document library ?.

Saturday, 28 September 2013

Creating SharePoint 2010 Event Receivers in Visual Studio 2010

Overview
Microsoft Visual Studio 2010 provides a project type that enables you to build event receivers that perform actions
before or after selected events on a Microsoft SharePoint 2010 site. This example shows how to add an event to the
adding and updating actions for custom list items.
Code It
This SharePoint Visual How To describes the following steps for creating and deploying an event receiver in
Visual Studio 2010:
1. Overriding the itemAdding event and the itemUpdating event.
2. Verifying that the list to which the item is being added is the Open Position list.
3. Elevating permissions so that the code can access a secure site to retrieve approved job titles.
4. Comparing approved Job Titles with the title of a new item that is created in the Open Position list.
5. Canceling the event when the Job Title is not approved.
In this example, a secure subsite contains a list named Job Definitions that specifies allowed job titles for roles
in the organization. Along with job titles, the list also contains confidential salary information for the job title and is
therefore secured from users. In the main site, a list named Open Positions tracks vacancies in the organization.
You create two event receivers for the itemAdding and itemUpdating events that verify that the title of the open
 position matches one of the approved titles in the Job Definitions list.
Prerequisites
Before you start, create the subsite and lists that you will need.
To create the Job Definitions subsite
1. On the main site, on the Site Actions menu, click New Site.
2. In the New Site dialog box, click Blank Site.
3. On the right of the dialog box, click More Options.
4. In the Title box, type Job Definitions.
5. In the Web Site Address box, type JobDefinitions.
6. In the Permissions section, click Use Unique Permissions, and then click Create.
7. In the Visitors to this site section, select Use an existing group, and then select Team Site Owners.
8. Click OK.
To create the Job Definitions list
1. In the Job Definitions site, create a custom list named Job Definitions with the following columns:
o  Title (Default column)
o  MinSalary (Currency)
o  MaxSalary (Currency)
o  Role Type (Choice: PermanentContract)
2. Add several jobs to this list. Note the titles that you specify for each job that you create because you will
need them later.
To create the Open Positions list
·    In the parent site, create a custom list named Open Positions with the following columns:
o  Title (Default column)
o  Location (Single line of text)
Creating an Event Receiver
Next, create an Event Receiver project in Visual Studio 2010, and add code to the events receiver file.
To create a SharePoint 2010 event receiver in Visual Studio 2010
1. Start Visual Studio 2010.
2. On the File menu, click New, and then click Project.
3. In the New Project dialog box, in the Installed Templates section, expand either Visual Basic or Visual C#,
expand SharePoint, and then click 2010.
4. In the template list, click Event Receiver.
5. In the Name box, type VerifyJob.
6. Leave other fields with their default values, and click OK.
7. In the What local site do you want to use for debugging? list, select your site.
8. Select the Deploy as a farm solution option, and then click Next.
9. On the Choose Event Receiver Settings page, in the What type of event receiver do you want? list, select 
List Item Events.
10.  In the What Item should be the event source? list, select Custom List.
11.  Under Handle the following events, select the An item is being added and the An item is being updated
check boxes. Click Finish.
To modify the events receiver file
1. In the events receiver file, add the following code to the class.
VB
Public Function CheckItem(ByVal properties As SPItemEventProperties) As Boolean
Dim jobTitle As String = properties.AfterProperties("Title").ToString()
    Dim allowed As Boolean = False
    Dim jobDefWeb As SPWeb = Nothing
    Dim jobDefList As SPList
    Dim privilegedAccount As SPUser = properties.Web.AllUsers("SHAREPOINT\SYSTEM")
   Dim privilegedToken As SPUserToken = privilegedAccount.UserToken

    Try
        Using elevatedSite As New SPSite(properties.Web.Url, privilegedToken)
            Using elevatedWeb As SPWeb = elevatedSite.OpenWeb()
                jobDefWeb = elevatedWeb.Webs("JobDefinitions")
                jobDefList = jobDefWeb.Lists("Job Definitions")

                For Each item As SPListItem In jobDefList.Items
                    If item("Title").ToString() = jobTitle Then
                        allowed = True
                        Exit For
                    End If
                Next

            End Using
        End Using

        Return (allowed)

    Finally
        jobDefWeb.Dispose()
    End Try
End Function
C#
bool checkItem(SPItemEventProperties properties)
  {
      string jobTitle = properties.AfterProperties["Title"].ToString();
      bool allowed = false;
      SPWeb jobDefWeb = null;
      SPList jobDefList;
      SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
      SPUserToken privilegedToken = privilegedAccount.UserToken;
      try
      {
          using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken))
          {
              using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
              {
                  jobDefWeb = elevatedWeb.Webs["JobDefinitions"];
                  jobDefList = jobDefWeb.Lists["Job Definitions"];
                  foreach (SPListItem item in jobDefList.Items)
                  {
                      if (item["Title"].ToString() == jobTitle)
                      {
                          allowed = true;
                          break;
                      }
                  }
              }
          }
          return (allowed);
      }
      finally
      {
          jobDefWeb.Dispose();
      }
  }
2. In the EventReceiver1 file, replace the ItemAdding method with the following code.
VB
Public Overrides Sub ItemAdding(properties as SPItemEventProperties)
    Try
        Dim allowed As Boolean = True

        If properties.ListTitle = "Open Positions" Then
            allowed = CheckItem(properties)
        End If

        If allowed = False Then
            properties.Status = SPEventReceiverStatus.CancelWithError
            properties.ErrorMessage = _
              "The job you have entered is not defined in the Job Definitions List"
            properties.Cancel = True
        End If

    Catch ex As Exception
        properties.Status = SPEventReceiverStatus.CancelWithError
        properties.ErrorMessage = ex.Message
        properties.Cancel = True
    End Try
End Sub

C#
public override void ItemAdding(SPItemEventProperties properties)
    {
      try
        {
            bool allowed = true;

            if (properties.ListTitle == "Open Positions")
            {
             allowed = checkItem(properties);
            }
       
               if (!allowed)
            {
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.ErrorMessage =
                 "The job you have entered is not defined in the Job Definitions List";
               properties.Cancel = true;
            }
        }
        catch (Exception ex)
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = ex.Message;
            properties.Cancel = true;
        }
    }
3. In the EventReceiver1 file, replace the ItemUpdating method with the following code.
VB
Public Overrides Sub ItemUpdating(properties as SPItemEventProperties)
        Try
            Dim allowed As Boolean = True

            If properties.ListTitle = "Open Positions" Then
                allowed = CheckItem(properties)
            End If

            If allowed = False Then
                properties.Status = SPEventReceiverStatus.CancelWithError
                properties.ErrorMessage = _
                  "The job you have entered is not defined in the Job Definitions List"
                properties.Cancel = True
            End If

        Catch ex As Exception
            properties.Status = SPEventReceiverStatus.CancelWithError
            properties.ErrorMessage = ex.Message
            properties.Cancel = True

        End Try
End Sub
C#
public override void ItemUpdating(SPItemEventProperties properties)
    {
          
        bool allowed = true;

        if (properties.ListTitle == "Open Positions")
        {
            allowed = checkItem(properties);
        }
       
        try
        {
           
            if (!allowed)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage =
                  "The job you have entered is not defined in the Job Definitions List";
                properties.Cancel = true;
            }
        }
        catch (Exception ex)
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = ex.Message;
            properties.Cancel = true;
        }
    }
To deploy the project
1. In Solution Explorer, right-click the project, and then click Deploy.
2. In the SharePoint site, in the Open Positions list, click Add new item.
3. In the Title field, provide a title for a job description that does not exist in the Job Definitions list in the
secured subsite.
4. Click Save. You receive a message from the event receiver.
5. In the Title field, provide a title for a job description that exists in the Job Definitions list in the secured
subsite.
6. Click Save. The position is created.
Read It
·    The solution overrides the ItemAdding and ItemUpdating methods and verifies whether the list that is
being added to is the Open Positions list. If it is, a call is made to the CheckItem method, passing in the
properties that are associated with the event.
·    In the CheckItem method, the permissions are elevated to ensure successful access to the secured subsite.
The job titles that are in the approved list are compared to the job title of the properties.AfterProperties 
property associated with the event. If any title matches, the allowedBoolean variable is set to true, and the
 method returns.
·    Depending on the value of the allowed variable, the calling method either permits the event or sets the
properties.ErrorMessage property and then cancels the event using properties.cancel.