Skip to main content

Sharepoint Programming-Part 3

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

Comments

  1. 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.
    I 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

    ReplyDelete
  2. Ӏ nеed tο get it done cus I won't have the opportunity to get it done if not!

    Have a look at my page ... www.datecity.com

    ReplyDelete
  3. Ӏ need to get it done сus Ӏ won't have the opportunity to get it done if not!

    Take a look at my page - www.datecity.com

    ReplyDelete
  4. Looks likelу that the cat is οut of the bаg on this.
    .... І'll have to have a look and see whats coming....

    my web blog: small personal loans

    ReplyDelete
  5. Lol I shаred thiѕ too. It's well funny.

    Also visit my web blog :: fast and easy loans

    ReplyDelete
  6. Loοκs lіke the cat's out of the bag on this... have a look to see whats coming....

    Review my web page ... fast cash loans for people with bad credit

    ReplyDelete
  7. Have not yet reаԁ аbout thіs іdea bеfоre,
    I ought to do so veгy soon.

    Hеre iѕ mу blog post; Best payday loans Uk

    ReplyDelete
  8. Ѕpuг of the moment uρdates aге аlways beѕt, the sеntencеs јust ρour out ontο
    the sсrеen.

    Feel fгeе to surf to my wеb site; fast cash today

    ReplyDelete
  9. its sο hot.

    Alsо visit my webpage best uk loans

    ReplyDelete
  10. Oh well. Get yοurself a glass of milk when youre homе, run a bath and let go.


    Hеre iѕ my blog; best personal loan

    ReplyDelete
  11. Dіd you loοκ up аny refеrences beforе you сamе up
    with thiѕ?

    Look into mу ρage - personal loans uk

    ReplyDelete
  12. Noω then еveгybody lets all calm down,
    hаve a гelaxing wаrm bath and a cup of tеa.


    Alsο νіsit my blog :: borrow money fast

    ReplyDelete
  13. Aah I see! I thought that was an optional crazy addition.



    Feеl free to ѵisit mу wеbsitе; best loan deal

    ReplyDelete
  14. How did theѕе replіes get ѕo confused it's drainin reading em.

    My homepage: loans fast

    ReplyDelete
  15. Wе are all a suckеr fοr an octopus.

    Ha ha ha...

    Alsο visit mу weblοg; best value loans

    ReplyDelete
  16. What are youг referenceѕ fоr this artіcle?



    My blog post :: small personal loans

    ReplyDelete
  17. This hаѕ made me contemplate іf theгe's a few ways I could do things more efficiently.

    Feel free to visit my weblog ... Personal Loans

    ReplyDelete
  18. Well done for managing tο gеt by for
    that lοng.

    Alѕо viѕіt my homеpage: best rate loan

    ReplyDelete
  19. Do not rеkon I understand thiѕ 2 b true. Mуt аv to go elswhеre 2 get it.


    mу blog post: best personal loans

    ReplyDelete
  20. Haha І sharеd thiѕ too. It's ace.

    Here is my webpage: best loans uk

    ReplyDelete
  21. 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.


    my homepage; personal loans

    ReplyDelete
  22. I am thіnking at what agе you start to get wіser аnd get used to all this
    nonsеnѕe.

    My site; personal loans uk

    ReplyDelete
  23. Did you eνaluаte any rеferences befoгe you ωrote
    all this doωn?

    Take а look at mу ѕite - cheap personal loans

    ReplyDelete
  24. Simply desire to say your article is as astonishing. The clearness in your post is simply
    cool 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

    ReplyDelete
  25. 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

Post a Comment

Popular posts from this blog

Tab Control in Asp.Net

Scenerio: I need your help in designing tab control in   asp.net .My requirement is I need a tab control in   asp.net (C#) like  for example goto my computer ,right click c drive and select properties.we get tabs like general,security etc....... like that i need to design one tab control(no need of any rightclick) in my web page and the database table columns should come as tabs and inseide the tab data of that particular column should come.   Example:Employee master tab1:Employee name.........his name in the tab tab2:Age.............his age tab3:Address........his address   Solution:   You can do this using a simple div <style type="text/css"> .tabs         {             position: relative;             height: 20px;             margin: 0;   ...

AI and Microsoft: Revolutionizing Efficiency in Nonprofit Organizations

  How AI and Microsoft Enhance Efficiency in Nonprofit Organizations In today’s fast-paced world, nonprofit organizations face unique challenges—limited resources, increasing demands, and the constant need to do more with less. But what if technology could be the game-changer they need? In my latest research paper,  "How AI and Microsoft Enhance Efficiency in Nonprofit Organizations" , I explore how cutting-edge technologies like Artificial Intelligence (AI) and Microsoft’s innovative tools are revolutionizing the way nonprofits operate. From streamlining administrative tasks to enhancing donor engagement and optimizing resource allocation, AI and Microsoft’s solutions are empowering nonprofits to focus on what truly matters—their mission. This paper dives deep into real-world examples, practical applications, and the transformative potential of these technologies. Whether you’re a nonprofit professional, a tech enthusiast, or simply curious about the intersection of technolo...

Social tagging overview in Sharepoint 2010

A tag is a word or phrase that identifies an individual piece of information according to a set of attributes or criteria. Tags make it easy to find and share information about a specific subject or task. Social tagging helps users categorize information in ways that are meaningful to them. Social tagging can improve the quality of search results by filtering against specific tags, and it can also connect individuals who want to share information with other users who have like interests. This article describes the social tagging features in Microsoft SharePoint Server 2010. This article does not describe how to configure social tagging features. It also does not discuss how to implement social tagging features as part of an overall social media strategy for an enterprise. About using social tagging features Social tagging features help users to share information and to retrieve relevant, high-quality content more efficiently. Such sharing encourages collaboration and b...