SharePoint 2007: AfterProperties of person input field shows always -1 as lookupid - sharepoint

I'm struggling with the SharePoint 2007 AfterProperties. I've a people input field, where several people can be added.
On the ItemUpdating event I now need to determine which users were added, removed or stayed the same.
Unfortunately this becomes quit difficult, as the id of the untouched users turns to -1 in the AfterProperties, so that I cant not use SPFieldUserValueCollection to find the user.
An example. properties.ListItem["AssignedTo"].ToString() shows:
1;#domain\user1;#2;#domain\user2
properties.AfterProperties["AssignedTo"].ToString() shows:
-1;#domain\user1;#-1;#domain\user2;#3;#domain\user3 <-Added a user
I planned to use following code, to determine removed and added users:
foreach (SPFieldUserValue oldUser in oldUserCollection)
{
if (newUserCollection.Find(x => x.LookupId == oldUser.LookupId) == null)
{
RemoveRole(aListItem, oldUser.User, roleDefCollection[workerRoleName]);
}
}
foreach (SPFieldUserValue newUser in newUserCollection)
{
if(oldUserCollection.Find(x => x.User.LoginName == newUser.LookupValue) == null)
{
AddRole(aListItem, newUser.User, roleDefCollection[workerRoleName]);
}
}
How can I archive, that the AfterProperties show the right lookupid?

Solved the problem by myself. Instead of using the SPFieldUserCollection I'm now using a list and try to parse all the information by myself out of the string.
Regex reg = new Regex(#"\;\#");
string[] usernameParts = reg.Split(usernames);
List<SPUser> list = new List<SPUser>();
int id;
foreach (string s in usernameParts)
{
if (!string.IsNullOrEmpty(s))
{
if (!Int32.TryParse(s, out id))
{
if (list.Find(x => x.ID == spweb.Users[s].ID) == null)
list.Add(spweb.Users[s]);
}
else
{
if (Convert.ToInt32(s) != -1)
{
if (list.Find(x => x.ID == Convert.ToInt32(s)) == null)
list.Add(spweb.Users.GetByID(Convert.ToInt32(s)));
}
}
}
}

Related

lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem

I try to put a file into a richtext but it crashes !
In my first code, I try to use directly "getFirstItem", in first time it was ok but now i try to use it again and it crashed.
In second time i pass with an object and it find my obj doesn't an richtextItem (instanceof) ???
I don't understand.
I have the message : "lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem" ?
Could you help me ?
public void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) throws NotesException {
lotus.domino.Session session = Utils.getSession();
lotus.domino.Database db = session.getCurrentDatabase();
lotus.domino.Document monDoc = db.getDocumentByUNID(idDocument);
lotus.domino.RichTextItem rtiNew = null;
try {
try {
if (monDoc != null) {
// if (monDoc.getFirstItem(nomRti) != null) {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.getFirstItem(nomRti);
// } else {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.createRichTextItem(nomRti);
// }
Object obj = null;
if (monDoc.getFirstItem(nomRti) != null) {
obj = monDoc.getFirstItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
} else {
obj = monDoc.createRichTextItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
}
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtiNew.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
}
} finally {
rtiNew.recycle();
monDoc.recycle();
db.recycle();
session.recycle();
}
} catch (Exception e) {
e.printStackTrace();
}
}
EDIT : I try to modify my code with yours advices but the items never considerate as richtextitem. It is my problem. I don't understand why, because in my field it is a richtext ! For it, the item can't do :
rtiNew = (lotus.domino.RichTextItem) item1;
because item1 not be a richtext !!!
I was trying to take all the fields and pass in the item one by one, and it never go to the obj instance of lotus.domini.RichTextItem....
Vector items = doc.getItems();
for (int i=0; i<items.size(); i++) {
// get next element from the Vector (returns java.lang.Object)
Object obj = items.elementAt(i);
// is the item a RichTextItem?
if (obj instanceof RichTextItem) {
// yes it is - cast it as such // it never go here !!
rt = (RichTextItem)obj;
} else {
// nope - cast it as an Item
item = (Item)obj;
}
}
A couple of things. First of all I would set up a util class method to handle the object recycling in a neater way:
public enum DominoUtil {
;
public static void recycle(Base... bases) {
for (Base base : bases) {
if (base != null) {
try {
base.recycle();
} catch (Exception e) {
// Do nothing
}
}
}
}
}
Secondly I would remove the reduntants try/catch blocks and simplify it like this:
private void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) {
Session session = DominoUtils.getCurrentSession();
Database db = session.getCurrentDatabase();
Document monDoc = null;
try {
monDoc = db.getDocumentByUNID(idDocument);
Item item = monDoc.getFirstItem(nomRti);
if (item == null) {
item = monDoc.createRichTextItem(nomRti);
} else if (item.getType() != Item.RICHTEXT) {
// The item is not a rich text item
// What are you going to do now?
}
RichTextItem rtItem = (RichTextItem) item;
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtItem.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
} catch (NotesException e) {
throw new FacesException(e);
} finally {
DominoUtil.recycle(monDoc);
}
}
Finally, apart from the monDoc, you need not recycle anything else. Actually Session would be automatically recycled and anything beneath with it (so no need to recycle db, let alone the session!, good rule is don't recycle what you didn't instantiate), but it's not bad to keep the habit of keeping an eye on what you instantiate. If it were a loop with many documents you definitively want to do that. If you also worked with many items you would want to recycle them as early as possible. Anyway, considered the scope of the code it's sufficient like this. Obviously you would call DominoUtil.recycle directly from the try block. If you have multiple objects you can recycle them at once possibly by listing them in the reverse order you set them (eg. DominoUtil.recycle(item, doc, view)).
Also, what I think you miss is the check on the item in case it's not a RichTextItem - and therefore can't be cast. I put a comment where I think you should decide what to do before proceeding. If you let it like that and let the code proceed you will have the code throw an error. Always better to catch the lower level exception and re-throw a higher one (you don't want the end user to know more than it is necessary to know). In this case I went for the simplest thing: wrapped NotesException in a FacesException.

Get the User Id - SharePoint 2010

I have a column that has names of the user. The column type is Single line of Text and the user name is stored in the format LastName, FirstName;
I would like to get the user id and email address of the stored user name.
I tried
string fieldValue = item["ProjectManager"] as string;
SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, fieldValue);
if (users != null)
{
/* The users.count is always zero */
foreach (SPFieldUserValue user in users)
{
if (user.User != null)
{
}
}
}
I cannot change the column type to Person or Group and it would remain as Single Line of Text. Please let me know how can I achieve this . I have been trying this for couple of hours now.
Try this:
public SPUser GetUser(SPWeb web, string userstring)
{
var user = FetchUser(web, userstring);
if (user == null)
{
SPPrincipalInfo info = SPUtility.ResolvePrincipal(web, userstring, SPPrincipalType.User, SPPrincipalSource.All, null, false);
if (info!=null)
user = FetchUser(web, info.LoginName);
}
return user;
}
public SPUser FetchUser(SPWeb web, string userstring)
{
return web.AllUsers.Cast<SPUser>().FirstOrDefault(
i => i.Name == userstring || i.LoginName == userstring || i.Email == userstring);
}
From SPUser you get get the user ID.
Get SPUser in your case with:
var user = GetUser(item.Web,fieldValue )

Outlook : Conflict while saving contact

I am working on a project involving contact synchronization between Outlook and SharePoint. Though there is an out of the box solution provided for this by Microsoft, but it does not cater some specific requirements like custom column synchronization.
For this requirement we had to create an outlook add-in. This add-in handles ItemAdd and ItemChange event for the contact folder created as a result of the synchronization.
In the ItemChange event I check a flag in the Notes field and identify whether the change has been made from SharePoint or Outlook and accordingly update the contact item.
Here is the code for my ItemChange event.
void Items_ItemChange(object Item)
{
try
{
ContactItem ctItem = Item as Outlook.ContactItem;
string customFieldsAndFlag = ctItem.Body;
Dictionary<string, string> customColumnValueMapping = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(customFieldsAndFlag))
{
string[] flagAndFields = customFieldsAndFlag.Split(';');
if (flagAndFields.Length == 2)
{
//SharePoint to Outlook
if (flagAndFields[0] == "1")
{
foreach (string customColumnAndValue in flagAndFields[1].Split('|'))
{
string[] KeyAndValue = customColumnAndValue.Split('=');
if (KeyAndValue.Length == 2)
{
if (ctItem.UserProperties[KeyAndValue[0]] == null)
{
ctItem.UserProperties.Add(KeyAndValue[0], OlUserPropertyType.olText, true, OlUserPropertyType.olText);
ctItem.UserProperties[KeyAndValue[0]].Value = KeyAndValue[1];
}
else
{
ctItem.UserProperties[KeyAndValue[0]].Value = KeyAndValue[1];
}
}
}
ctItem.Body = "2;" + flagAndFields[1];
}
//Outlook to SharePoint
else
{
foreach (string customColumnAndValue in flagAndFields[1].Split('|'))
{
string[] KeyAndValue = customColumnAndValue.Split('=');
if (KeyAndValue.Length == 2)
{
if (ctItem.UserProperties[KeyAndValue[0]] != null && ctItem.UserProperties[KeyAndValue[0]].Value != null)
{
KeyAndValue[1] = ctItem.UserProperties[KeyAndValue[0]].Value.ToString();
}
customColumnValueMapping.Add(KeyAndValue[0], KeyAndValue[1]);
}
}
string newBody = string.Empty;
foreach (KeyValuePair<string, string> kvp in customColumnValueMapping)
{
newBody += kvp.Key + "=" + kvp.Value + "|";
}
if (newBody == flagAndFields[1])
{
return;
}
else
{
ctItem.Body = "0;" + newBody;
}
}
}
}
ctItem.Save();
}
catch(System.Exception ex)
{
// log the error always
Trace.TraceError("{0}: [class]:{1} [method]:{2}\n[message]:{4}\n[Stack]:\n{5}",
DateTime.Now, // when was the error happened
MethodInfo.GetCurrentMethod().DeclaringType.Name, // the class name
MethodInfo.GetCurrentMethod().Name, // the method name
ex.Message, // the error message
ex.StackTrace // the stack trace information
);
// now display a friendly error to the user
MessageBox.Show("There was an application error, you should save your work and restart Outlook.",
"TraceAndLog",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
Now the issue is, the contact item update works fine from outlook the first time. The contact gets updated properly, the add-in works fine and changes get reflected in SharePoint just fine. But when I try to edit the contact again using outlook, a pop-up comes up saying "Item cannot be changed because it was changed by another user or in another window. Do you want to make a copy in the default folder for the item?" and the oulook add-in stops working thereafter.
Can anyone please suggest a solution for this problem?
I cannot use ctItem.Close() as when I use this function, the synchronization process doesn't work and the changes don't get populated to SharePoint.

Detect Change in EntityFrameWork

In my current project I need write in a table all values are changed in the application.
Ex. the guy update the UserName, I need put in a table UserName old value "1" new value "2".
I tried use the ObjectStateEntry but this return all fields. I think the FW return all because my code.
public USER Save(USER obj)
{
using(TPPTEntities db = new TPPTEntities())
{
db.Connection.Open();
USER o = (from n in db.USERs where n.ID == obj.ID select n).FirstOrDefault();
if (o == null)
{
o = new USER()
{
BruteForce = 0,
Email = obj.Email,
IsBlock = false,
LastLogin = DateTime.Now,
Name = obj.Name,
UserName = obj.UserName,
UserPassword = new byte[0],
};
db.AddToUSERs(o);
}
else
{
o.Email = obj.Email;
o.Name = obj.Name;
o.UserName = obj.UserName;
}
db.SaveChanges();
db.Connection.Close();
}
return obj;
}
A way to get old and new values is this:
var ose = this.ObjectStateManager.GetObjectStateEntry(o.EntityKey);
foreach (string propName in ose.GetModifiedProperties())
{
string.Format("Property '{0}', old value: {1}, new value: {2}",
propName, ose.OriginalValues[propName], ose.CurrentValues[propName]);
}
This is pretty useless, of course, but I'm sure you'll know what to do in the foreach loop to store the changes.
Is this a WCF Service? In that case, the changes will probably never come trough since changes to the Object Graph are made where the Object Context is not available. Consider using Self-Tracking Entities

Loop through attribute of a class and get a count of how many properties that are not null

I was wondering if there was a simpler way to do something like this?
public int NonNullPropertiesCount(object entity)
{
if (entity == null) throw new ArgumentNullException("A null object was passed in");
int nonNullPropertiesCount = 0;
Type entityType = entity.GetType();
foreach (var property in entityType.GetProperties())
{
if (property.GetValue(entity, null) != null)
nonNullPropertiesCount = nonNullPropertiesCount+ 1;
}
return nonNullPropertiesCount;
}
How about:
public int NonNullPropertiesCount(object entity)
{
return entity.GetType()
.GetProperties()
.Select(x => x.GetValue(entity, null))
.Count(v => v != null);
}
(Other answers have combined the "fetch the property value" and "test the result for null". Obviously that will work - I just like to separate the two bits out a bit more. It's up to you, of course :)
Type entityType = entity.GetType();
int count = entityType.GetProperties().Count(p => p.GetValue(p, null) != null);
Your code is OK, can suggest using Linq
entity
.GetProperties()
.Count(x=>x.CanRead && x.GetProperty(entity, null) != null)
And don't forget to add condition, that property has getter.

Resources