C# EWS copy contacts to a mailbox - c#

I want to select the user "test" so I can create a contact into his mailbox.
My actual problem is that it will create Contacts into my user "c-sharp".
"c-sharp" has full access on "test" mailbox
I changed the IP and the contact infos users are also only for testing.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.EnableScpLookup = false;
service.Credentials = new WebCredentials("c-sharp", "c-sharp", "domain");
service.UseDefaultCredentials = false;
IgnoreBadCertificates();
service.Url = new Uri("https://192.000.000.000/EWS/Exchange.asmx");
Contact contact = new Contact(service);
// Specify the name and how the contact should be filed.
contact.GivenName = "n.a.";
contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
contact.DisplayName = "bau gmbh";
// Specify the company name.
contact.CompanyName = "bau";
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "00000 00000";
contact.PhoneNumbers[PhoneNumberKey.MobilePhone] = "n.a.";
contact.PhoneNumbers[PhoneNumberKey.BusinessFax] = "00000 00000";
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("e#mail.de");
//homepage
contact.BusinessHomePage = "n.a.";
// Specify the home address.
PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry();
paEntry1.Street = "straße";
paEntry1.City = "stadt";
paEntry1.State = "D";
paEntry1.PostalCode = "88890";
paEntry1.CountryOrRegion = "Deutschland";
contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1;
contact.Save();
Already tried this:
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "test");
I tested it with "test" and "test#domain" and "test#domain.de"
And get back this error:
"Der Name des Identitätsprinzipals ist ungültig."
Own translation: "The name of the identity principal is unvailed"

You can use Impersonation like this
ExchangeUserData exchangeUserData = new ExchangeUserData();
exchangeUserData.Username = "c-sharp";
exchangeUserData.Password = "c-sharp"; // c-sharp's Password
ExchangeService service = Service.ConnectToServiceWithImpersonation(exchangeUserData, impersonatedUserPrincipal);
Contact contact = new Contact(service);
// Specify the name and how the contact should be filed.
contact.GivenName = "n.a.";
contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
contact.DisplayName = "bau gmbh";
// Specify the company name.
contact.CompanyName = "bau";
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "00000 00000";
contact.PhoneNumbers[PhoneNumberKey.MobilePhone] = "n.a.";
contact.PhoneNumbers[PhoneNumberKey.BusinessFax] = "00000 00000";
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("e#mail.de");
//homepage
contact.BusinessHomePage = "n.a.";
// Specify the home address.
PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry();
paEntry1.Street = "straße";
paEntry1.City = "stadt";
paEntry1.State = "D";
paEntry1.PostalCode = "88890";
paEntry1.CountryOrRegion = "Deutschland";
contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1;
contact.Save();

If your c-sharp user has the proper rights in Exchange, you should be able to do:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials("c-sharp", "c-sharp", "domain");
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "test");
If this doesn't work for you, please comment below or update your question (there's an "edit" link under it) with the exact behavior you are seeing including any error messages.

Problem sloved.
I found the bug... both of you are right just change:
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "test");
Into:
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "test#domain.de");
Thats all ...
Great thanks to you

Related

Adding User to Organization Unit and Group using Google Directory API

I am successful to create new user account using Google Directory API in .Net platform, but now I need to add that created user to Organization Unit and Group. I see the API details in this link to add the user to Organization Unit but any example showing insertion to Organization Unit would be greatly appreciated.
Updated with working code: Below is the code to create new user account using Directory API:
String serviceAccountEmail = ".........#developer.gserviceaccount.com";
X509Certificate2 certificate = new X509Certificate2(#"C:\key.p12", "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[]
{
DirectoryService.Scope.AdminDirectoryUser
},
User = "test#example.com",
}.FromCertificate(certificate));
var ser = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Account",
});
try
{
var user = new Google.Apis.Admin.Directory.directory_v1.Data.User()
{
Name = new Google.Apis.Admin.Directory.directory_v1.Data.UserName()
{
GivenName = FirstName.Text,
FamilyName = LastName.Text
},
Password = password
};
User newUser = new User();
UserName newUserName = new UserName();
newUser.PrimaryEmail = Email.Text;
newUserName.GivenName = FirstName_txt.Text;
newUserName.FamilyName = LastName_txt.Text;
newUser.Name = newUserName;
newUser.Password = password;
//Adding User to OU:
newUser.OrgUnitPath = "/Employee";
User results = ser.Users.Insert(newUser).Execute();
//Adding User to Group:
Member newMember = new Member();
newMember.Email = Email.Text;
newMember.Role = "MEMBER";
newMember.Kind = "admin#directory#member";
api.Members.Insert(newMember, "Employee#example.com").Execute();
Any idea how to insert the created user in Organization Unit and Group using Directory API?
To insert the new user into a Organization Unit just set the OU path when you create the user.
User newUser = new User();
UserName newUserName = new UserName();
newUser.PrimaryEmail = Email.Text;
newUserName.GivenName = FirstName_txt.Text;
newUserName.FamilyName = LastName_txt.Text;
newUser.Name = newUserName;
newUser.Password = password;
**newUser.OrgUnitPath ="\My\Organization\Unit\path\";**
User results = ser.Users.Insert(newUser).Execute();
Now your user has been added to the OU path.
To add a member into a group see the following code.
Member newMember = new Member();
newMember.Email = userKey;//email of the user that you want to add
newMember.Role = "MEMBER";
newMember.Type = "USER";
newMember.Kind = "admin#directory#member";
ser.Members.Insert(newMember, "MyDestinationGroup#mydomain").Execute();
that's it.
Note: you must review the scopes for the correct permissions.
Hope this help you.

Perforce Api - How to command "get revision [changelist number]"

I would like to implement the Perforce command "Get Revision [Changelist Number]" using the Perforce .NET API (C#). I currently have code that will "Get Latest Revision", but I need to modify it to get a specific changelist.
To sync the data with a changelist number, what should I do?
Source
// --------Connenct----------------
Perforce.P4.Server server = new Perforce.P4.Server(
new Perforce.P4.ServerAddress("127.0.0.1:9999"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = m_P4ID;
string password = m_P4PASS;
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
if (con.Credential == null)
con.Login(password);
//----------Download----------
string clientPath = #"C:\P4V\";
string ws_client = clientPath;
Perforce.P4.Client client = new Perforce.P4.Client();
client.Name = ws_client;
client.Initialize(con);
con.CommandTimeout = new TimeSpan(0);
IList<Perforce.P4.FileSpec> fileList = client.SyncFiles(new Perforce.P4.Options());
//----------Disconnect------------
con.Disconnect();
con.Dispose();
Edit: Attempt 1
Perforce.P4.DepotPath depot = new Perforce.P4.DepotPath("//P4V//");
Perforce.P4.LocalPath local = new Perforce.P4.LocalPath(ws_client);
Perforce.P4.FileSpec fs = new Perforce.P4.FileSpec(depot, null, local,
Perforce.P4.VersionSpec.Head);
IList<Perforce.P4.FileSpec> listFiles = new List<Perforce.P4.FileSpec>();
listFiles.Add(fs);
IList<Perforce.P4.FileSpec> foundFiles = rep.GetDepotFiles(listFiles,
new Perforce.P4.Options(1234)); // 1234 = Changelist number
client.SyncFiles(foundFiles, null);
Error Message
Usage: files/print [-o localFile -q] files...Invalid option: -c.
I do not know the problem of any argument.
Or there will not be related to this reference source?
Edit 2
I tried to solve this problem. However, it does not solve the problem yet.
Perforce.P4.Changelist changelist = rep.GetChangelist(1234);
IList<Perforce.P4.FileMetaData> fileMeta = changelist.Files;
In this case, I could get only the files in the changelist. I would like to synchronize all files of the client at the moment of changelist 1234.
SyncFiles takes an optional FileSpec arg. You can specify a file path and a revision specifier with that FileSpec arg. Here are the relevant docs:
FileSpec object docs
SyncFiles method docs
You don't need to run GetDepotFiles() to get the FileSpec object; you can just create one directly as shown in the FileSpec object docs. The error you are getting with GetDepotFiles() is because it expects the change number to be specified as part of the FileSpec object passed into as the first argument to GetDepotFiles().
To expand further, GetDepotFiles() calls the 'p4 files' command when it talks to Perforce. new Perforce.P4.Options(1234) generates an option of '-c 1234' which 'p4 files' doesn't accept. That's why the error message is 'Usage: files/print [-o localFile -q] files...Invalid option: -c.'
I struggled with the same problem as well. Finally based on Matt's answer I got it working. Please see simple example below.
using (Connection con = rep.Connection)
{
//setting up client object with viewmap
Client client = new Client();
client.Name = "p4apinet_solution_builder_sample_application_client";
client.OwnerName = "p4username";
client.Root = "c:\\clientRootPath";
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.RevertUnchanged);
client.ViewMap = new ViewMap();
client.ViewMap.Add("//depotpath/to/your/file.txt", "//" + client.Name + "/clientpath/to/your/file.txt", MapType.Include);
//connecting to p4 and creating client on p4 server
Options options = new Options();
options["Password"] = "p4password";
con.UserName = "p4username";
con.Client = new Client();
con.Connect(options);
con.Client = rep.CreateClient(client);
//syncing all files (in this case 1) defined in client's viewmap to the changelist level of 12345
Options syncFlags = new Options(SyncFilesCmdFlags.Force, 100);
VersionSpec changeListLevel = new ChangelistIdVersion(12345);
List<FileSpec> filesToBeSynced = con.Client.ViewMap.Select<MapEntry, FileSpec>(me => new FileSpec(me.Left, changeListLevel)).ToList();
IList<FileSpec> results = con.Client.SyncFiles(filesToBeSynced, syncFlags);
}
The following code should allow you to sync a depot to a particular revision (changelist number).
string uri = "...";
string user = "...";
string workspace = "...";
string pass = "...";
int id = 12345; // the actual changelist number
string depotPath = "//depot/foo/main/...";
int maxItemsToSync = 10000;
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
server = new Server(new ServerAddress(uri));
rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
con.Client.Name = workspace;
// connect
bool connected = con.Connect(null);
if (connected)
{
try
{
// attempt a login
Perforce.P4.Credential cred = con.Login(pass);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
con.Disconnect();
connected = false;
}
if (connected)
{
// get p4 info and show successful connection
ServerMetaData info = rep.GetServerMetaData(null);
Console.WriteLine("CONNECTED TO " + info.Address.Uri);
Console.WriteLine("");
try
{
Options opts = new Options();
// uncomment below lines to only get a preview of the sync w/o updating the workspace
//SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.Preview, maxItemsToSync);
SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.None, maxItemsToSync);
VersionSpec version = new ChangelistIdVersion(id);
PathSpec path = new DepotPath(depotPath);
FileSpec depotFile = new FileSpec(path, version);
IList<FileSpec> syncedFiles = rep.Connection.Client.SyncFiles(syncOpts, depotFile);
//foreach (var file in syncedFiles)
//{
// Console.WriteLine(file.ToString());
//}
Console.WriteLine($"{syncedFiles.Count} files got synced!");
}
catch (Exception ex)
{
Console.WriteLine("");
Console.WriteLine(ex.Message);
Console.WriteLine("");
}
finally
{
con.Disconnect();
}
}
}
If you are looking for other ways to build the file spec, like for example sync only a specific list of files to "head", etc, visit this link and search for "Building a FileSpec"

I am getting An Error with c# and Docusign How Do i resolve this error

I am getting the error
Unable to load template. Unable to load template from TemplateReference(0). Error: Data at the root level is invalid. Line 1, position 1.
below is a simplified version of the code i am using...
If i don't use the template reference type of the code everything works fine. But when i start using a template reference.. Nothing works and i get this error. Anyone have a suggestion?
TemplateReference _tempRef = new TemplateReference();
TemplateReference[] _tempRefs = new TemplateReference[] { };
TemplateReferenceRoleAssignment[] _roleAssignmentArray = new TemplateReferenceRoleAssignment[] { };
Recipient[] _recipientsArray = new Recipient[] { };
EnvelopeInformation envelope = new EnvelopeInformation();
Recipient recipient = new Recipient();
recipient.ID = "1";
recipient.Email = "someemail#somewhere.com";
recipient.UserName = "Some Person";
recipient.Type = RecipientTypeCode.Signer;
recipient.RequireIDLookup = false;
Array.Resize(ref _roleAssignmentArray, 1);
Array.Resize(ref _recipientsArray, 1);
_recipientsArray[0] = recipient;
var saRoleAssignment = new TemplateReferenceRoleAssignment
{
RecipientID = "1",
RoleName = "SA"
};
_roleAssignmentArray[0] = saRoleAssignment;
var reference = new Docusign.TemplateReference();
reference.Template = "49C0BE2B-48F7-4F38-B44A-19EB8E6A1A38";
reference.Document = new Docusign.Document();
reference.Document.PDFBytes = new byte[0];
reference.Document.ID = Convert.ToString(1);
reference.Document.Name = "please work";
reference.RoleAssignments = _roleAssignmentArray;
Array.Resize(ref _tempRefs, 1);
_tempRefs[1 - 1] = reference;
//.NET
//.NET
envelope.AccountId = "accountID";
envelope.Subject = "Sample Application";
envelope.EmailBlurb = "You can add a personal message here.";
APIServiceSoapClient apiService = new APIServiceSoapClient();
apiService.ClientCredentials.UserName.UserName = "userhere";
apiService.ClientCredentials.UserName.Password = "pass";
var status = apiService.CreateEnvelopeFromTemplates(_tempRefs, _recipientsArray, envelope, true);
If you're using DocuSign's SOAP api instead of REST then you should definitely familiarize yourself with the SOAP SDK on GitHub:
https://github.com/docusign/DocuSign-eSignature-SDK
There's an MS.NET (C#) version which has sample code that works out of the box, you only need to enter your api credentials. I suggest you use that as your project base, especially since it was updated recently.
Since you have not identified which line the error is stemming from it's a little hard to debug, but if you look at SendTemplate.aspx.cs in the SDK you'll see that the template reference is instantiated like this:
// Construct the template reference
var templateReference = new DocuSignAPI.TemplateReference
{
TemplateLocation = DocuSignAPI.TemplateLocationCode.Server,
Template = TemplateTable.Value,
RoleAssignments = CreateFinalRoleAssignments(recipients)
};
where CreateFinalRoleAssignments() is defined as:
protected DocuSignAPI.TemplateReferenceRoleAssignment[] CreateFinalRoleAssignments(DocuSignAPI.Recipient[] recipients)
{
// Match up all the recipients to the roles on the template
return recipients.Select(recipient => new DocuSignAPI.TemplateReferenceRoleAssignment
{
RecipientID = recipient.ID, RoleName = recipient.RoleName
}).ToArray();
}

Using Exchange Web Services v1 to retrieve emails from a generic mailbox?

I am using Exchange Web Services v1 to pull down unread emails from a user's mailbox like so:
//get exchange service
ExchangeServiceBinding exchangeService = new ExchangeServiceBinding();
exchangeService.Credentials = credentials; //LAN credentials of user
exchangeService.Url = URL; // http://myserver.com/ews/exchange.asmx
//REturn all properties
FindItemType findType = new FindItemType();
findType.Traversal = ItemQueryTraversalType.Shallow;
findType.ItemShape = new ItemResponseShapeType();
findType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
//Only search the inbox
DistinguishedFolderIdType[] foldersToSearch = new DistinguishedFolderIdType[1];
foldersToSearch[0] = new DistinguishedFolderIdType();
foldersToSearch[0].Id = DistinguishedFolderIdNameType.inbox;
findType.ParentFolderIds = foldersToSearch;
//Only unread emails
RestrictionType restriction = new RestrictionType();
IsEqualToType isEqualTo = new IsEqualToType();
PathToUnindexedFieldType pathToFieldType = new PathToUnindexedFieldType();
pathToFieldType.FieldURI = UnindexedFieldURIType.messageIsRead;
//Not IsRead
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "0";
constantType.Item = constantValueType;
isEqualTo.Item = pathToFieldType;
isEqualTo.FieldURIOrConstant = constantType;
restriction.Item = isEqualTo;
findType.Restriction = restriction;
FindItemResponseType findResponse = exchangeService.FindItem(findType);
ResponseMessageType[] responseMessType = findResponse.ResponseMessages.Items;
List<ItemIdType> unreadItemIds = new List<ItemIdType>();
Now I would like to find emails from a generic mailbox.
How would I go about specifying the mailbox I would like to pull emails from?

SAP Enterprise Service Workspace

I am trying to consume some of these services in .Net/C#. Some of the Service could be easily consumed but with others i have got a misleading error.
this a part of the code:
input.AcademicProgramOfStudySelectionByName = new AcademicProgramOfStudyByNameQueryMessage_syncAcademicProgramOfStudySelectionByName();
input.AcademicProgramOfStudySelectionByName.AcademicProgramOfStudyName.languageCode = "DE";
I am getting at the second line the error "Object reference not set to an object instance."
but i have create the object in the first line!
The same code works in some other service!
you created the object
input.AcademicProgramOfStudySelectionByName, but you did not create its member input.AcademicProgramOfStudySelectionByName.AcademicProgramOfStudyName. As it seems, the constructor of class AcademicProgramOfStudyByNameQueryMessage_syncAcademicProgramOfStudySelectionByName does not populate its member AcademicProgramOfStudyName. So when you try to assign a value to a member of AcademicProgramOfStudyName and that instance is NULL, you get an exception.
Example code:
AcademicProgramOfStudyByNameQueryResponse_InClient client =
new AcademicProgramOfStudyByNameQueryResponse_InClient();
client.ClientCredentials.UserName.UserName = "XX";
client.ClientCredentials.UserName.Password = "YY";
AcademicProgramOfStudyByNameQueryMessage_sync input =
new AcademicProgramOfStudyByNameQueryMessage_sync();
input.AcademicProgramOfStudySelectionByName = new AcademicProgramOfStudyByNameQueryMessage_syncAcademicProgramOfStudySelectionByName();
// this is the member that currently is still NULL and has to be created:
input.AcademicProgramOfStudySelectionByName.AcademicProgramOfStudyName = new <insert whatever class is needed here>
// now this should work without throwing an exception
input.AcademicProgramOfStudySelectionByName.AcademicProgramOfStudyName.languageCode = "DE";
AcademicProgramOfStudyByNameResponseMessage_sync output =
new AcademicProgramOfStudyByNameResponseMessage_sync();
output = client.AcademicProgramOfStudyByNameQueryResponse_In(input);
it is really strange. see this compare:
In this code i get the error
AcademicProgramOfStudyByNameQueryResponse_InClient client =
new AcademicProgramOfStudyByNameQueryResponse_InClient();
client.ClientCredentials.UserName.UserName = "XX";
client.ClientCredentials.UserName.Password = "YY";
AcademicProgramOfStudyByNameQueryMessage_sync input =
new AcademicProgramOfStudyByNameQueryMessage_sync();
input.AcademicProgramOfStudySelectionByName = new AcademicProgramOfStudyByNameQueryMessage_syncAcademicProgramOfStudySelectionByName();
input.AcademicProgramOfStudySelectionByName.AcademicProgramOfStudyName.languageCode = "DE";
AcademicProgramOfStudyByNameResponseMessage_sync output =
new AcademicProgramOfStudyByNameResponseMessage_sync();
output = client.AcademicProgramOfStudyByNameQueryResponse_In(input);
and in this code i dont!!
CustomerSimpleByNameAndAddressQueryResponse_InClient client =
new CustomerSimpleByNameAndAddressQueryResponse_InClient();
client.ClientCredentials.UserName.UserName = "XX";
client.ClientCredentials.UserName.Password = "YY";
CustomerSimpleByNameAndAddressQueryMessage_sync input = new CustomerSimpleByNameAndAddressQueryMessage_sync();
input.CustomerSimpleSelectionByNameAndAddress = new CustomerSimpleByNameAndAddressQueryMessage_syncCustomerSimpleSelectionByNameAndAddress();
input.CustomerSimpleSelectionByNameAndAddress.CustomerAddressCityName = "Berlin";
CustomerSimpleByNameAndAddressResponseMessage_sync output = new CustomerSimpleByNameAndAddressResponseMessage_sync();
output = client.CustomerSimpleByNameAndAddressQueryResponse_In(input);

Categories

Resources