adding a user to a list programmatically - c#

i have a list which is being populated from a program that takes user input, i am having a problem when it comes to adding a person or group to one of the columns in the list. does anybody know how to do this?

have a look at this article: http://blogs.msdn.com/b/uksharepoint/archive/2009/02/17/quick-tip-using-the-sharepoint-person-or-group-field-in-code-part-1.aspx
it shows you how to use it:
Console.WriteLine("Enter a ; delimited list of domain\alias that need to be added:");
string sAliases = Console.ReadLine(); //captures whatever the user entered
string sValueToAddToFieldInSP = ""; //used to build the full string needed for the person field
string sAllContacts = "";
using (SPSite site = new SPSite(“http://sites/site/yoursite”))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
string[] aAliases = sAliases.Split(';');
foreach (string sAlias in aAliases)
{
SPUser user = web.EnsureUser(sAlias);
sAllContacts += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
}
web.Update();
}
}
if (sAllContacts.EndsWith(";#"))
{
sAllContacts = sAllContacts.Substring(0, sAllContacts.Length - 2);
}
//add the list item
SPList l = web.Lists["<name of your list>"];
SPListItem li= l.Items.Add();
li["Title"] = sAllContacts ;
li["MyPerson"] = sAllContacts ;
li.Update();
Console.WriteLine("Done");

Related

How can I retrieve just users from the Active Directory, not groups

I am having this code that returns list of users and groups from the Active Directory
public ArrayList GetADGroupUsers(string groupNames)
{
string[] strGrpNames = groupNames.Split(new char[] { ',' });
string strTeamList = string.Empty;
ArrayList userNames = new ArrayList();
string ADPassword = ConfigurationManager.AppSettings["ADPassword"];
IAAccess_Transaction.drms_dataaccess drmsda = new IAAccess_Transaction.drms_dataaccess();
string domainAndUsername = ConfigurationManager.AppSettings["domain"] + #"\" + ConfigurationManager.AppSettings["ADUserName"];
string decriptedADPassword = drmsda.Decrypt(ADPassword);
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, decriptedADPassword);
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
foreach (string strGrp in strGrpNames)
{
search.Filter = String.Format("(cn={0})", strGrp);
search.PropertiesToLoad.Add("member");
SearchResult result = search.FindOne();
if (result != null)
{
for (int counter = 0; counter <
result.Properties["member"].Count; counter++)
{
string user = (string)result.Properties["member"][counter];
userNames.Add(user);
}
}
}
return userNames;
}
This code retrieves BOTH, users AND group as shown on the screenshot. How can I modify this code to retrieve JUST users, NOT groups?
In order to include the nested group members, you need to lookup each entry and find out if it is a group or user. If it is a group, you can add to the groups you are already processing. Since C#/.Net doesn't have a built-in Deque class, I used LinkedList<T> instead.
public List<string> GetADGroupUsers(string groupNames) {
LinkedList<string> strGrpNames = new(groupNames.Split(','));
List<string> userNames = new();
string ADPassword = ConfigurationManager.AppSettings["ADPassword"];
string domainAndUsername = ConfigurationManager.AppSettings["domain"] + #"\" + ConfigurationManager.AppSettings["ADUserName"];
string decryptedADPassword = drmsda.Decrypt(ADPassword);
DirectoryEntry entry = new(_path, domainAndUsername, decryptedADPassword);
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher groupSearcher = new(entry);
groupSearcher.PropertiesToLoad.Add("member");
DirectorySearcher userSearcher = new(entry);
userSearcher.PropertiesToLoad.Add("groupType");
while (strGrpNames.Count > 0) {
string strGrp = strGrpNames.First();
strGrpNames.RemoveFirst();
groupSearcher.Filter = $"(cn={strGrp})";
SearchResult result = groupSearcher.FindOne();
if (result != null) {
var members = result.Properties["member"];
for (int counter = 0; counter < members.Count; ++counter) {
var user = (string)members[counter];
var userCN = user.Substring(user.IndexOf('=')+1).Substring(0,user.IndexOf(',')-3);
userSearcher.Filter = $"(cn={userCN})";
SearchResult userProperties = userSearcher.FindOne();
var userGroupType = userProperties.Properties["groupType"];
if (userGroupType != null && userGroupType.Count > 0) // group
strGrpNames.AddFirst(userCN);
else
userNames.Add(user);
}
}
}
return userNames;
}

Reading existing field value from SharePoint Custom List fails

I am trying to read the value of a particular field in a SharePoint Custom List.
The Custom List has the following fields: Field1, Field2 and Field3
When I call the code below:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
foreach (var fieldValue in listItem.FieldValues)
{
Console.WriteLine(fieldValue.Key + ":" + fieldValue.Value + Environment.NewLine);
}
}
targetColumnValue = listItem[targetColumnName] as string;
return targetColumnValue;
}
The error message is:
Additional information: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
The fields which are displayed in the foreach show "Field1" and "Field2". Do I have to explicitly request "Field3". If yes how?
I had to get the internal name before querying the value for some reason. Here is the code that worked:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var field = list.Fields.GetByInternalNameOrTitle(targetColumnName);
var textField = clientContext.CastTo<FieldText>(field);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(textField);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
targetColumnValue = listItem[textField.InternalName] as string;
}
return targetColumnValue;
}

Update people or group field of sharepoint list C# code

I have a console app, it updates people or group field of sharepoint list. If the item["Approver"] value is a user value this app works fine. If the item["Approver"] value is a sharepoint group this will fail.
I expect this app should work if the item["Approver"] value is both user or group. Can someone suggest the code part to make me success?
static SPWeb _web;
static SPSite _site;
static SPList myList;
static void Main(string[] args)
{
string usercontrolvalue = "test";
_site = new SPSite("URL");
_web = _site.OpenWeb();
_web.AllowUnsafeUpdates = true;
myList = _web.Lists["MYList"];
SPListItem item = myList.Items.Add();
SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
string[] userarray = usercontrolvalue.Split(',');
for (int i = 0; i < userarray.Length; i++)
{
SPFieldUserValue usertoadd = ConvertLoginName(userarray[i]);
usercollection.Add(usertoadd);
}
item["Approver"] = usercollection;
item.Update();
}
public static SPFieldUserValue ConvertLoginName(string userid)
{
SPUser requireduser = _web.EnsureUser(userid);
SPFieldUserValue uservalue = new SPFieldUserValue(_web, requireduser.ID, requireduser.LoginName);
return uservalue;
}
Use below code as is. Hope this will help you :)
static SPWeb _web;
static SPSite _site;
static SPList myList;
static void Main(string[] args)
{
string usercontrolvalue = "test";
_site = new SPSite("URL");
_web = _site.OpenWeb();
_web.AllowUnsafeUpdates = true;
myList = _web.Lists["MYList"];
SPListItem item = myList.Items.Add();
SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
for (int i = 0; i < userarray.Length; i++)
{
SPUser usr = web.EnsureUser(userarray[i]);
SPFieldUserValue usertoadd = new SPFieldUserValue(_web, usr.ID, usr.Name);
if (usertoadd.User == null) // value is a SharePoint group if User is null
{
SPGroup group = web.Groups[usertoadd.LookupValue];
SPFieldUserValue groupValue = new SPFieldUserValue(_web, group.ID, group.Name);
usercollection.Add(groupValue);
}
else
{
usercollection.Add(usertoadd);
}
}
item["Approver"] = usercollection;
item.Update();
}
Because SPGroup is Lookup item you have to look for user first on group.
http://msdn.microsoft.com/en-gb/library/microsoft.sharepoint.spgroup(v=office.14).aspx
//Group or User are allowed to update
SPFieldUser spuserField = (SPFieldUser)item.Fields.GetField("Approver");
SPFieldUserValue spuserFieldValue = (SPFieldUserValue)spuserField.GetFieldValue(item["Approver"].ToString());
//Tries to get SPUser
if (spuserFieldValue.User != null)
{
SPUser user = userFieldValue.User;
}
//if the field contain group
else
{
SPGroup group = web.SiteGroups.GetByID(spuserFieldValue.LookupId);
}
Hope above helps.

search a Text File for a sentence by date AND name

I am trying to search my text-file for a sentence by date and by name. Then I want this sentence to load it to some textboxes in my form. I am new in VS but I know some things about C.
I have came up with this code:
string pattern = dateTimePicker1Is.Text;
string pattern1 = _txtNameIs.Text;
IList<string> result = new List<string>();
using (var reader = new StreamReader(#"C:\Users\user\Desktop\Testet System\isto.txt"))
{
string currentLine;
while ((currentLine = reader.ReadLine()) != null)
{
if (currentLine.Contains(pattern))
{
if (currentLine.Contains(pattern1))
{
result.Add(currentLine);
string[] tempArray = currentLine.Split(',');
_txtNameIs.Text = tempArray[0];
_txtSurnameIs.Text = tempArray[1];
_txtApokxT.Text = tempArray[2];
_txtApoktT.Text = tempArray[3];
_txtEpanxT.Text = tempArray[4];
_txtEpandT.Text = tempArray[5];
_txtApokkT.Text = tempArray[6];
_txtEpankT.Text = tempArray[7];
_txtApoksT.Text = tempArray[8];
_txtEpansT.Text = tempArray[9];
_txtGenSun.Text = tempArray[10];
break;
}
else
{
MessageBox.Show("There are no records!");
}
}
}
}
When I press the search button it loads me all the data that I need, but if I have the same name and different date a message-box pops up and tells 'there are no records'.
I believe there is better way doing this:
string pattern = dateTimePicker1Is.Text;
string pattern1 = _txtNameIs.Text;
string pathToFile = #"C:\Users\user\Desktop\Testet System\isto.txt";
List<string> result = new List<string>();
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains(pattern) && line.Contains(pattern1))
{
result.Add(line);
string[] tempArray = line.Split(',');
if(tempArray.Length >= 11)
{
_txtNameIs.Text = tempArray[0];
_txtSurnameIs.Text = tempArray[1];
_txtApokxT.Text = tempArray[2];
_txtApoktT.Text = tempArray[3];
_txtEpanxT.Text = tempArray[4];
_txtEpandT.Text = tempArray[5];
_txtApokkT.Text = tempArray[6];
_txtEpankT.Text = tempArray[7];
_txtApoksT.Text = tempArray[8];
_txtEpansT.Text = tempArray[9];
_txtGenSun.Text = tempArray[10];
break;
}
}
}
It is better to show message if the list count is 0.
I think your There are no records error should happen
AFTER the while statement
IF no matches were found
Right?
So put if there was a match found in a bool, and then after the while if !IsMatchFound then throw your error.

What´s the better way to get ID from lookup field value programmatically?

When I try to get the id from:
string idValue = item[Lookup].ToString();
I get the next value by example:
1;#1
I need the value this way:
1
Actually this code handle the requirement:
using (SPSite site = new SPSite(context.CurrentWebUrl))
{
using (SPWeb web = site.OpenWeb())
{
//Context list
SPList list = web.Lists[context.ListId];
SPList child = web.Lists[List];
SPListItem currentItem = list.GetItemById(context.ItemId);
string updateItems = "";
int ID = currentItem.ID;
foreach (SPListItem item in child.Items)
{
string idValue = item[Lookup].ToString();
int partial = idValue.LastIndexOf(";");
string idPure = idValue.Substring(0, partial);
if (idPure == ID.ToString())
{
item[Field] = Value;
item.Update();
updateItems += item.ID.ToString();
}
}
//Return Items*/
results["Items"] = updateItems;
SPWorkflow.CreateHistoryEvent(web, context.WorkflowInstanceId, 0,
web.CurrentUser, TimeSpan.Zero, "Information",
"Event from sandboxed, updates: " + updateItems, string.Empty);
}
}
I want to know a better function or property to get the ID from lookup field.
SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(item["FieldName"].ToString());
int lookupID = fieldLookupValue.LookupId;
Here you go :)
SPList mySPList = oWeb.Lists["ProjectList"];
newItem["LookupFieldName"] = new SPFieldLookupValue(getLookUp(mySPList,LookupFieldValue), LookupFieldValue);
public static int getLookUp(SPList oList, string FieldValue, string sFieldName="Title")
{
foreach (SPListItem spi in oList.GetItems())
{
if (spi[sFieldName].ToString() == FieldValue)
{
return spi.ID;
}
}
return 0;
}
i can set lookup field in SharePoint by use this code
<script>
window.onload = (event) => {
document.getElementById("tafahomNameId_78ec7c44-beab-40de-9326-095f474519f4_$LookupField").value = 1;
};
</script>

Categories

Resources