I am playing around with a SharePoint server and I am trying to programmatically add a service request to microsoft's call center application template. So far, I have had pretty good success. I can add a call for a specified customer and assign a specific support tech:
private enum FieldNames
{
[EnumExtension.Value("Service Request")]
ServiceRequest,
[EnumExtension.Value("Customer")]
Customer,
[EnumExtension.Value("Service Representative")]
ServiceRepresentative,
[EnumExtension.Value("Assigned To")]
AssignedTo,
[EnumExtension.Value("Software")]
Software,
[EnumExtension.Value("Category")]
Category
}
private void CreateServiceCall(string serviceCallTitle, string customerName, string serviceRep)
{
SPSite allSites = new SPSite(siteURL);
SPWeb site = allSites.AllWebs[siteName];
SPListItemCollection requestsList = site.Lists[serviceRequests].Items;
SPListItem item = requestsList.Add();
SPFieldLookup customerLookup = item.Fields[FieldNames.Customer.Value()] as SPFieldLookup;
item[FieldNames.ServiceRequest.Value()] = serviceCallTitle;
if (customerLookup != null)
{
using (SPWeb lookupWeb = allSites.OpenWeb(customerLookup.LookupWebId))
{
SPList lookupList = lookupWeb.Lists.GetList(new Guid(customerLookup.LookupList), false);
foreach (SPListItem listItem in lookupList.Items)
{
if (listItem[customerLookup.LookupField].ToString() != customerName) continue;
item[FieldNames.Customer.Value()] = new SPFieldLookupValue(listItem.ID, customerName);
break;
}
}
}
SPUserCollection userCollection = site.SiteUsers;
if (userCollection != null)
{
foreach (SPUser user in userCollection)
{
if (user.Name != serviceRep) continue;
item[FieldNames.AssignedTo.Value()] = user;
break;
}
}
item.Update();
site.Close();
allSites.Close();
}
I added two custom columns (category, software) to the default list:
I populated both of these columns inside of SharePoint, now I want to retrieve that data so I can use it in the code snippet I posted to assign the proper category/software etc to the call. I have not been able to get the list in the code, I have tried using a item["Software"], site.Lists["Software"] and a couple of others, but so far all I have come up is null.
Can anyone point me in the right direction for this? Thanks!
SPFieldMultiChoice and related fields have a Choices property:
SPFieldMultiChoice software = item.Fields[FieldNames.Software.Value()] as SPFieldMultiChoice;
StringCollection softwareChoices = software.Choices;
If you need to set a value on the field, use the SPFieldMultiChoiceValue type:
SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue();
values.Add("Choice 1");
values.Add("Choice 2");
item[FieldNames.Software.Value()] = values;
Related
I am making a windows application that sync the source data to Active Directory.
This application works like this.
Choose Source Data(Department, User)
Mapping user or department attributes from source data
When Application service is run, it create groups and users in Active Directory
And also it sets the attributes to users and groups.
When I try to set group or user attributes(properties), it throws exception message like this.
in DirectoryEntry.CommitChanges(); block
The directory
service cannot perform the requested operation on the RDN attribute of an object.
I tried to solve it, but it's really hard to me because I`m not good at Active directory...
Code is below, Please share your knowledge.
//ppk: department key column, pk:user key column, row : Source DataTable's row
void CreateADUser(string ppk,string pk,DataRow row)
{
//password
string pass = GetPass(pk,row,LogSections.AD);
//OU
DirectoryEntry addept = adm.FindOU(ppk);
//principal path
string sOU = adm.GetPrincipalPath(addept);
var aduser = adm.CreateNewUser(sOU, pk, pass, pk, null, null, adm.sDomain);
SetAdUserProperties(pk, pass, row);
MoveUser(ppk,pk);
}
void SetAdUserProperties(string pk,string pass,DataRow row)
{
if (row == null) return;
//list of mapped column(AD User attributes)
List<ADMapping> MappingPatterns = GetAdMappings(Words.User,false);
//Columns name of Source Data table's row
var colnames = Tool.GetColNames(row);
//get user proterties
var aduser = adm.GetUser(pk);
//directory entry of users
var de=aduser.GetUnderlyingObject() as DirectoryEntry;
//looping mapped column of user attributes
foreach (var ADMap in MappingPatterns)
{
string val = ADMap.Mapping;
//mapped columns value
val=Util.ReplaceColPattern(val, row);
SetProperty(de, ADMap.CN, val);
}
if (!string.IsNullOrWhiteSpace(pass))
{
var UserPkColumn = AppConfigHelper.GetAppString(Words.SourceUserPKColumn);
UserPkColumn = Util.GetActualColName(UserPkColumn);
aduser.SetPassword(pass);
QueryHelper.Update(QueryHelper.ConnectionString, Words.ShadowUserTable
,new SqlParameter[] { new SqlParameter("#passwd", pass) }
, new SqlParameter("#"+UserPkColumn,pk));
}
aduser.Save();
}
public void SetProperty(DirectoryEntry oDE, string sPropertyName, object sPropertyValue)
{
if (sPropertyValue != null && !string.IsNullOrWhiteSpace(sPropertyValue.ToString()))
{
if (oDE.Properties.Contains(sPropertyName))
{
oDE.Properties[sPropertyName].Value = sPropertyValue;
}
else
{
oDE.Properties[sPropertyName].Add(sPropertyValue);
}
try
{
oDE.CommitChanges(); //exception here.
oDE.Close();
}
catch (Exception)
{
}
}
}
I also asked this question to other forums, and finally got it.
Before DirectoryEntry.CommitChanges(); set UserPropertyCache property to true
and call the RefreshCache method.
It's hard to see what's the cause of the issue here as we're not seeing what attributes you are trying to set.
That said, you can't just add an attribute if it doesn't exist on your AD object so this part of your code definitely has an issue :
if (oDE.Properties.Contains(sPropertyName))
{
oDE.Properties[sPropertyName].Value = sPropertyValue;
}
else
{
//The following line will never work in this context
oDE.Properties[sPropertyName].Add(sPropertyValue);
}
If I had to make an educated guess, I'd say you're either trying to set an attribute that can't be set, or the User you're adding doesn't have all it's mandatory attributes set.
I am making an Active Directry managment tool but I am having trouble getting somethings working.
While I made a class where I want to find a specific user and return als his information(Name,Fullname,CN,...). I can find all this information but when I don't know the best way to return all the values from my class.
Here is the code I use so far:
DirectorySearcher search = new DirectorySearcher(ldapConnectie);
search.Filter = "(cn=" + username + ")";
SearchResult result = search.FindOne();
if (result != null)
{
List<string> listLdapFields = new List<string>();
List<Object> listLdapValues = new List<Object>();
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
listLdapFields.Add(ldapField);
foreach (Object myCollection in fields[ldapField])
{
listLdapValues.Add(myCollection);
}
}
}
The program add everything well to a list. But if I return this I cannot search the list on "CN" or "Name". I can only find the information on Index Number.
Hope you can help me out.
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
if(user != null)
{
// do something here....
// the most often used attributes are available as nice, strongly-typed properties
string value = user.GivenName;
value = user.Surname;
value = user.EmailAddress;
value = user.VoiceTelephoneNumber;
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
Here's an approach where you can call the property by name. It also uses the authenticated account making the request.
string domainPath = String.Format("LDAP://{0},DC=site,DC=com", domain);
using (DirectoryEntry searchRoot = new DirectoryEntry(domainPath))
{
using (DirectorySearcher search =
filterSearch(new DirectorySearcher(searchRoot), username))
{
SearchResult result = null;
try
{
result = search.FindOne();
}
catch (DirectoryServicesCOMException e)
{
//handle the error
}
if (result != null)
{
string givenname = result.Properties["givenname"].Count > 0 ?
(string)result.Properties["givenname"][0] : "";
string sn = result.Properties["sn"].Count > 0 ?
(string)result.Properties["sn"][0] : "";
var samaccount= result.Properties["samaccountname"].Count > 0 ?
(string)result.Properties["samaccountname"][0] : "";
var name = String.Format("{0}, {1}", sn, givenname);
var email = result.Properties["mail"].Count > 0 ?
(string)result.Properties["mail"][0] : "";
}
}
}
//Apply a filter to search only specific classes and categories.
//Add the specific properties to be retrieved
private DirectorySearcher filterSearch(DirectorySearcher search, string username)
{
DirectorySearcher filteredSearch = search;
filteredSearch.Filter = "(&(objectClass=user)(objectCategory=person)(samaccountname=" + username + "))";
filteredSearch.PropertiesToLoad.Add("givenname");
filteredSearch.PropertiesToLoad.Add("sn");
filteredSearch.PropertiesToLoad.Add("samaccountname");
filteredSearch.PropertiesToLoad.Add("department");
filteredSearch.PropertiesToLoad.Add("physicalDeliveryOfficeName");
filteredSearch.PropertiesToLoad.Add("mail");
return filteredSearch;
}
This may be helpful if looking for specific properties, but if you want to retrieve a list of all attributes/values, take a look at this other SO question.
Google has a list of common filters you can use. Take a look through them and modify the filterSearch method appropriately.
I have an issue, where by each user in my user list is showing as on-line when I know they're not.
When the page is loaded, they show as offline, but if I refresh the page, they all show as on-line. I'm assuming this is because I'm programmatically accessing their profile information (CommonProfile) to get the data to show on the gridview?
Is there any way to get the profile information without triggering the IsOnline property to be true?
Update:
Sorry, code is here. Please be gentle, I'm relatively new to c# & asp.net and I'm still learning.
The code is collecting information from Membership user and the common profiles and adding the fields to a datatable so that i can display the results in a gridview.
MembershipUserCollection usersList = Membership.GetAllUsers();
MembershipUserCollection filteredUsers = new MembershipUserCollection();
foreach (MembershipUser user in usersList)
{
if (!Roles.IsUserInRole(user.UserName, "Admin") && !Roles.IsUserInRole(user.UserName, "Engineering"))
{
if (txtFilterCustomerNo.Text.Length > 0)
{
ProfileCommon PC = Profile.GetProfile(user.UserName);
if (PC.CompanyAccountNo == txtFilterCustomerNo.Text.ToUpper())
{
filteredUsers.Add(user);
}
}
else
{
filteredUsers.Add(user);
}
}
}
txtFilterCustomerNo.Text = null;
foreach (MembershipUser user in filteredUsers)
{
userProfile = Profile.GetProfile(user.UserName);
string[] userRoles = Roles.GetRolesForUser(user.UserName);
DataRow orderLine = dataSet.Tables["UserAccounts"].NewRow();
orderLine["USER_NAME"] = user.UserName;
orderLine["CREATED"] = user.CreationDate;
orderLine["LAST_LOGIN"] = user.LastLoginDate;
orderLine["PASSWORD_CHANGED"] = user.LastLoginDate;
orderLine["ACTIVE"] = user.IsApproved;
orderLine["ONLINE"] = user.IsOnline;
orderLine["LOCKED"] = user.IsLockedOut;
orderLine["CUSTOMER_NO"] = userProfile.CompanyAccountNo;
orderLine["HAS_INVENTORY"] = userProfile.HasOwnInventory;
orderLine["ORDER"] = userRoles.Contains("Order");
orderLine["REPAIR"] = userRoles.Contains("Repair");
orderLine["WARRANTY"] = userRoles.Contains("Warranty");
orderLine["COMMISSIONING"] = userRoles.Contains("Commissioning");
orderLine["ACCOUNT"] = userRoles.Contains("Account");
dataSet.Tables["UserAccounts"].Rows.Add(orderLine);
}
if (dataSet.Tables.Contains("UserAccounts"))
{
GridView1.DataSource = dataSet.Tables["UserAccounts"];
}
If you simply looked at the different overloads of GetUser, you would see that some of them take a Boolean called userIsOnline. If you specify this as false, it will not update the last online timestamp, and will not list them as online.
var user = Membership.GetUser(userid, false);
EDIT:
I see you are using GetAllUsers() rather than GetUser(). There are some problems with GetAllUsers() and you cannot rely on the IsOnline property. Instead, you need to check the LastActivityDate field and figure out the difference between that and the current DateTime. If the amount of time is greater than what you consider "Online" to be, then they are offline, otherwise online.
We have a large public contacts folder in Outlook called Global Contacts, I'd like to be able to search through it and return a number of results that match certain criteria, ideally wildcard-style.
E.g. if someone puts "je" in the 'name' textbox, it will return all contacts whose names contain 'je'. This may be coupled as an AND with a companyname textbox.
Most of the examples I've seen are either in VB, or are concerned with doing this form a web app - I'm doing a winforms app, and every machine has Outlook 2002 installed (yeah, I know, update long overdue).
Can anyone point me in the right direction? Some code would be nice as a place to start.
Cheers
I ended up doing this:
Microsoft.Office.Interop.Outlook._Application objOutlook; //declare Outlook application
objOutlook = new Microsoft.Office.Interop.Outlook.Application(); //create it
Microsoft.Office.Interop.Outlook._NameSpace objNS = objOutlook.Session; //create new session
Microsoft.Office.Interop.Outlook.MAPIFolder oAllPublicFolders; //what it says on the tin
Microsoft.Office.Interop.Outlook.MAPIFolder oPublicFolders; // as above
Microsoft.Office.Interop.Outlook.MAPIFolder objContacts; //as above
Microsoft.Office.Interop.Outlook.Items itmsFiltered; //the filtered items list
oPublicFolders = objNS.Folders["Public Folders"];
oAllPublicFolders = oPublicFolders.Folders["All Public Folders"];
objContacts = oAllPublicFolders.Folders["Global Contacts"];
itmsFiltered = objContacts.Items.Restrict(strFilter);//restrict the search to our filter terms
Then just looping through itmsFiltered to add it to an ObjectListView. Hopefully this will be of use to someone else looking to do the same - it took me a while to cobble this together from various sources.
to find contacts folder you can iterate items of olFolderContacts. Here is the code
using System;
using Microsoft.Office.Interop.Outlook;
using Application = Microsoft.Office.Interop.Outlook.Application;
namespace RyanCore
{
public class Loader
{
public static ContactsViewModel LoadModel(Application objOutlook)
{
var viewModel = new ContactsViewModel();
MAPIFolder fldContacts = objOutlook.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
foreach (object obj in fldContacts.Items)
{
if (obj is _ContactItem)
{
var contact = (_ContactItem) obj;
viewModel.Contacts.Add(new Contact(contact.FirstName + " " + contact.LastName, contact.Email1Address));
}
else if (obj is DistListItem)
{
var distListItem = (DistListItem) obj;
var contactGroup = new ContactGroup(distListItem.Subject);
viewModel.Groups.Add(contactGroup);
for (Int32 i = 1; i <= distListItem.MemberCount; i++)
{
Recipient subMember = distListItem.GetMember(i);
contactGroup.Contacts.Add(new Contact(subMember.Name, subMember.AddressEntry.Address));
}
}
}
return viewModel;
}
}
}
In Sharepoint how can you copy a list item from one list to another list
eg copy from "List A" to "List B" (both are at the root of the site)
I want this copying to occur when a new list item is added to "List A"
I tried using the CopyTo() method of an SPListItem inside the ItemAdded event receiver but couldnt figure out the url to copy to.
Here is the code I use. Pass it a SPlistItem and the name of the destination list as seen in Sharepoint(Not the URL). The only restriction is that both list must be in the same site:
private SPListItem CopyItem(SPListItem sourceItem, string destinationListName) {
//Copy sourceItem to destinationList
SPList destinationList = sourceItem.Web.Lists[destinationListName];
SPListItem targetItem = destinationList.Items.Add();
foreach (SPField f in sourceItem.Fields) {
//Copy all except attachments.
if (!f.ReadOnlyField && f.InternalName != "Attachments"
&& null != sourceItem[f.InternalName])
{
targetItem[f.InternalName] = sourceItem[f.InternalName];
}
}
//Copy attachments
foreach (string fileName in sourceItem.Attachments) {
SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
byte[] imageData = file.OpenBinary();
targetItem.Attachments.Add(fileName, imageData);
}
return targetItem;
}
Indeed as Lars said, it can be tricky to move items and retain versions and correct userinfo. I have done similar things with that before so if you need some code examples, let me know through a comment and can supply you with some guidance.
The CopyTo method (if you decide to go with that) need an absolute Uri like:
http://host/site/web/list/filename.doc
So, if you are performing this in an event receiver you need to concatinate a string containing the elements needed. Something like (note that this can be done in other ways to):
string dest=
siteCollection.Url + "/" + site.Name + list.Name + item.File.Name;
Copying and moving files, items and folders in SharePoint can be tricky if you want to retain all metadata, timestamps, author info and version history. Take a look a CopyMove for SharePoint - it also has a Web Service API.
There's many tools on the market for copying a list item to another list (avepoint, metavis, etc.) but they are pretty expensive if you're planning to do this on only one list.
If you can do this manually once a week for example, look at the following tool : http://en.share-gate.com/sharepoint-tools/copy-move-sharepoint-list-items-with-metadata-and-version-history
Here is a powershell equivalent of Sylvian's that does allow for cross-site copy. His code could be modified similarly as well...
param([string]$sourceWebUrl, [string]$sourceListName, [string]$destWebUrl, [string]$destListName)
$sourceWeb = get-spweb $sourceWebUrl;
$sourceList = $sourceWeb.Lists[$sourceListName];
$destWeb = get-spweb $destWebUrl;
$destList = $destWeb.Lists[$destListName];
$sourceList.Items |%{
$destItem = $destList.Items.Add();
$sourceItem = $_;
$sourceItem.Fields |%{
$f = $_;
if($f.ReadOnlyField -eq $false -and $f.InternalName -ne "Attachments" -and $sourceItem[$f.InternalName] -ne $null){
$destItem[$f.InternalName] = $sourceItem[$f.InternalName];
}
}
$destItem.Update();
}
To use, copy and past to a file copy-listitems.ps1 and run using Sharpoint powerhsell commandline...
Make sure you call CopyTo(url) method on SPFile, not on SPListItem.
for example:
ItemUpdated(SPItemEventProperties properties)
{
//...
string url = properties.Web.Site.Url + "/" + properties.Web.Name + "Lists/ListName/" + properties.ListItem.File.Name;
//properties.ListItem.File.MoveTo(url);
properties.ListItem.File.CopyTo(url);
//...
}
private void CopyAttachmentsToList(SPListItem srcItem, SPListItem tgtItem)
{
try
{
//get source item attachments from the folder
SPFolder srcAttachmentsFolder =
srcItem.Web.Folders["Lists"].SubFolders[srcItem.ParentList.Title].SubFolders["Attachments"].SubFolders[srcItem.ID.ToString()];
//Add items to the target item
foreach (SPFile file in srcAttachmentsFolder.Files)
{
byte[] binFile = file.OpenBinary();
tgtItem.Update();
tgtItem.Attachments.AddNow(file.Name, binFile);
tgtItem.Update();
}
}
catch
{
//exception message goes here
}
finally
{
srcItem.Web.Dispose();
}
}
Don't forget to add this line, tgtItem.Update();, else you will get an err.
So, the lists have the exact same or similar columns? Either way, you could create a simple workflow that runs automatically when an item is created in "List A". Since the workflow in question is relatively simple, I'd recommend using SharePoint Designer (which is free) to create it, since you can easily match up the columns from the two lists. The walk through below should be able to help you get started.
Create a Workflow - SharePoint Designer
I had the same problem.
After experimenting a bit instead of
targetItem[f.InternalName] = sourceItem[f.InternalName];
I used:
targetItem[childField.Title] = sourceItem[parentField.Title];
How to copy field and save versions:
public static SPListItem CopyItem(SPListItem sourceItem, SPList destinationList)
{
SPListItem targetItem = destinationList.AddItem();
//loop over the soureitem, restore it
for (int i = sourceItem.Versions.Count - 1; i >= 0; i--)
{
//set the values into the archive
foreach (SPField sourceField in sourceItem.Fields)
{
SPListItemVersion version = sourceItem.Versions[i];
if ((!sourceField.ReadOnlyField) && (sourceField.InternalName != "Attachments"))
{
SetFields(targetItem, sourceField, version);
}
}
//update the archive item and
//loop over the the next version
targetItem.Update();
}
foreach (string fileName in sourceItem.Attachments)
{
SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
targetItem.Attachments.Add(fileName, file.OpenBinary());
}
targetItem.SystemUpdate();
return targetItem;
}
private static bool SetFields(SPListItem targetItem, SPField sourceField, SPListItemVersion version)
{
try
{
targetItem[sourceField.InternalName] = version.ListItem[sourceField.InternalName];
return true;
}
catch (System.ArgumentException)//field not filled
{
return false;
}
catch (SPException)//field not filled
{
return false;
}
}
Copy List Items from one SharePoint List or library to Another SharePoint list or library using c# server side code
//Itecollection is a collection of data from source list
public void CopyItemsFromOneListToAnotherList(SPListItemCollection itemCollection)
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
//Get destination list/library
//destListName - Destination list/library name
SPList destList = web.Lists.TryGetList(destListName);
foreach (SPListItem sourceItem in itemCollection)
{
//Add new Item to list
SPListItem destItem = destList.Items.Add();
foreach (SPField field in sourceItem.Fields)
{
if (!field.ReadOnlyField && !field.Hidden && field.InternalName != "Attachments")
{
if (destItem.Fields.ContainsField(field.InternalName))
{
//Copy item to destination library
destItem[field.InternalName] = sourceItem[field.InternalName];
}
}
}
//Update item in destination library or list
destItem.Update();
Console.WriteLine("Copied " + sourceItem["ID"] + "to destination list/library");
}
}
}
}