Set or Get value people editor control in SharePoint 2007 with C#
How to get and set the value of a people editor control programatically in SharePoint 2007 ?
Get People Editor Values
This code demostrate how to get people editor control values and insert a sharepoint list
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["myList"].Items;
SPListItem item = listItems.Add();
item["Title"] = this.txtTitle.Text.ToString();
item["Location"] = this.lblLocations.Text.ToString();
item["EventDate"] = txtStart.SelectedDate ;
string[] UsersSeperated = pplEditor.CommaSeparatedAccounts.Split(',');
SPFieldUserValueCollection UserCollection = new SPFieldUserValueCollection();
foreach (string UserSeperated in UsersSeperated)
{
mySite.EnsureUser(UserSeperated);
SPUser User = mySite.SiteUsers[UserSeperated];
SPFieldUserValue UserName = new SPFieldUserValue(mySite, User.ID, User.LoginName);
UserCollection.Add(UserName);
}
item["people"] = UserCollection;
item.Update();
Set People Editor values from Sharepoint List
This code demostrate how to set people editor control values from a sharepoint list
SPSite site = SPContext.Current.Site;
SPWeb myweb = site.OpenWeb();
SPList mylist = myweb.Lists["MyList"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='ID'/>" +
"<Value Type='Text'>" + e.Value.ToString() + "</Value></Eq></Where>";
SPListItemCollection items = mylist.GetItems(query);
foreach (SPListItem item in items)
{
try
{
this.txtTitle.Text = item["Title"].ToString();
this.txtStart.SelectedDate = Convert.ToDateTime(item["EventDate"].ToString());
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
ArrayList _arrayList = new ArrayList();
SPFieldUserValueCollection users = item["People"] as SPFieldUserValueCollection;
if (users != null)
{
foreach (SPFieldUserValue user in users)
{
PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
_pickerEntity.Key = user.User.LoginName;
_pickerEntity.IsResolved = true;
_arrayList.Add(_pickerEntity);
}
pplEditor.UpdateEntities(_arrayList);
}
}
Embedding Ajax Control ToolKit into SharePoint 2007
To enabling Ajax for the first time in SharePoint 2007, you need first to configure your SharePoint Portal to support AJAX. To do this, it is better to open a new AJAX web site in Visual Studio to pick a copy from configuration sections in web.config
1– Add the following part under: <configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" /> <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> </sectionGroup> </sectionGroup> </sectionGroup>
2– Add the following part under: <pages >
<controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </controls>
3– Add the following part under : <compilation><assemblies>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
4– Add the following part under: <httpHandlers>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, SSystem.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
5– Add the following part under: <httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
6– At the end of web.config add the following part under: <configuration>
<system.web.extensions> <scripting> <webServices> <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. --> <!-- <authenticationService enabled="true" requireSSL = "true|false"/> --> <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and writeAccessProperties attributes. --> <!-- <profileService enabled="true" readAccessProperties="propertyname1,propertyname2" writeAccessProperties="propertyname1,propertyname2" /> --> </webServices> <!-- <scriptResourceHandler enableCompression="true" enableCaching="true" /> --> </scripting> </system.web.extensions> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules> <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated" /> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </handlers> </system.webServer>
7– Add following part under: <SafeControls>
<SafeControl Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TypeName="*" Safe="True" />
CX_UserMemberships_RecordId_MemberGroupId_SID Event Source: Office SharePoint Server
Error :
failure trying to synch site abc12d90-7d1d-4341-8df3-a1d92eba7a47 for ContentDB db7fb0d6-7d0d-4230-8de5-e7cc00ca0db7 WebApp e4b621e3-148d-4822-96bf-357b341b715d. Exception message was Cannot insert duplicate key row in object 'dbo.UserMemberships' with unique index 'CX_UserMemberships_RecordId_MemberGroupId_SID'. The statement has been terminated..
Solving:
to solve this error on SharePoint 2007 FARM run a Query on Configration Database and take the name webapplication
SELECT Id, ClassId, ParentId, Name, Status, Version, Properties
FROM Objects
WHERE (Id = 'e4b621e3-148d-4822-96bf-357b341b715d')
and run this 3 stsadm command on your sahrePoint enviroment
stsadm -o preparetomove -ContentDB YOUR_SQL_SERVER_NAME:YOUR_SITE_CONTENT_DB_NAME -Site http://yourSiteName
stsadm -o deletecontentdb -url http://yourSiteName -databaseserver YOUR_SQL_SERVER_NAME -databasename YOUR_CONTENT_DB_NAME
stsadm -o addcontentdb -url http://yourSiteName -databasename YOUR_CONTENT_DB_NAME -databaseserver YOUR_SQL_SERVER_NAME
Windows Update Error Code 80070490
To troubleshoot this issue, I suggest we first reset permission and
reinstall Windows Update Agent 3.0.
Step 1: Reset permission
1. Please download the subinacl.msi file from the following link and save
the installation patch onto the Desktop:
http://www.microsoft.com/downloads/details.aspx?FamilyID=e8ba3e56-d8fe-4a91-93cf-ed6985e3927b&displaylang=en#AffinityDownloads
2. Please go to the Desktop and double click the downloaded file.
3. install Downloded fie to your system. To do this Run as adminstration to command promt.
4. Add installation file to windows path PATH and run notepad
5. Copy the following commands and then paste them into the opened Notepad
window:
@echo off
subinacl /subkeyreg HKEY_LOCAL_MACHINE /grant=administrators=f
subinacl /subkeyreg HKEY_CURRENT_USER /grant=administrators=f
subinacl /subkeyreg HKEY_CLASSES_ROOT /grant=administrators=f
subinacl /subdirectories %SystemDrive% /grant=administrators=f
subinacl /subkeyreg HKEY_LOCAL_MACHINE /grant=system=f
subinacl /subkeyreg HKEY_CURRENT_USER /grant=system=f
subinacl /subkeyreg HKEY_CLASSES_ROOT /grant=system=f
subinacl /subdirectories %SystemDrive% /grant=system=f
@Echo =========================
@Echo Finished.
@Echo =========================
@pause
6. After pasting the above commands, please close the Notepad window. Choose
Save when you are prompted to save the file. Type "reset.bat" as the file
name and choose Desktop from the left panel as the save location.
7. Refer to the Desktop and right click the reset.bat file, then choose "Run
as administrator."
8. You will see a DOS-like window processing.
NOTE: It may take several minutes, please be patient. When it is finished,
you will be prompted with the message: "Finished, press any key to continue".
Step 2: download Windows Update agent from http://support.microsoft.com/kb/949104 and Reinstall Windows Update Agent 3.0
SharePoint Management Studio - Solution Deployer
SharePoint Management Studio is a Open Source SharePoint Administration Tools that helps you manage your sharepoint enviroment simple and easy. SharePoint Management Studio (SPMS) has a module named Solution Deployer. Solution deployer is a powerfull application to deploy your solutions easy. Solution Deployer can deploy multible solution file to multible web applications. For example you need to new Sharepoint farm as a preprotuction and you want to same configration to production to preprotuction. Notice that you install new farm and create all webapplication now you can add solution new farm and deply it global or web applications. if you has 10 solution files and 5 web application you can perform 100 jobs to do this. Because you must run 10 addsolution command and 10 solutin X 5web applications deploy. Solution Deployer do all of them for you. (http://spms.codeplex.com/)
The other properties is Solution deployer understand solution file type authomaticly. GLOBAL deployet or web application deployment.
SharePoint Management Studio - Download installed Solutions
SharePoint Management Studio is a Open Source SharePoint Administration Tools that helps you manage your sharepoint enviroment simple and easy. SharePoint Management Studio (SPMS) has a module named Download installed Solutions to export Solution Files from Solution Store.By default Sharepoint don't allow download your solutions on central admin. (http://spms.codeplex.com/)
This section has only two options one of them Deploy Solution and the other one is Romove Solution. One day I lost my solution instalation setup and wsp file and I need to deploy same solution the other farm. This tool was very usefull for me. Download this application source code codeplex or my site and run application your Sharepoint enviroment. Application load your web application list and wait your selection wich application solution(s) you want to download or global deployed applications.
Click wich solution you want download and click Save as button. Application ask you a destination directory. Select ona and click okey. Finaly application save your solution which you lost setup or wsp, download your destination directory.
Working with SPFile in Sharepoint
SPFile class help us working with Sharepoint list attachments. I want to explain SPFile class with some console application. The first console application working with Personel List attachments and display Attachment full name and their file size;
using (SPSite site = new SPSite("http://testsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.GetList("/Lists/Personel/");
foreach(SPListItem item in list.Items)
{
foreach (string name in item.Attachments)
{
string fullname = item.Attachments.UrlPrefix + name;
SPFile files = item.Web.GetFile(fullname);
Console.WriteLine("File Name {0}, fileSize {1} kb",
fullname, files.Length);
}
}
}
}
}
This console application connect to http://testsite/ (This is my test site, change it your test enviromet) and get Personel list. Result of display attachment full path and their size like this.
Sample code : SPListAttachments.rar (349.27 kb)
Download A List Attachments Programatically
For example I want to download all attechments on personel list ( no shared documents). This code sample done it.
foreach (string name in item.Attachments)
{
string fullname = item.Attachments.UrlPrefix + name;
SPFile files = item.Web.GetFile(fullname);
Console.WriteLine("Downloded file: {0} ", name);
byte[] binFile = files.OpenBinary();
System.IO.FileStream fstream =
System.IO.File.Create("c:\\Temp\\" + files.Name);
fstream.Write(binFile, 0, binFile.Length);
}
Sample Code : SpDownloadAttachments.rar (349.85 kb)
Download Shared Document library Programatically
using (SPSite site = new SPSite("http://testsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList doclib = web.Lists["Documents"];
foreach (SPListItem item in doclib.Items)
{
byte[] binFile = item.File.OpenBinary();
System.IO.FileStream fstream =
System.IO.File.Create("c:\\Temp\\" + item.File.Name);
fstream.Write(binFile, 0, binFile.Length);
}
}
}
Sample Code : SPDownloadDocuments.rar (349.76 kb)
Difference between SpListItem.Update and SpListItem.SystemUpdate
To update a list item we have two ways. One of them is SPListitem.Update and its is most popular way. But this method is change version history and trigger all alerts. Some times, some reason you can want to avoid change version history or triggering allerts. Like this case, SpListitem.SystemUpdate medhod help us. Because that SystemUpdate() is not changing version history.
For Example; I have a list name Personel and I want to change secont record by a console application with SPitem.Update method. Before Run this code sample my list item history like this.
using (SPSite site = new SPSite("http://testsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Personel"];
SPListItem item = list.Items[1];
item["Title"] = "Sample Update with Versions.";
item.Update();
list.Update();
}
}
After work this Consle Application secont item version history changin like this;
The outher mathod which SystemUpdate() don't add new version history.
using (SPSite site = new SPSite("http://testsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Personel"];
SPListItem item = list.Items[1];
item["Title"] = "Sample Update with out add Versions";
item.SystemUpdate();
list.Update();
}
}
Finnaly My item history changing but not a new version number.
Download Sample Code : SPSystemUpdate.rar (348.76 kb)
Bind the List Data to a DataGird Control
To Bind the List Data to a DataGrid Control, you can write like this example webpart. This web part connect to Personel List and convert List data to DataTable Object.
protected override void CreateChildControls()
{
base.CreateChildControls();
SPWeb site = SPControl.GetContextWeb(Context);
SPList List = site.Lists["Personel"];
SPListItemCollection Listitems = List.Items;
DataTable MyTable = Listitems.GetDataTable();
DataGrid MyGrid = new DataGrid();
MyGrid.DataSource = MyTable;
MyGrid.DataBind();
this.Controls.Add(MyGrid);
}
After the publish this webpart your test site via Visual Studio. it's avalibel to add as webpart like this.
To Download This sample application Click BindTheListData.rar (358.57 kb)
Writing CAML Queries
The Collaborative Application Markup Language (CAML) is an XML-based query language that helps you querying and customizing Web sites based on Windows SharePoint Services. CAML Quesies has a root element named Query and Query element has two optional elements named Order by elemet and Where elemet.
<Query>
<OrderBy>
<!-- Query elemend to sort result data-->
</OrderBy>
<Where>
<!--Query elemet to filter data-->
</Where>
</Query>
Order By Element
Order by elemet use to sort resutl data for example, You create a Microsoft Windows SharePoint Service list named Personel. And you want to sort of data by FirstName column. To do this you can write like this CAML Query.
<OrderBy>
<FieldRef Name='FirstName' />
</OrderBy>
The order by element has one or more fields which you want to sort. The other detail about order by is Ascending or Descending. İf you want to sort data Descending, You must change your query <FieldRef Name='FirstName' Ascending='False' /> because that Ascending is a default key and value is True.
Where Element
The where element is the other part of CAML Queries. Where element help us filtering data. For ex. I want to filter list data by LastName = Kemal.
<Where>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Kemal</Value>
</Eq>
</Where>
And tihs example I want to add the other criteria which City = Istanbul to to this change the query a bit and add a new key <And>.
<Where>
<And>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Kemal</Value>
</Eq>
<Eq>
<FieldRef Name='City' />
<Value Type='Text'>İstanbul</Value>
</Eq>
</And>
</Where>
The CAML Query Operators
| Eq |
Equals |
== |
| Neq |
Not Equals |
!= |
| Gt |
Greater than |
> |
| Geq |
Greater than or equal |
>= |
| Lt |
Lower than |
< |
| Leq |
Lower than or equal |
<= |
| IsNull |
Is Null |
|
| BeginsWith |
Begins With |
|
| Contains |
|
|