Translate
Friday, September 21, 2012
Wednesday, September 19, 2012
Using SPUser in SharePoint
Using SPUser in SharePoint
SharePoint Object Model using SPUser Class
SPUser is actually derived from SPPrinciple, SPUser is main
base class which allows in extending its functionality by exposing its member
and different properties.SharePoint object model has provided the provision to
add the user programatically to sharepoint group or permissions to user to a list,and it is possible to update the user information or fetch the user information.
The following sample code shows about how to display user
permission is he in admin group or normal user
also it has the code to update the user information or giving the permission to a list
WebPart
using System;
using System.ComponentModel;
using System.Web;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace SPUserDemo
{
[ToolboxItemAttribute(false)]
public class SPUserDemoWebPart:
WebPart
{
protected override void CreateChildControls()
{
}
protected override void RenderContents(HtmlTextWriter
writer)
{
//Get the user
information
GetUser(writer)
}
private void GetUser(HtmlTextWriter writer)
{
SPUser SPuser = SPContext.Current.Web.CurrentUser;
if(SPuser.IsSiteAdmin)
writer.Write("<p>Ohh you are Super admin user'</p>");
else
writer.Write("<p>No you are a normal user </p>");
}
}
}
Private void AddNewUser()
{
const string listUsers = @"Users ";
SPList Users= null;
SPSecurity.RunWithElevatedPrivileges(
delegate {
using (SPSite spSsite= new SPSite(“http://sitedemo”)) {
using (SPWeb spWeb= spSsite.OpenWeb)
{
spWeb.AllowUnsafeUpdates = true;
Guid listGuidID = spWeb.Lists.Add listUsers,
"Members", SPListTemplateType.GenericList);
Users = spWeb.Lists[listGuidID];
Users.Fields.Add("User", SPFieldType.User, true);
Users.WriteSecurity = 4;
Users.Update();
spWeb.Update();
}
}
});
}
//update user email information
using (SPSite spSsite=new SPSite(“http://sitedemo”)) {
using (SPWeb spWeb= spSsite.OpenWeb)
{
SPUser spUser = spWeb.AllUsers["ABCUser"];
spUser.Email =
" E-mail_Address";
spUser.Update();
}
}
Using SPQuery with ContentIterator.MaxItemsPerQuery in SharePoint
Using SPQuery with ContentIterator.MaxItemsPerQuery
1.
Using SPQuery with RowLimit or with ContentIterator.MaxItemsPerQuery
When we query the
SharePoint list and libraries we use SPQuery
and some situations because of threshold value limit in sharepoint does
not allow the user to query more than or equal to 5000 items,If we use SPQuery
with RowLimit still it is not
sure to get the items, but there is
still SharePoint has provide one more way can do it through using ContentIterator.MaxItemsPerQuery.
We also need to use different keywords using depends upon
the requirement ContentIterator.ItemEnumerationOrderByID,
ContentIterator.ItemEnumerationOrderByPath,
or ContentIterator.ItemEnumerationOrderByNVPField.
Sample Code
SPQuery
myQuery = new SPQuery();
myQuery.Query
=
"<Where><Eq><FieldRef
Name=\"Name\"/><Value
Type=\"Text\">FieldValue</Value></Eq></Where>"
+
ContentIterator.
ItemEnumerationOrderByID;
ContentIterator
citerator = new ContentIterator();
citerator.ProcessItemsInList(query,
delegate(SPListItem item)
{
// Code for update or move the list
item from one list to another or //any
operation
},
// Return true so that ContentIterator
rethrows the exception.
delegate(SPListItem item, Exception e)
{
// Handle an exception that was thrown
while iterating.
return true;
}
);
SharePoint 2013 preview in Cloud Share
SharePoint 2013 preview in the Cloud Share
Using SharePoint in the Cloud Computing
http://www.cloudshare.com/products/proplus/getstarted
http://www.cloudshare.com/products/proplus/getstarted site is really a good to start using SharePoint 2013 in Cloud Share ,there is a free 14 days trail version Cloud SharePoint 2013 preview.
This is really amazing site,this cloud system has got everything
Server has the following software's got installed
1.SharePoint 2013 preview
2.Visual Studio 2012
3.SharePoint Designer 2012
4.SQL Server.
other softwares like PDF and other office tools.
Sunday, September 16, 2012
Creating Site Collection in SharePoint 2013 Preview
Creating Site Collection in SharePoint 2013 Preview
What is new features in SharePoint 2013 Preview
This is my first post on SharePoint 2013 preview,the following are the steps to create new site collection in SharePoint 2013,Microsoft has provided more features and enhancements in SharePoint 2013 than the SharePoint 2010.
Please follow the steps to create a new site collection in SharePoint 2013
1.Go to Central Admin and click on create site collection.
2.Screen will appear to create a new site collection,it is found that now it has a provision to create new web application on site collection creation screen as shown in the screen shot.
2. There is new option to select the template type based on
SharePoint 2010 and SharePoint 2013 also provided with more number of templates
like one is “Developer Site” and other
as shown in the following picture.3.Select the template which is required to create the site
4. Add the Site Collection Administrator account in primary
site collection Administrator and secondary Site Collection Administrator
There is new feature in People picker, more advanced can be
able to search people by Active directory,NT Account or even Claim Based User
as shown in the following screens shots
Now
Microsoft has provided one more feature by displaying the “Sorry to keep you waiting”
as shown in the screen shot
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
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.
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
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
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:
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
Subscribe to:
Posts (Atom)