Translate

Sunday, September 16, 2012

SPList.GetItemById and SPList.GetItemByIdSelectedFields

Using SPList.GetItemById and SPList.GetItemByIdSelectedFields

Difference between SPList.GetItemById and SPList.GetItemByIdSelectedFields


It is very important to consider about the performance when we are query the SPList using SharePoint Object Model, it is not recommended to fetch all items when you are using only one column SharePoint has provided the GetItemByIdSelectedFields which takes the arguments as ID and Field Names which is required.

SPList.GetItemByIdSelectedFields(ID,"Field 1","Field 2","Field3"... so on)

GetItemById method fetches the full item from SPListItemCollection, with all its columns of metadata,even though it may be not required for the any purpose of extra columns still SPListItem hold that values too. So it is required to use in more better way of both GetItemByIdSelectedFields and GetItemById based on the requirements

The following example shows the Employee List which is being query by using GetItemByIdSelectedFields

Let us say the Employee List has three columns

Employee List

Column Name
Type
Employee Number
Number
Employee Salary
Number
Employee Designation
Single Line Of Text


ID
Employee Number
Employee Salary
Employee Designation
1
1123
24000
Senior Software Engineer
2
1124
12000
Trainee
3
1125
50000
Project Manager

The following code fetches

using (SPSite site = new SPSite("http://sampledemo /"))
{
using (SPWeb web = site.OpenWeb()) {
SPList employeeList = web.Lists["Employee List"];
SPListItem  employeeItem= employeeList.GetItemByIdSelectedFields (2,” Employee Salary”);
}
}

Using ReadSecurity and WriteSecurity members in SharePoint

Using ReadSecurity and WriteSecurity members in SharePoint

ReadSecurity and WriteSecurity

ReadSecurity
Using the ReadSecurity we can specify the list permission as read only access to list created through programmatically, it will restrict the users for modifications to the items which they are not owners of that items.
WriteSecurity
Using  WriteSecurity we can allow the users to do modifications to list items which they are owners of the items when we create the list by using the SharePoint Object Model programmatically.
Sample demo code explains about the ReadSecurity  and WriteSecurity by creating reimbursement expense list in which employee who wants to claim their expanses will have the permission which they item and others will not have an access ,Creating it through console application.
//Create the SPSite by passing the url
Using(SPSite spSite=new SPSite(“http://demo/sites/HR”);
{
//Create new GUID
Guid  newListGuid=spWeb.Lists.Add(“ExpensesReimbursement”,” Expenses Reimbursement List”,SPListTemplateType. GenericList );
//open  site

Using (SPWeb spWeb=spSite.OpenWeb())
{
//Create new SPList by passing new GUID
SPList newInstanceList  =  spWeb.Lists[newListGuid];
}
}

Saturday, September 15, 2012

Using SPSite and SPWeb Objects in Sharepoint

Using SPSite and SPWeb Objects in SharePoint


SPSite is the most fundamental object of the SharePoint Object Model,SPSite object can be created using the overloaded constructors or it can be referenced by using unique ID GUID, or with URL
Overloaded methods
SPSite(Guid id)
SPSite(string requestUrl)
SPSite(Guid id, SPUrlZone zone)
SPSite(Guid id, SPUserToken userToken)
SPSite(string requestUrl, SPUserToken userToken)
SPSite(Guid id, SPUrlZone zone, SPUserToken userToken)
SPSite is the only through which we can access the SPWeb  because SPWeb does not have a constructor, There are way with which we can get the instance of SPWeb is through using “SPControl” and “SPContext
Some of the important members of SPWeb are
1.       Users
2.       Title
3.       Update
4.       Delete
5.       ContentTypes
6.       AllUnsafeUpdates
7.       List
8.       ID
9.       GetSiteData
And so on.

Sample code shows how to access the SPWeb using SPSite and display the title of the site collection and update the specific  Subsite Tilte
namespace SampleDemo
{
    [ToolboxItemAttribute(false)]
    public class Sample : WebPart
    {
protected override void CreateChildControls()
        {
        }

       protected override void RenderContent(HtmlTextWriter writer)
        {
SPSite mySiteCollection=null;
SPWeb mySPweb=null;
              Try
{
//Get the SPSite by passing the url
mySiteCollection = new SPSite("http://demoSite /")
Writer.Write(“I am in Site Collection”);
//print /display the current site collection title
Writer.Write ("My Current Site  Exist here: ", mySiteCollection.Url);
mySPweb = mySiteCollection.OpenWeb("MySubSite")
//Update the subsite title
                                mySPweb.Title = mySPweb.Title + " Hey I have changed the Title";
mySPweb.Update();
}
Catch(SPExecption exception)
{
Throw exception
}
Finally
{
mySiteCollection.Dispose();
mySPweb.Dispose();
}
        }

     }
}


Using SPFarm in SharePoint

Using SPFarm in SharePoint

How to use SPFarm

SPFarm is the top level object in SharePoint for any SharePoint installation involves the Farm configuration this is the main object through it is possible to identify collection of server running in the current SharePoint Farm

The sample demo shows how to access the SPFarm Object using SharePoint Object Model
The following sample demonstrate how we can iterate through the farm.Servers that is servers collection
And adding these information in two dictionaries

Code:

           SPFarm farm = SPFarm.Local;
            Dictionary<string, string> serversNames = new Dictionary<string, string>();
            Dictionary<string, string> serversAddress = new Dictionary<string, string>();
            int counter = 0;
            foreach (SPServer server in farm.Servers)
            {
                serversNames.Add("Server Name : " + counter, server.Name);
                serversAddress.Add("Address of Server: " + counter, server.Address);
                counter++;
            }

Sunday, September 9, 2012

Fantastic 40 templates sharepoint 2010

Fantastic 40 templates sharepoint 2010


http://www.wssdemo.com/application/default.aspx

In C # Managing the Lifetime of Objects and Controlling Resources

In C # Managing the Lifetime of Objects and Controlling Resources

Garbage Collector

It is found that all the applications which we create use some resources.The resources fall into two broad categories:
1.managed resources that are handled by the common language runtime (CLR)
2.unmanaged resources that are maintained by the operating system outside the scope of the CLR.

A managed resource is typically an object based on a class defined by using a managed
language, such asC#.

Unmanaged resources include items implemented outside the Microsoft .NET Framework, which include such as Component Object Model (COM) components, file handles, database connections, and network
connections.
Managing resources is important in any applications development,that you develop.
Microsoft has provided “GC” which is called “Garbage Collector “ it facilities  by automatically reclaiming the resources by a managed object when it is no longer referenced by an applica
tion.Managed resources are handled by the .NET Framework garbage collector.However, unmanaged resources are not controlled by the garbage collector; it must take special steps to dispose of them properly and prevent them from being held longer than necessary.


Object life Cycle




An object has several distinct stages in its life cycle, which starts at creation and
ends in destruction. Creating an object is very simple; the new keyword to instantiate the new object. However, the process that you use to create an object is not really this simple. When we create a
new object, It follows the following steps:

Steps
1. A big block of memory will be allocated to hold the object.

2. The object is initialized. The block of memory is converted to an object.
The runtime handles the allocation of memory for managed objects.

Destroying an Object

When you have finished with an object, it can be destroyed.
We use destruction to reclaim any resources used by that object. Like creation,
destruction is a two-phase process:

1. The object is cleaned up; for example, by releasing any unmanaged resources
used by the application, such as file handles and database connections.

2. The memory used by the object is reclaimed.You can control only the first of these steps—cleaning up the object and releasing resources by implementing a destructor.
The CLR handles the release of memory used by managed objects

Using IDisposable Interface

The IDisposable interface defines a single method called Dispose, which takes do not take any
parameters. The Dispose method should release all of the unmanaged resources that an object owns. It should also release all resources owned by its base types by calling the Dispose method of the parent type.Visual C# includes constructs that ensure that resources are released in a timely
fashion for classes that implement the IDisposable interface.


Sample Demo

class Employee : IDisposable
{
bool isDisposed = false;
string name;
public Employee(string Name)
{
name = Name;
}
public void PaySalary()
{
if (!isDisposed)
{
Console.WriteLine("Employee {0} paid.", name);
}
else
{
throw new ObjectDisposedException("Employee already
disposed.");
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool IsDisposing)
{
if (IsDisposing)
{
isDisposed = true;
Console.WriteLine("Employee object disposed.");
}
GC.SuppressFinalize(this);
}
}

Create WCF Service and Host in SharePoint

Create WCF Service and Host in SharePoint

Creating a custom SharePoint WCF Service

There are situations where SharePoint could be acting as a data store providing your business data
to external applications or any web service or any components. These applications requesting data may need to provide information  on having a valid subscription or license before accessing the data. The out-of-the-box web services will not provide you a way to verify this information before allowing access. There may also be a scenario where you may want to strip out confidential information from the list
before passing the data to these external applications. In these scenarios, you can create
your own custom web service which could validate the credentials, or strip out the confidential
data before passing the information to these external applications.


In this example, we will create a custom SharePoint WCF service which returns us the string.This service is 
being host in _layout\_vti_bin directory in internet manager IIS.

Steps to Create a WCF Service:


In order to create a custom SharePoint WCF service,follow the following steps:

1. Open Visual Studio 2010 and create an empty SharePoint project.


2. Name the project CustomWCF. Deploy the solution as the farm solution.
3. Add a SharePoint mapped folder for ISAPI. In this folder, create a folder
named CustomWCF.
4. Add an empty text file named CustomWCF.svc to the CustomWCF folder
underneath ISAPI.
5. Add a new item to the project and select the WCF Service template in the Visual
Studio:
6. This will add three files to your project namely: CustomWCF.cs, ICustomWCF.cs,
and app.config.
7. Move the app.config file from the root folder to the ISAPI\CustomWCF folder in
the project and rename it web.config.
8. Build your project.
9. Open the Visual Studio command prompt and navigate to the bin\debug
directory of your project and execute the following command to get the public
key token of the assembly:
Sn –T CustomWCF.dll
10. Add the following line to the CustomWCF.svc file and add the public key token
obtained from the previous step:
<%@ ServiceHost Debug="true" Language="C#" Service="CustomWCF.
CustomWCF, CustomWCF, Version=1.0.0.0, Culture=neutral, PublicKeyT
oken=2832c7898c525539" CodeBehind="CustomWCF.cs" %>
11. The default DoWork method the Visual Studio added to ICustomWCF.cs returns string
12. Make the same change in the CustomWCF.cs file as well. This is the file where
the interface is implemented. Add the following line of code as shown in the

sample code
public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

13. Add the AspNetComaptibility attribute to the class that is implementing the
interface. So your CustomWCF.cs
class should look as follows:
using System.ServiceModel.Activation;
namespace CustomWCF
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Required)]
    public class CustomWCF : ICustomWCF
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}
14. Build and deploy the application. You should now be able to access this WCF service
from the browser by typing in the URL: http://servername/_vti_bin/
CustomWCF/CustomWCF.svc.

15. Screenshot similar to the following