I built a login/register system, and I want that when you create a username it checks if email exists, it works fine and it shows the message box "Email exists", but when it is a new user and there is no email that exists, it crashes.
Here is the exception message:
(System.NullReferenceException) Message=The object reference was not set to an object instance
Code:
FirebaseResponse response = await client.GetTaskAsync("Information/" + Emailtextbox.TextName);
Data result = response.ResultAs<Data>();
if (Emailtextbox.TextName == result.Email)
{
MessageBox.Show("Email exists");
} else
{
var data = new Data
{
Email = Emailtextbox.TextName,
Fullname = Fullnametextbox.TextName,
Password = EncryptSHA.GetShaData(PasswordTextbox.TextName)
}
};
Updating this based on the screenshot of the error as well as the information provided in the following comments.
It looks like your error has to do with what's being returned from your client.GetTaskAsync("Information/" + Emailtextbox.Textname); call.
My recommendation would be to try and understand what it is you're receiving from that call (what's stored in your response object). With the latest screenshot I see that the Body is null, and that might be part of the problem. Try expanding what you see in the Response object in your response and see if you're even receiving any kind of data you can use and go from there.
Related
Have the following code.
if (attachments != null)
{
if (attachments.Length > 0)
{
_newTask.Attachments = new TodoTaskAttachmentsCollectionPage();
foreach (var _attachment in attachments)
{
_newTask.Attachments.Add(new TaskFileAttachment
{
Name = _attachment.FileName,
ContentBytes = _attachment.ContentBytes,
ContentType = _attachment.ContentType
});
}
}
}
await _graphServiceClient.Users[idUser].Todo.Lists[idList].Tasks.Request().AddAsync(_newTask);
Im trying to add multiple small files to a task and then post it to the graph api.
But it results in the following error:
One or more errors occurred. (One or more errors occurred. (A type
named 'microsoft.toDo.taskFileAttachment' could not be resolved by the
model. When a model is available, each type name must resolve to a
valid type.
Basically saying that the type taskFileAttachment is not the correct type to add to the collection of attachments of a task.
But, according to MSdoc that's the correct type to add.
Cant see what i'm missing and there is not a lot of documentation of how to post small files to a task. I already done it through the api for mails and thought it was really straightforward but it looks as it is not the case.
As per the docs , there are list of property that are required when you create the todoTask , in that you can't find any property to attach the file
First try to create a new listItems , and attach the file
Sample to attach the file
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var attachmentBase = new TaskFileAttachment
{
Name = "smile",
ContentBytes = Convert.FromBase64String("a0b1c76de9f7="),
ContentType = "image/gif"
};
await graphClient.Me.Todo.Lists["{todoTaskList-id}"].Tasks["{todoTask-id}"].Attachments
.Request()
.AddAsync(attachmentBase);
So as they commented in my original post, there is no current way to attach a collection of files in one single request. They must attached to a created task one at a time.
I have a C# backend code that receives a POST request from the client side code in TypeScript.
The JSON is done for the POST with JSON.stringify(objectOfData);
In the C# code I am getting an exception when I try to use the object like so:
// Passed into this function is InboundObjectDTO inboundObject
// inboundObject.Email in debugger is like so: "\"a#example.com\""
var message = new MailMessageDTO
{
Subject = "My Subject",
MailAddresses = new List<MailAddress>()
};
message.MailAddresses.Add(new MailAddress(inboundObject.Email));
Am I supposed to deserialize the object somehow before hand? I have 3 strings in the object: email, message, and name.
The last line of code above gives me "An invalid character in MailAddresses exception." I am guessing it needs to have all the extra quotes and such removed in a proper way.
As OP had originally postulated, the issue is the quotes around the email address, all we need to do is remove those quotes. This process is referred to as Sanitizing the input.
The original methodology was hard to follow and the exception information posted was ambiguous, this solution shows how to sanitise the input and return more relevant information with the exception.
The example you have pasted ""a#example.com"" would not fail in your original code that included the santize logic, if you had simply used the result of the sanitize step!
You should wrap the code block in a try-catch so you can capture the exception and output the specific string value that has failed:
string email = inboundObject.Email;
MailMessageDTO message = null;
try
{
// sanitized the email, removed known invalid characters
email = email.Replace("\"", "");
// construct the payload object
message = new MailMessageDTO
{
Subject = "My Subject",
MailAddresses = new List<MailAddress>()
};
message.MailAddresses.Add(new MailAddress(email));
}
catch (Exception ex)
{
throw new ApplicationException($"Failed to construct MailMessage for email: {email}", ex);
}
Now when this fails, we have more information to work with inside the exception, infact this situation itself probably warrants it's own separate reusable method:
public MailAddress SanitizeEmail(string emailAddress)
{
string email = emailAddress;
try
{
// sanitized the email, removed known invalid characters
email = email.Replace("\"", "");
// TODO: add other rules an replacement cases as you find them
return new MailAddress(email);
}
catch (Exception ex)
{
throw new ApplicationException($"Failed to sanitize email address: '{email}' [original input: '{emailAddress ?? "NULL" }']", ex);
}
}
You could call this using:
message.MailAddresses.Add(SanitizeEmail(email));
Update
OP's original code included references and test conditions that are no longer in the posted code, this response has only been marginally updated to reflect those changes
If you are posting json data to controller action,you can use [FromBody],[FromBody] will get values from the request body:
public IActionResult Index([FromBody]inboundObject inboundObject)
{
...
}
Or you can use JsonConvert.DeserializeObject to deserialize the the JSON to specified .NET type:
message.MailAddresses.Add(new MailAddress(JsonConvert.DeserializeObject<string>(inboundObject.Email)));
I am using stripe connect(destination payment) with the help of stripe.net library from Jaymedavis.
The problem that I am facing is that I am not able to retrieve the destination payment ID to update the metadata in the connected account. The following line returns a null preventing me from updating meta data on the connected account. But the strange thing is that when I log in to the dashboard the destination payment ID exists. I am not sure why I am not able to retreive it in code.
Is the charge creation asynchronous?. I am not sure. Stripe's connect documentation does not help either. The following line returns a null. My code is down below. Seeking help.
String deschargeID = result.Transfer.DestinationPayment;
Here is the code that I am using
var service = new StripeChargeService(ZambreroSecretKey);
var result = (Stripe.StripeCharge) null;
try {
result = service.Create(newCharge);
if (result.Paid) {
//get the chargeID on the newgen account and update the metadata.
//Returns null even though it exists in the dashboard
String deschargeID = result.Transfer.DestinationPayment;
var chargeService = new StripeChargeService(newgenSecretKey);
StripeCharge charge = chargeService.Get(deschargeID);
charge.Metadata = myDict;
Response.Redirect("PgeCustSuccess.aspx?OrderID=" + OrderID);
}
} catch (StripeException stripeException) {
Debug.WriteLine(stripeException.Message);
stripe.Text = stripeException.Message;
}
The charge object's transfer attribute is not expanded by default, meaning it's just a string with the ID of the transfer object ("tr_..."), not a full transfer object.
According to Stripe.net's documentation, you can expand the transfer attribute by adding this line:
service.ExpandTransfer = True
before sending the charge creation request.
How to retrieve email based on time in Google api using c#?
Can we pass date time to query string for getting the latest email?
While working around this one i am able to find pas the date only.
Is there any way to get the latest mail based on time?
Yes, you can achieve this by passing in a query parameter along with Get Message List call of Gmail API like below:
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.Q = query;//This is where you put in your data query
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
Query parameter is the same as you pass in your mailbox search box. e.g. after:2015/6/28 before:2015/7/1
Afterwards, fetch individual message details by calling Get with message ID.
Hope this helps.
Furhan's answer is great. I would just like to add, that if you want to search for mails more specifically than 2015/6/28, you can supply e.g. after:<TIME_IN_SECONDS_SINCE_EPOCH>
Let's say you wanted mail after:2015/6/28 12:55:00 and before:2015/7/1 02:30:00, your would write:
after:1435496100 before:1435710600
Using: Drive v2: 1.5.0.99 Beta, .NET Framework: 4.5
The authentication takes place properly (using impersonation) - via service account (AssertionFlowClient).
Access token is obtained. Service account has been granted domain wide privileges
I am able to get the parent folder - ID (strRootFolder) via Service.Files.List();
byte[] byteArray = System.IO.File.ReadAllBytes(FileName);
Google.Apis.Drive.v2.Data.File flUpload = new Google.Apis.Drive.v2.Data.File();
flUpload.Title = Title;
flUpload.Description = Description;
flUpload.MimeType = MimeType;
flUpload.Parents = new List<ParentReference>() { new ParentReference() { Id = strRootFolder } };
Google.Apis.Drive.v2.FilesResource.InsertMediaUpload drvRequest = drvService.Files.Insert(flUpload, new System.IO.MemoryStream(byteArray), "text/plain");
drvRequest.Upload();
However Upload method does not send any request. No exception is thrown. Fiddler trace shows no request has been sent and hence request.responsebody is always null.
Am I missing something ?
If some exception occur during the upload, the return object (IUploadProgress) should contain the exception (take a look at the Exception property).
Please check what is the exception.
You should also consider using UploadAsync which doesn't block your code (but first you should understand what is the exception)
You should look into Exception from your upload, that will give you a better idea of the actual problem.
Sample code:
var progress = request.Upload();
if (progress.Exception != null)
{
//Log execption, or break here to debug
YourLoggingProvider.Log(progress.Exception.Message.ToString());
}