views:

734

answers:

3

Does anyone have sample code to add a new user to CRM 4.0 using sdk?

+1  A: 

I have code that creates users for us based on users in another system so I can't exactly paste it all here - most of it wouldn't make sense to you - but this is the core of it:

[In VB sorry :-) - also when posting VB here I find I need to use '//' to indicate a comment to make the formatting correct]

Public Sub CreateNewUser()
  Dim s as mscrm.CrmService = GetMyService()
  Dim newUser as New mscrm.systemuser()
  With newUser
     .domainname = "domain\user"
     .firstname = "Stan"
     .lastname = "Molda"
     //set anything else you want here
  End With
  Dim userGuid as guid = s.Create(newUser)

  //Next we need to assign the user a role
  AssignRole(userGuid)

  //Finally we need to assign them to the correct Time Zone
  SetUserTimeZone(userGuid)
End Sub

Public Sub AssignRole(g as Guid)
    Dim s as mscrm.CrmService = GetMyService()
    Dim req As New mscrm.AssignUserRolesRoleRequest()
    req.UserId = g
    req.RoleIds = New Guid() {GetTheGuidForMyPrimaryRole()}
    s.Execute(req)
End Sub

Public Sub SetUserTimeZone(g as Guid)
    Dim s as mscrm.CrmService = GetMyService()
    Dim r As New mscrm4.RetrieveUserSettingsSystemUserRequest()
    r.ColumnSet = New mscrm3.AllColumns()
    r.EntityId = New Guid(g)
    Dim resp As mscrm.RetrieveUserSettingsSystemUserResponse = CType(s.Execute(r), mscrm.RetrieveUserSettingsSystemUserResponse)
    Dim settings As mscrm.usersettings = CType(resp.BusinessEntity, mscrm.usersettings)
    settings.timezonecode = New mscrm.CrmNumber
    settings.timezonecode.Value = OUR_TIME_ZONE_CONSTANT
    Dim update As New mscrm.UpdateUserSettingsSystemUserRequest()
    update.Settings = settings
    update.UserId = g
    s.Execute(update)
End Sub
brendan
Hey Brendon good job very clear and the perfect solution i wonder why no one even cared to say it is useful... Who ever asked this question should really click as answer to the question...
Srikrishna Sallam
A: 

Does anyone have sample code in java?

kishen
A: 

For C#, take a look at my question, Dynamics CRM: Create users with specific GUIDs, which does exactly what you want (but not exactly what I want :-P).

Kevin L.