Message.Payload is always null for all messages. How do I get this data? - gmail-api

It is returning the correct number of message, but the only fields that are populated are Id and ThreadId. Everything else is null
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
ListMessagesResponse response = service.Users.Messages.List(emailAddress).Execute();
IList<Google.Apis.Gmail.v1.Data.Message> messages = response.Messages;
Console.WriteLine("Messages:");
if (messages != null && messages.Count > 0)
{
foreach (var message in messages)
{
Console.WriteLine("{0}", message.Payload.Body);
Console.WriteLine();
}
}
else
{
Console.WriteLine("No Messages found.");
}

Messages.List() only returns message and thread ids. To retrieve message contents, you need to invoke Get() for each message you are interested in. Updated version of your foreach loop example:
foreach (var message in messages)
{
Message m = service.Users.Messages.Get("me", message.Id).Execute();
// m.Payload is populated now.
foreach (var part in m.Payload.Parts)
{
byte[] data = Convert.FromBase64String(part.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
}
}
Note: You may need to run a string replace on the part.Body.Data string. See this post for instructions.

Related

Tenant to tenant user migration in Azure Active Directory using Graph API

Is it possible to migrate users using the MS Graph API in Azure AD?
If so, please explain how to migrate users from one tenant to the other using the MS Graph API.
You can export the users with MS Graph. Note, you can't export the passwords. This means that you have to create a new password and share it with the users. Or choose a random password and let the users reset their password using the self-service password rest feature.
Here is an example how to export the users from a directly
public static async Task ListUsers(GraphServiceClient graphClient)
{
Console.WriteLine("Getting list of users...");
DateTime startTime = DateTime.Now;
Dictionary<string, string> usersCollection = new Dictionary<string, string>();
int page = 0;
try
{
// Get all users
var users = await graphClient.Users
.Request()
.Select(e => new
{
e.DisplayName,
e.Id
}).OrderBy("DisplayName")
.GetAsync();
// Iterate over all the users in the directory
var pageIterator = PageIterator<User>
.CreatePageIterator(
graphClient,
users,
// Callback executed for each user in the collection
(user) =>
{
usersCollection.Add(user.DisplayName, user.Id);
return true;
},
// Used to configure subsequent page requests
(req) =>
{
var d = DateTime.Now - startTime;
Console.WriteLine($"{string.Format(TIME_FORMAT, d.Days, d.Hours, d.Minutes, d.Seconds)} users: {usersCollection.Count}");
// Set a variable to the Documents path.
string filePrefix = "0";
if (usersCollection.Count >= 1000000)
{
filePrefix = usersCollection.Count.ToString()[0].ToString();
}
page++;
if (page >= 50)
{
page = 0;
string docPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"users_{filePrefix}.json");
System.IO.File.WriteAllTextAsync(docPath, JsonSerializer.Serialize(usersCollection));
}
Thread.Sleep(200);
return req;
}
);
await pageIterator.IterateAsync();
// Write last page
string docPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"users_all.json");
System.IO.File.WriteAllTextAsync(docPath, JsonSerializer.Serialize(usersCollection));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
After you export the users, you can import them back to the other tenant. The following example creates test users. Change the code to set the values from the files you exported earlier. Also, this code uses batch with 20 users in single operation.
public static async Task CreateTestUsers(GraphServiceClient graphClient, AppSettings appSettings, bool addMissingUsers)
{
Console.Write("Enter the from value: ");
int from = int.Parse(Console.ReadLine()!);
Console.Write("Enter the to value: ");
int to = int.Parse(Console.ReadLine()!);
int count = 0;
Console.WriteLine("Starting create test users operation...");
DateTime startTime = DateTime.Now;
Dictionary<string, string> existingUsers = new Dictionary<string, string>();
// Add the missing users
if (addMissingUsers)
{
// Set a variable to the Documents path.
string docPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "users.json");
if (!System.IO.File.Exists(docPath))
{
Console.WriteLine("Can't find the '{docPath}' file.");
}
string usersFile = System.IO.File.ReadAllText(docPath);
existingUsers = JsonSerializer.Deserialize<Dictionary<string, string>>(usersFile);
if (existingUsers == null)
{
Console.WriteLine("Can't deserialize users");
return;
}
Console.WriteLine($"There are {existingUsers.Count} in the directory");
}
List<User> users = new List<User>();
// The batch object
var batchRequestContent = new BatchRequestContent();
for (int i = from; i < to; i++)
{
// 1,000,000
string ID = TEST_USER_PREFIX + i.ToString().PadLeft(7, '0');
if (addMissingUsers)
{
if (existingUsers.ContainsKey(ID))
continue;
}
count++;
try
{
var user = new User
{
DisplayName = ID,
JobTitle = ID.Substring(ID.Length - 1),
Identities = new List<ObjectIdentity>()
{
new ObjectIdentity
{
SignInType = "userName",
Issuer = appSettings.TenantName,
IssuerAssignedId = ID
},
new ObjectIdentity
{
SignInType = "emailAddress",
Issuer = appSettings.TenantName,
IssuerAssignedId = $"{ID}#{TEST_USER_SUFFIX}"
}
},
PasswordProfile = new PasswordProfile
{
Password = "1",
ForceChangePasswordNextSignIn = false
},
PasswordPolicies = "DisablePasswordExpiration,DisableStrongPassword"
};
users.Add(user);
if (addMissingUsers)
{
Console.WriteLine($"Adding missing {ID} user");
}
// POST requests are handled a bit differently
// The SDK request builders generate GET requests, so
// you must get the HttpRequestMessage and convert to a POST
var jsonEvent = graphClient.HttpProvider.Serializer.SerializeAsJsonContent(user);
HttpRequestMessage addUserRequest = graphClient.Users.Request().GetHttpRequestMessage();
addUserRequest.Method = HttpMethod.Post;
addUserRequest.Content = jsonEvent;
if (batchRequestContent.BatchRequestSteps.Count >= BATCH_SIZE)
{
var d = DateTime.Now - startTime;
Console.WriteLine($"{string.Format(TIME_FORMAT, d.Days, d.Hours, d.Minutes, d.Seconds)}, count: {count}, user: {ID}");
// Run sent the batch requests
var returnedResponse = await graphClient.Batch.Request().PostAsync(batchRequestContent);
// Dispose the HTTP request and empty the batch collection
foreach (var step in batchRequestContent.BatchRequestSteps) ((BatchRequestStep)step.Value).Request.Dispose();
batchRequestContent = new BatchRequestContent();
}
// Add the event to the batch operations
batchRequestContent.AddBatchRequestStep(addUserRequest);
// Console.WriteLine($"User '{user.DisplayName}' successfully created.");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

An unexpected null key in HashSet, the first be added not the rest

I'm learning Activiti 7, I drew a BPMN diagram as below:
When the highlight1 UserTask has been completed but the highlight2 UserTask is still pending, I ran the following code to highlight the completed flow element.
private AjaxResponse highlightHistoricProcess(#RequestParam("instanceId") String instanceId,
#AuthenticationPrincipal UserInfo userInfo) {
try {
// Get the instance from the history table
HistoricProcessInstance instance = historyService
.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
BpmnModel bpmnModel = repositoryService.getBpmnModel(instance.getProcessDefinitionId());
Process process = bpmnModel.getProcesses().get(0);
// Get all process elements, including sequences, events, activities, etc.
Collection<FlowElement> flowElements = process.getFlowElements();
Map<String, String> sequenceFlowMap = Maps.newHashMap();
flowElements.forEach(e -> {
if (e instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) e;
String sourceRef = sequenceFlow.getSourceRef();
String targetRef = sequenceFlow.getTargetRef();
sequenceFlowMap.put(sourceRef + targetRef, sequenceFlow.getId());
}
});
// Get all historical Activities, i.e. those that have been executed and those that are currently being executed
List<HistoricActivityInstance> actList = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.list();
// Each history Activity is combined two by two
Set<String> actPairSet = new HashSet<>();
for (HistoricActivityInstance actA : actList) {
for (HistoricActivityInstance actB : actList) {
if (actA != actB) {
actPairSet.add(actA.getActivityId() + actB.getActivityId());
}
}
}
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
// Get the completed Activity
List<HistoricActivityInstance> finishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.finished()
.list();
// Highlight the completed Activity
Set<String> highActSet = Sets.newHashSet();
finishedActList.forEach(point -> highActSet.add(point.getActivityId()));
// Get the pending highlighted node, i.e. the currently executing node
List<HistoricActivityInstance> unfinishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.unfinished()
.list();
Set<String> unfinishedPointSet = Sets.newHashSet();
unfinishedActList.forEach(point -> unfinishedPointSet.add(point.getActivityId()));
...
return AjaxResponse.ajax(ResponseCode.SUCCESS.getCode(),
ResponseCode.SUCCESS.getDesc(),
null);
} catch (Exception e) {
e.printStackTrace();
return AjaxResponse.ajax(ResponseCode.ERROR.getCode(),
"highlight failure",
e.toString());
}
}
Please see this piece of code:
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
It was expected to get 2 elements in the highSequenceSet, but it got 3, with a unexpected null.
The log printed in the console was:
Why is the first null added to the HashSet but not the rest?
Why is the first null added to the HashSet but not the rest?
HashSet implements the Set interface, duplicate values are not allowed.

How to send encrypted (3DES) data into aqueduct without getting any error?

I m using Aqueduct 3.0. I need to learn How to capture post request in Aqueduct 3.0?
My Request: http://127.0.0.1:8888/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU
Get a Response:
[INFO] aqueduct: GET /login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU 11ms 404
my channel.dart routing
// TODO: connect to Socket **********
router.route('/login/[:value]').link(() {
return new LoginController();
//..contentType = ContentType.TEXT;
});
my LoginController.dart
import 'package:aqueduct/aqueduct.dart';
import 'package:niyaziapi/niyaziapi.dart';
import 'package:niyaziapi/util/niyaziGetPrivate.dart';
import 'package:niyaziapi/util/niyaziSetPrivate.dart';
class LoginController extends Controller {
String _xCustomerToken;
String _xCustomerName;
String _xPrivate;
String _xResult;
String _xRequestValue;
String _xReply;
#override
Future<RequestOrResponse> processRequest(Request request) async {
String tempData = request.toString();
print("tempDate: $tempData"); // can’t print
try {
if (request.path.variables.containsKey('value')) {
_xPrivate = (request.path.variables['value']).trim();
print("_xPrivate: $_xPrivate");
var decryptedData = await getPrivate(_xPrivate);
var decryptedList = decryptedData.split(":_:");
decryptedData = null;
decryptedData = "Q101:_:" + decryptedList[2].toString() + ":_:" + decryptedList[3].toString();
print(decryptedData);
var socket = await Socket.connect('192.168.1.22', 1024);
socket.write("$decryptedData\r\n");
await for (var data in socket) {
_xReply = new String.fromCharCodes(data).trim();
var list = _xReply.split(":_:");
_xCustomerToken = list[2].toString();
_xCustomerName = list[3].toString();
});
_xResult = "$_xCustomerToken:_:$_xCustomerName";
var encryptedData = await setPrivate(_xResult);
return new Response.ok("$encryptedData");
}
} else {
return new Response.ok("404: Wrong Request");
}
} catch (e) {
return new Response.ok("404: $e.errorMessage");
}
}
}
when I testing I found that my code works. Only reason that I am sending 3DES data and has + and / character in it.
If you look at closely in first request, there is a + and / character in data which give me an error.
/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU 19ms 404
on the other hand if I remove those character than I get perfect response.
/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjMoHROYzYTHnd3NH1XfHRULY0jaHU 13 ms 200
So, question comes how to send encrypted (3DES) data into aqueduct without getting any error?
Going to Like Aqueduct twice :)
It was very simple:
var _xPrivate = (request.path.variables['value']).trim(); change to:
var _xPrivate = request.path.remainingPath;
print("request: $_xPrivate");

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

Strange error message when using SaveChanges in EF with MVC

I have a dropdownlistfor with values that is not from my database, and when a user select values that does not exist in my database, I want to save it to the database(and if it already exist, I just use the existing data).
This work fine with some of my data(see code for where it does not work)
This is my repository:
public void newPerson(Person addperson)
{
db.Person.AddObject(addperson);
db.SaveChanges(); //This wont work
}
here is my controller:
[HttpPost]
public ActionResult Create(CreateNKIphase1ViewModel model)
{
if (ModelState.IsValid)
{
var goalcard = new GoalCard();
var companyChecker = "";
var dbCompanies = createNKIRep.GetCustomerByName();
var addcustomer = new Customer();
foreach (var existingcustomer in dbCompanies)
{
companyChecker = existingcustomer.CompanyName;
if (existingcustomer.CompanyName == model.CompanyName)
{
var customerId = existingcustomer.Id;
var selectedCustomerID = createNKIRep.GetByCustomerID(customerId);
goalcard.Customer = selectedCustomerID;
break;
}
}
if (companyChecker != model.CompanyName)
{
addcustomer.CompanyName = model.CompanyName;
createNKIRep.newCustomer(addcustomer); //This works!
goalcard.Customer = addcustomer;
}
if (model.PersonName != null)
{
var Personchecker = "";
var dbPersons = createNKIRep.GetPersonsByName();
foreach (var existingPerson in dbPersons)
{
Personchecker = existingPerson.Name;
if (existingPerson.Name == model.PersonName)
{
var personId = existingPerson.Id;
var selectedPersonID = createNKIRep.GetByPersonID(personId);
goalcard.Person = selectedPersonID;
break;
}
}
if (Personchecker != model.PersonName)
{
Person newPerson = new Person();
newPerson.Name = model.PersonName;
createNKIRep.newPerson(newPerson);//Where repository is called
goalcard.Person = newPerson;
}
}
But when I try to save a new Person I get the following error message:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Even though Person only have Id and name as attributes in my database.
Is there anything wrong in my code, or is it any setting in my database that has to be changed?
Thanks in advance.
It's because I use db.SaveChanges(); multiple times in one post. Reducing numbers of time I use db.SaveChanges helped me get rid of the error.

Resources