Q)How to get page title and URL in SharePoint 2010 using server object model?
To get the Page Title in SharePoint, you can follow the below approach.
User the below namespace:
using Microsoft.SharePoint;
Then write the below code to get the Title
String Title= SPContext.Current.Item["Title"].ToString();
Similarly you can get the URL in the below way
Sting URL=System.Web.HttpContext.Current.Request.Path;
Q)Generate Random password using C#.Net?
public GenerateRandomPassword()
{
String strGuid=System.Guid.NewGuid().ToString();
strGuid=strGuid.Replace("-",string.Empty);
strGuid=strGuid.Substring(0,8); //Here 8 means the password contains 8 characters.
}
Q)To create a list instance with SP object Model.
using System;
using Microsoft.SharePoint;
class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}
if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}
Q)How to use GetList() method?
SPList announcementsList = web.GetList("/Lists/Announcements");
Q)To create and save a new list item.
SPListItem newItem = list.Items.Add();
newItem ["Title"] = "Litware Goes Public!";
newItem ["Body"] = " We all live in exciting times.";
newItem["Expires"] = DateTime.Now + TimeSpan.FromDays(2);
newItem.Update();
Q) How to enumerate through the fields in a list by using a foreach construct?
foreach (SPField field in list.Fields)
{
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine(field.Title);
}
5. How to use CAML Query with SPQuery Object?
SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@"
//Write a query(using CAML)
";
SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}
Q)How to use SPSiteDataQuery ?
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";
string queryText =
@"
//Write a query(using CAML)
";
query.Query = queryText;
DataTable table = site.GetSiteData(query);
foreach (DataRow row in table.Rows) {
Console.WriteLine(row["Title"].ToString());
}
Q)Difference between SPquery and SPSiteDataQuery?
SPQuery object return an SPListItemCollection. SPSiteDataQuery object are different, because they return an ADO.NET DataTable object.
Q)Visit through document library in SharePoint Site.
SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;
// Add document library to DropDownList control
lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}
Q)Points about SharePoint List?
You can access a List by its name or by its URL.
When retrieving a list by name, you can use the TryGetList method of the SPListCollection, which returns null if the list does not exist.
When retrieving the list by the URL, you can use the GetList method of the SPWeb object, which throws a System.IO.FileNotFoundException if the list does not exist.
Code Samples:
using (SPSite siteCollection = new SPSite("Site URL"))
{
using (SPWeb site = siteCollection.OpenWeb)
{
SPList lstName = site.Lists.TryGetList("NameOfTheList");
if(lstName != null)
//do your work
else
//List does not exists
try
{
SPList taskList = site.GetList("/Lists/Tasks");
//do your work
}
catch(FileNotFoundException)
{
//List does not work
}
}
}
Lists maintain items in a Microsoft.SharePoint.SPListItemCollection object, which is accessible via the Items property of SPList.
Items in the collection are returned as Microsoft.SharePoint.SPListItem objects.
You can iterated over using a foreach statement, or directly accessed using either the item’s ID or index.
Each individual SPListItem maintains a Hashtable of values representing the properties of the item.
//Add new item to list
SPListItem newItem = list.Items.Add;
newItem["Title"] = "This will be the title";
newItem.Update;
//Bind the item to gridview
SPListItemCollection items = list.Items;
gridview1.DataSource = items;
gridview1.DataBind;
//Delete Item by Index
list.Items[0].Delete;
//Update Item by Index
SPListItem updateItem = list.Items[0];
updateItem["Title"] = "Updated Title";
updateItem.Update;
when creating new items in a list, the Update method must be called to save the new item. If the Update method is not called, then the list item will be lost.
if the item was edited by another user before the update is saved, the operation will fail.
Q)Query a List by using CAML in SharePoint
Microsoft.SharePoint.SPQuery object has Query property that accepts a CAML fragment, which defines the query to be performed. A ViewFields property defines the fields to return.
Code Sample:
SPQuery query = new SPQuery;
query.Viewfields = @"<fieldref name="Title"><fieldref name="Expires">";
query.Query =
@"<where>
<lt>
<fieldref name="Expires">
<value type="DateTime"><today></today></value>
</fieldref></lt>
</where>";
SPList list = SPContext.Current.Web.Lists.TryGetList("Announcements");
SPListItemCollections items = list.GetItems(query);
</fieldref></fieldref>
Each FieldRef element has a Name attribute that specifies the name of the list field to return from the query.
The CAML fragment may contain Where, OrderBy, and GroupBy elements.
<where>
</where>
<orderby>
<fieldref>
</fieldref></orderby>
<groupby>
<fieldref>
<groupby>
</groupby></fieldref></groupby>
Where condition may contain:
And,BeginsWith,Contains,Eq,FieldRef,Geq,GroupBy,Gt,IsNotNull,IsNull,Join, Leq,Lt,Neq, Now,Or etc
SPQuery object can be used to query across two lists that are joined by a Lookup field.
Showing you a sample from Inside book:
SPWeb site = SPContext.Current.Web;
SPList listInstructors = site.Lists["Instructors"];
SPList listModules = site.Lists["Modules"];
SPQuery query = new SPQuery;
query.Query = "<where><eq><fieldref name="\"Audience\"/">" +
"<value type="\"Text\"">Developer</value></fieldref></eq></where>";
query.Joins = "<join type="\"Inner\"" listalias="\"classInstructors\"">" +
"<eq><fieldref name="\"Instructor\"" reftype="\"Id\"">" +
"<fieldref list="\"classInstructors\"" name="\"Id\""></fieldref></fieldref></eq></join>";
query.ProjectedFields =
"<field name="Email" type="Lookup" list="classInstructors" showfield="Email">";
query.ViewFields = "<fieldref name="\"Title\""><fieldref name="\"Instructor\"">" +
"<fieldref name="\"Email\"">";
SPListItemCollection items = listModules.GetItems(query);
</fieldref></fieldref></fieldref></field>
Q)How to get user profiles details programmatically in sharepoint 2010
The below 2 function will show how to get user profile and how to access the profile properties.
private UserProfile GetUserInfo(string AccountName)
{
UserProfile profile = null;
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
if (AccountName != string.Empty)
{
profile = profileManager.GetUserProfile(AccountName);
}
else
{
profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
}
return profile;
}
void GetCurrentUserDetails()
{
UserProfile userProfile = GetUserInfo("");
lblUserName.Text = GetUserName(userProfile);
if (userProfile[PropertyConstants.FirstName].Value != null)
{
lblUserName.Text += " (" + userProfile[PropertyConstants.FirstName].Value.ToString() + ")";
}
try
{
imgBtnUserImage.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();
}
catch (Exception ex)
{
imgBtnUserImage.ImageUrl = "/_layouts/ExpressionsWP/0.jpg";
}
if (userProfile[PropertyConstants.Department].Value != null)
{
ltrAddress.Text = userProfile[PropertyConstants.Department].Value.ToString();
}
if (ltrAddress.Text != string.Empty)
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += "," + userProfile[PropertyConstants.Location].Value.ToString();
}
}
else
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += userProfile[PropertyConstants.Location].Value.ToString();
}
}
}
Q)SPLimitedWebPartManager Class in SharePoint 2010?
It allows developer with direct access to the collection of Web Parts on a Web Part page.
It allows to add, customize, personalize, and delete Web Part instances
SPLimitedWebPartManager is available in SharePoint solutions deployed at the farm level, but it cannot be used in
sandboxed solutions.Here is a code sample to delete all the web parts in a page.
// Get Web Part Manager for home page
SPWeb site = (SPWeb)properties.Feature.Parent;
SPFile homePage = site.GetFile("default.aspx");
SPLimitedWebPartManager wpm;
wpm = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared);
// delete all Web Parts on page
while (wpm.WebParts.Count > 0) {
wpm.DeleteWebPart(wpm.WebParts[0]);
}
SPFile is used to get a web part page.
Q)How to delete or uninstall a custom site defination in sharepoint 2010?
Step-1
Go to the features directory of 14 hive folder and delete the folder name same with your site defination name.
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES
Step-2
Go to the directory webtemp*.xml file location and delete the corresponding webtemp_[site defination name]. The location is:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\1033\XML
Step-3
Make an IISRESET.
Q)HTTP Error 503. The service is unavailable in SharePoint
This error normally comes whenever a user changed the passoword
for the account. So to correct the error follow the below steps:
Go to Start -> All Programs -> Administrative Tools -> Internet
Information Services (IIS) Manager.
Then Click on(+) the server name -> Application Pools then locate
your application pools.
Right click on the Application pool name go to Advance settings ->
Go to process model then Identity Click on the Identity ->Set and
then give the user name, password and confirm password
To get the Page Title in SharePoint, you can follow the below approach.
User the below namespace:
using Microsoft.SharePoint;
Then write the below code to get the Title
String Title= SPContext.Current.Item["Title"].ToString();
Similarly you can get the URL in the below way
Sting URL=System.Web.HttpContext.Current.Request.Path;
Q)Generate Random password using C#.Net?
public GenerateRandomPassword()
{
String strGuid=System.Guid.NewGuid().ToString();
strGuid=strGuid.Replace("-",string.Empty);
strGuid=strGuid.Substring(0,8); //Here 8 means the password contains 8 characters.
}
Q)To create a list instance with SP object Model.
using System;
using Microsoft.SharePoint;
class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}
if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}
Q)How to use GetList() method?
SPList announcementsList = web.GetList("/Lists/Announcements");
Q)To create and save a new list item.
SPListItem newItem = list.Items.Add();
newItem ["Title"] = "Litware Goes Public!";
newItem ["Body"] = " We all live in exciting times.";
newItem["Expires"] = DateTime.Now + TimeSpan.FromDays(2);
newItem.Update();
Q) How to enumerate through the fields in a list by using a foreach construct?
foreach (SPField field in list.Fields)
{
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine(field.Title);
}
5. How to use CAML Query with SPQuery Object?
SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@"
//Write a query(using CAML)
";
SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}
Q)How to use SPSiteDataQuery ?
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";
string queryText =
@"
//Write a query(using CAML)
";
query.Query = queryText;
DataTable table = site.GetSiteData(query);
foreach (DataRow row in table.Rows) {
Console.WriteLine(row["Title"].ToString());
}
Q)Difference between SPquery and SPSiteDataQuery?
SPQuery object return an SPListItemCollection. SPSiteDataQuery object are different, because they return an ADO.NET DataTable object.
Q)Visit through document library in SharePoint Site.
SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;
// Add document library to DropDownList control
lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}
Q)Points about SharePoint List?
You can access a List by its name or by its URL.
When retrieving a list by name, you can use the TryGetList method of the SPListCollection, which returns null if the list does not exist.
When retrieving the list by the URL, you can use the GetList method of the SPWeb object, which throws a System.IO.FileNotFoundException if the list does not exist.
Code Samples:
using (SPSite siteCollection = new SPSite("Site URL"))
{
using (SPWeb site = siteCollection.OpenWeb)
{
SPList lstName = site.Lists.TryGetList("NameOfTheList");
if(lstName != null)
//do your work
else
//List does not exists
try
{
SPList taskList = site.GetList("/Lists/Tasks");
//do your work
}
catch(FileNotFoundException)
{
//List does not work
}
}
}
Lists maintain items in a Microsoft.SharePoint.SPListItemCollection object, which is accessible via the Items property of SPList.
Items in the collection are returned as Microsoft.SharePoint.SPListItem objects.
You can iterated over using a foreach statement, or directly accessed using either the item’s ID or index.
Each individual SPListItem maintains a Hashtable of values representing the properties of the item.
//Add new item to list
SPListItem newItem = list.Items.Add;
newItem["Title"] = "This will be the title";
newItem.Update;
//Bind the item to gridview
SPListItemCollection items = list.Items;
gridview1.DataSource = items;
gridview1.DataBind;
//Delete Item by Index
list.Items[0].Delete;
//Update Item by Index
SPListItem updateItem = list.Items[0];
updateItem["Title"] = "Updated Title";
updateItem.Update;
when creating new items in a list, the Update method must be called to save the new item. If the Update method is not called, then the list item will be lost.
if the item was edited by another user before the update is saved, the operation will fail.
Q)Query a List by using CAML in SharePoint
Microsoft.SharePoint.SPQuery object has Query property that accepts a CAML fragment, which defines the query to be performed. A ViewFields property defines the fields to return.
Code Sample:
SPQuery query = new SPQuery;
query.Viewfields = @"<fieldref name="Title"><fieldref name="Expires">";
query.Query =
@"<where>
<lt>
<fieldref name="Expires">
<value type="DateTime"><today></today></value>
</fieldref></lt>
</where>";
SPList list = SPContext.Current.Web.Lists.TryGetList("Announcements");
SPListItemCollections items = list.GetItems(query);
</fieldref></fieldref>
Each FieldRef element has a Name attribute that specifies the name of the list field to return from the query.
The CAML fragment may contain Where, OrderBy, and GroupBy elements.
<where>
</where>
<orderby>
<fieldref>
</fieldref></orderby>
<groupby>
<fieldref>
<groupby>
</groupby></fieldref></groupby>
Where condition may contain:
And,BeginsWith,Contains,Eq,FieldRef,Geq,GroupBy,Gt,IsNotNull,IsNull,Join, Leq,Lt,Neq, Now,Or etc
SPQuery object can be used to query across two lists that are joined by a Lookup field.
Showing you a sample from Inside book:
SPWeb site = SPContext.Current.Web;
SPList listInstructors = site.Lists["Instructors"];
SPList listModules = site.Lists["Modules"];
SPQuery query = new SPQuery;
query.Query = "<where><eq><fieldref name="\"Audience\"/">" +
"<value type="\"Text\"">Developer</value></fieldref></eq></where>";
query.Joins = "<join type="\"Inner\"" listalias="\"classInstructors\"">" +
"<eq><fieldref name="\"Instructor\"" reftype="\"Id\"">" +
"<fieldref list="\"classInstructors\"" name="\"Id\""></fieldref></fieldref></eq></join>";
query.ProjectedFields =
"<field name="Email" type="Lookup" list="classInstructors" showfield="Email">";
query.ViewFields = "<fieldref name="\"Title\""><fieldref name="\"Instructor\"">" +
"<fieldref name="\"Email\"">";
SPListItemCollection items = listModules.GetItems(query);
</fieldref></fieldref></fieldref></field>
Q)How to get user profiles details programmatically in sharepoint 2010
The below 2 function will show how to get user profile and how to access the profile properties.
private UserProfile GetUserInfo(string AccountName)
{
UserProfile profile = null;
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
if (AccountName != string.Empty)
{
profile = profileManager.GetUserProfile(AccountName);
}
else
{
profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
}
return profile;
}
void GetCurrentUserDetails()
{
UserProfile userProfile = GetUserInfo("");
lblUserName.Text = GetUserName(userProfile);
if (userProfile[PropertyConstants.FirstName].Value != null)
{
lblUserName.Text += " (" + userProfile[PropertyConstants.FirstName].Value.ToString() + ")";
}
try
{
imgBtnUserImage.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();
}
catch (Exception ex)
{
imgBtnUserImage.ImageUrl = "/_layouts/ExpressionsWP/0.jpg";
}
if (userProfile[PropertyConstants.Department].Value != null)
{
ltrAddress.Text = userProfile[PropertyConstants.Department].Value.ToString();
}
if (ltrAddress.Text != string.Empty)
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += "," + userProfile[PropertyConstants.Location].Value.ToString();
}
}
else
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += userProfile[PropertyConstants.Location].Value.ToString();
}
}
}
Q)SPLimitedWebPartManager Class in SharePoint 2010?
It allows developer with direct access to the collection of Web Parts on a Web Part page.
It allows to add, customize, personalize, and delete Web Part instances
SPLimitedWebPartManager is available in SharePoint solutions deployed at the farm level, but it cannot be used in
sandboxed solutions.Here is a code sample to delete all the web parts in a page.
// Get Web Part Manager for home page
SPWeb site = (SPWeb)properties.Feature.Parent;
SPFile homePage = site.GetFile("default.aspx");
SPLimitedWebPartManager wpm;
wpm = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared);
// delete all Web Parts on page
while (wpm.WebParts.Count > 0) {
wpm.DeleteWebPart(wpm.WebParts[0]);
}
SPFile is used to get a web part page.
Q)How to delete or uninstall a custom site defination in sharepoint 2010?
Step-1
Go to the features directory of 14 hive folder and delete the folder name same with your site defination name.
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES
Step-2
Go to the directory webtemp*.xml file location and delete the corresponding webtemp_[site defination name]. The location is:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\1033\XML
Step-3
Make an IISRESET.
Q)HTTP Error 503. The service is unavailable in SharePoint
This error normally comes whenever a user changed the passoword
for the account. So to correct the error follow the below steps:
Go to Start -> All Programs -> Administrative Tools -> Internet
Information Services (IIS) Manager.
Then Click on(+) the server name -> Application Pools then locate
your application pools.
Right click on the Application pool name go to Advance settings ->
Go to process model then Identity Click on the Identity ->Set and
then give the user name, password and confirm password
What's Taking place i'm new to this, I stumbled upon this I have discovered It positively helpful and it has helped me out loads.
ReplyDeleteI hope to contribute & aid different customers like its aided me.
Good job.
Also visit my web page :: earn cash for doing stuff you normally do on the internet
Ӏ nеed tο get it done cus I won't have the opportunity to get it done if not!
ReplyDeleteHave a look at my page ... www.datecity.com
Ӏ need to get it done сus Ӏ won't have the opportunity to get it done if not!
ReplyDeleteTake a look at my page - www.datecity.com
Looks likelу that the cat is οut of the bаg on this.
ReplyDelete.... І'll have to have a look and see whats coming....
my web blog: small personal loans
Lol I shаred thiѕ too. It's well funny.
ReplyDeleteAlso visit my web blog :: fast and easy loans
Loοκs lіke the cat's out of the bag on this... have a look to see whats coming....
ReplyDeleteReview my web page ... fast cash loans for people with bad credit
Have not yet reаԁ аbout thіs іdea bеfоre,
ReplyDeleteI ought to do so veгy soon.
Hеre iѕ mу blog post; Best payday loans Uk
Ѕpuг of the moment uρdates aге аlways beѕt, the sеntencеs јust ρour out ontο
ReplyDeletethe sсrеen.
Feel fгeе to surf to my wеb site; fast cash today
its sο hot.
ReplyDeleteAlsо visit my webpage best uk loans
Oh well. Get yοurself a glass of milk when youre homе, run a bath and let go.
ReplyDeleteHеre iѕ my blog; best personal loan
Dіd you loοκ up аny refеrences beforе you сamе up
ReplyDeletewith thiѕ?
Look into mу ρage - personal loans uk
Noω then еveгybody lets all calm down,
ReplyDeletehаve a гelaxing wаrm bath and a cup of tеa.
Alsο νіsit my blog :: borrow money fast
Aah I see! I thought that was an optional crazy addition.
ReplyDeleteFeеl free to ѵisit mу wеbsitе; best loan deal
How did theѕе replіes get ѕo confused it's drainin reading em.
ReplyDeleteMy homepage: loans fast
Wе are all a suckеr fοr an octopus.
ReplyDeleteHa ha ha...
Alsο visit mу weblοg; best value loans
What are youг referenceѕ fоr this artіcle?
ReplyDeleteMy blog post :: small personal loans
This hаѕ made me contemplate іf theгe's a few ways I could do things more efficiently.
ReplyDeleteFeel free to visit my weblog ... Personal Loans
Well done for managing tο gеt by for
ReplyDeletethat lοng.
Alѕо viѕіt my homеpage: best rate loan
Do not rеkon I understand thiѕ 2 b true. Mуt аv to go elswhеre 2 get it.
ReplyDeletemу blog post: best personal loans
Haha І sharеd thiѕ too. It's ace.
ReplyDeleteHere is my webpage: best loans uk
I've been looking for a reliable article on this for weeks, and this has been a good help. I'll be getting this гe-tweеted for sure.
ReplyDeletemy homepage; personal loans
I am thіnking at what agе you start to get wіser аnd get used to all this
ReplyDeletenonsеnѕe.
My site; personal loans uk
Did you eνaluаte any rеferences befoгe you ωrote
ReplyDeleteall this doωn?
Take а look at mу ѕite - cheap personal loans
Simply desire to say your article is as astonishing. The clearness in your post is simply
ReplyDeletecool and i can assume you're an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.
Look into my web blog play and get Minecraft for free
Hi,In many ways this is true of any Web Design Cochin process - navigation is no way near as sexy as that lovely design look! Supermarkets have traditionally spent a lot of time getting those aisles lined up so that you buy items you don't really need.Thanks.....
ReplyDelete