.NET MVC Web API Upload file to local storage and data model to database - asp.net-web-api

I want to upload a file and pass the model with it. But when I try it from postman, it Always bring error.
Here is my code
public async Task<IHttpActionResult> PostArPumPd([FromBody] tx_arPumPd pum)
{
try
{
if (pum == null)
{
return Content(HttpStatusCode.BadRequest, "Enter the data correctly");
}
else
{
tx_arPumPd arpumpds = new tx_arPumPd()
{
doc_no = doc,
doc_date = DateTime.Now,
descs = pum.descs,
currency_code = pum.currency_code,
amount = pum.amount,
employee_code = pum.employee_code,
head_code = pum.head_code,
company_code = pum.company_code,
created_by = pum.emp_code,
created_date = DateTime.Now
};
db.tx_arPumPd.Add(arpumpds);
var multiFormDataStreamProvider = new MultiFileUploadProvider(Constants.MEDIA_PATH);
var mod = "PP";
var newFileName = mod + "_" + doc;
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
try
{
await FileHelper.Upload(multiFormDataStreamProvider, mod, newFileName);
db.SaveChanges();
return Content(HttpStatusCode.Created, "Data was save");
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
I get an Error while i get to this part
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
This is the error
ioexception: unexpected end of mime multipart stream. mime multipart
message is not complete test with postman
Is there anyone who know why? And Help me to upload file and the data model?
Thank you very much for your help

Okay I found the answer. To save a file and the Form data, i'm not parse the model. I'm just send the data from postmant using form data and the value is Json data. So I read the request from ReadAsMultipartAsync and get the Json data, and then deserilize the json. After that we can save the data.
This how I send the data from postmant
Postmant
and this is the code
public async Task<IHttpActionResult> PostArPumPd()
{
try
{
var multiFormDataStreamProvider = new MultiFileUploadProvider(Constants.MEDIA_PATH);
var readToProvider = await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
// Get Json Data and Deserialize it
var json = await readToProvider.Contents[0].ReadAsStringAsync();
tx_arPumPd a = JsonConvert.DeserializeObject<tx_arPumPd>(json);
// Set mod and file name for FileHelper classl
var mod = "PP";
var newFileName = mod + "_" + doc ;
tx_arPumPd arpumpds = new tx_arPumPd()
{
doc_no = doc,
doc_date = DateTime.Now,
descs = a.descs,
currency_code = a.currency_code,
amount = a.amount,
employee_code = a.employee_code,
head_code = a.head_code,
company_code = a.company_code,
created_by = a.emp_code,
created_date = DateTime.Now
};
db.tx_arPumPd.Add(arpumpds);
var dtl = a.tx_arPumPdDtl;
foreach (var item in dtl)
{
item.doc_no = doc;
item.bg_is_ok = true;
item.bg_approved = true;
item.bg_app_date = DateTime.Now;
item.created_by = a.emp_Code;
item.created_date = DateTime.Now;
db.tx_arPumPdDtl.Add(item);
}
try
{
await FileHelper.Upload(multiFormDataStreamProvider, mod, newFileName);
db.SaveChanges();
return Content(HttpStatusCode.Created, "Data was save");
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
if anyone has a better way to do this, i'm still very happy getting to know about it.
Thank you.

Related

How to get a CNContact phone number(s) as string in Xamarin.ios?

I am attempting to retrieve the names and phone number(s) of all contacts and show them into tableview in Xamarin.iOS. I have made it this far:
var response = new List<ContactVm>();
try
{
//We can specify the properties that we need to fetch from contacts
var keysToFetch = new[] {
CNContactKey.PhoneNumbers, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses
};
//Get the collections of containers
var containerId = new CNContactStore().DefaultContainerIdentifier;
//Fetch the contacts from containers
using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
{
CNContact[] contactList;
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysToFetch, out
var error);
}
//Assign the contact details to our view model objects
response.AddRange(from item in contactList
where item?.EmailAddresses != null
select new ContactVm
{
PhoneNumbers =item.PhoneNumbers,
GivenName = item.GivenName,
FamilyName = item.FamilyName,
EmailId = item.EmailAddresses.Select(m => m.Value.ToString()).ToList()
});
}
BeginInvokeOnMainThread(() =>
{
tblContact.Source = new CustomContactViewController(response);
tblContact.ReloadData();
});
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
and this is my update cell method
internal void updateCell(ContactVm contact)
{
try
{
lblName.Text = contact.GivenName;
lblContact.Text = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
//var no = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
//NSString a = new NSString("");
// var MobNumVar = ((CNPhoneNumber)contact.PhoneNumbers[0]).ValueForKey(new NSString("digits")).ToString();
var c = (contact.PhoneNumbers[0] as CNPhoneNumber).StringValue;
}
catch(Exception ex)
{
throw ex;
}
}
I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value.
this line of code
lblContact.Text = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
throw a run time exception as specified cast is not valid
Yes, exception is correct. First of all, you don't need any casts at all, contact.PhoneNumbers[0] will return you CNLabeledValue, so you just need to write it in next way
lblContact.Text = contact.PhoneNumbers[0].GetLabeledValue(CNLabelKey.Home).StringValue
//or
lblContact.Text = contact.PhoneNumbers[0].GetLabeledValue(CNLabelPhoneNumberKey.Mobile).StringValue
or you may try, but not sure if it works
contact.PhoneNumbers[0].Value.StringValue
I got solution. Here is my code if any one required.
CNLabeledValue<CNPhoneNumber> numbers =
(Contacts.CNLabeledValue<Contacts.CNPhoneNumber>)contact.PhoneNumbers[0];
CNPhoneNumber number = numbers.Value;
string str = number.StringValue;
lblContact.Text = str;

TaskContinuation.cs not found exception while accessing WebAPI Task

I'm trying to fetch records from a db cursor from the Client app.
Debugging Web API shows that the Cursor returns records but when returning to the Client it throws mscorlib.pdb not loaded window and clicking on Load option it throws TaskContinuation.cs not found exception
Code snippets as below ( removed irrelevant codes for readability )
WebAPI
[HttpPost("{values}")]
public async Task<ActionResult> Post([FromBody] JToken values)
{
// code removed for readility
string[] cursors = { };
cursors = await cursor.GetRpts();
CursorClass firstCursor = JsonConvert.DeserializeObject<CursorClass>(cursors[0]);
return new OkObjectResult(cursors);
}
public async Task<string[]> GetRpts()
{
try
{
DataTable[] dataTables;
CursorClass[] cursorClasses = new CursorClass[5];
//stripped some code
using (DataAccess dataAccess = new DataAccess()
{
ParamData = PrepareDoc(),
ProcedureName = Constants.Rpt,
RecordSets = this.CursorNumbers,
})
{
Int32 errorNumber = await dataAccess.RunComAsync();
dataTables = dataAccess.TableData;
};
//fetching code stripped off
string[] _cursors = Array.ConvertAll(cursorClasses, JsonConvert.SerializeObject);
return _cursors;
}
catch (Exception ex)
{
string tt = ex.Message;
}
}
public async Task<Int32> RunComAsync()
{
Int32 returnValue = 0;
try
{
//open db connection
//---------- Running the Command in asysnc mode ----------
Task<int> task = new Task<int>(oracleCommand.ExecuteNonQuery);
task.Start();
returnValue = await task;
//--------------------------------------------------------
OracleRefCursor[] refCursor = { null, null, null, null, null };
for (int _sub = 0; _sub < RecordSets; _sub++)
{
//DT declaration / connection code removed
dataAdapter.Fill(dataTable, refCursor[_sub]);
TableData[_sub] = dataTable;
}
}
catch (Exception ex)
{
return LogMsg(ex);
}
finally
{
this.Dispose(true);
}
CloseConnection();
return LogMsg(null,"Successful Operation");
}
Client
private async Task<HttpStatusCode> CallService()
{
HttpResponseMessage _response = null;
try
{
using (HttpRequestMessage requestMessage = new HttpRequestMessage()
{
Content = new System.Net.Http.StringContent(JsonRepo, System.Text.Encoding.UTF8, HeaderJson),
RequestUri = new Uri(UriString),
Method = HttpMethod.Post,
})
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Utils.TOKEN) ;
_response = await httpClient.SendAsync(requestMessage);
if (_response.IsSuccessStatusCode)
{
string httpResponse = await _response.Content.ReadAsStringAsync();
httpString = JsonConvert.DeserializeObject<string[]>(httpResponse);
}
}
}
return ErrorCode;
}
Is that something related to async operation? while debugging the API it confirms the Datatable with records . Any inputs are deeply appreciated.
error image
TIA

Best practice to send a lot of files (images) from your device to your server

I have a list of files to send from my device to my server.
List<myFiles> list = new List<myFiles>() { "[long list of files...]" };
For that I want to create a list of tasks: for each file I should invoke a function that sends to my webapi that file via PUT
public async Task<bool> UploadPhoto(byte[] photoBytes, int PropertyId, string fileName)
{
bool rtn = false;
if (CrossConnectivity.Current.IsConnected)
{
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(photoBytes);
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = fileName + ".jpg"
};
content.Add(fileContent);
string url = RestURL() + "InventoriesPicture/Put";
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
HttpResponseMessage response = await client.PutAsync(url, content);
if (response.IsSuccessStatusCode)
{
rtn = true;
Debug.WriteLine($"UploadPhoto response {response.ReasonPhrase}");
}
else
{
Debug.WriteLine($"UploadPhoto response {response.ReasonPhrase}");
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"UploadPhoto exception {ex.Message}");
}
Debug.WriteLine($"UploadPhoto ends {fileName}");
}
return rtn;
}
In a function I have a foreach that calls UploadPhoto. I think there are too many tasks at the same time then I want to send a file, wait the result from the webapi and then send next file and so on.
What can I do? What is the best practice for that? Or in any case how can I resolve my problem? :)
Thank you in advance

Return a User and Message in Parse Query

Updated:
I am able to get to here, but I still can't return the username.
public async void getMessagesFromGroup1(string sGroupObjectId) {
try{
var innerQuery = ParseObject.GetQuery("Message").WhereEqualTo("Group", ParseObject.CreateWithoutData("Group", sGroupObjectId)).Include("User"); //.Include("Category");
IEnumerable<ParseObject> MyFirstResults = await innerQuery.FindAsync();
Console.WriteLine("made it past the query");
foreach (var result in MyFirstResults)
{
Console.WriteLine("made it into forloop");
var category = result.Get<string>("Content");
Console.WriteLine ("The message is......... " + category);
var userObject = result.Get<ParseObject>("User");
var user = result.Get<string>("username");
Console.WriteLine ("The from user......... " + user);
// return category;
}
}
catch(Exception exception){
Console.WriteLine ("- " + exception.Message.ToString());
}
}
I am building a message board application using Parse and Xamarin.
I need to query a table of Messages and return the Content of each message and the Username of the person who posted the message.
This should return a list.
I am able to retrieve the Message.Content, but not the User information.
How can I return the username from user table?
I appreciate your advice and thoughts.
Current Code:
public async void getMessagesFromGroup(string sGroupObjectId) {
// OBJECT ID: ejphwBr3UX
var query = from message in ParseObject.GetQuery("Message")
where message["Group"] == ParseObject.CreateWithoutData("Group", sGroupObjectId)
select message;
IEnumerable<ParseObject> results1 = await query.FindAsync ();
// List<ParseObject> list = results.ToList;
List<ParseObject> list = results1.ToList();
Console.WriteLine ("testing");
try
{
Console.WriteLine ("test" + list[0].Get<string>("Content") + " ");
}
catch (Exception exception){
Console.WriteLine ("- " + exception.Message.ToString());
}
// Get our button from the layout resource,
// and attach an event to it
}
Solved.
this is how I did it... I had to convert the Parse Object into a parseuser
public async void getMessagesFromGroup1(string sGroupObjectId) {
try{
var innerQuery = ParseObject.GetQuery("Message").WhereEqualTo("Group", ParseObject.CreateWithoutData("Group", sGroupObjectId)).Include("User"); //.Include("Category");
IEnumerable<ParseObject> MyFirstResults = await innerQuery.FindAsync();
Console.WriteLine("made it past the query");
foreach (var result in MyFirstResults)
{
Console.WriteLine("made it into forloop");
var Content = result.Get<string>("Content");
Console.WriteLine ("The message is......... " + Content);
var userObject = result.Get<ParseUser>("User");
var user = userObject.Username;
Console.WriteLine ("The message is from user......... " + user);
// return category;
}
}
catch(Exception exception){
Console.WriteLine ("- " + exception.Message.ToString());
}
}

Xamarin http webservice issue

I m trying to use http request webservice issue is that when we post wrong username and password the login service generate exception and it can't return any value in async calls.
A code snippet would help assist with the problem ...
However using a try catch should help you catch your exception and prevent application from crashing and handling the exceptions accordingly.
As seen in my sample code below I cater for the incorrect details entered / connectivity problems. I peform the http async request then parse the xml to my model handling the exceptions accordingly
var response = await WebRequestHelper.MakeAsyncRequest(url, content);
if (response.IsSuccessStatusCode == true)
{
Debug.WriteLine("Login Successfull" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
var result = response.Content.ReadAsStringAsync().Result;
result = result.Replace("<xml>", "<LoginResult>").Replace("</xml>", "</LoginResult>");
loginResult = XMLHelper.FromXml<LoginResult>(result);
if (loginResult != null)
{
login.Type = ResultType.OK;
login.Result = loginResult;
}
else
{
login.Type = ResultType.WrongDetails;
}
}
else
{
Debug.WriteLine("Login Failed" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
login.Type = ResultType.WrongDetails;
}
}
catch (Exception ex)
{
login.Type = ResultType.ConnectivityProblem;
}
Web Request
public static async Task<HttpResponseMessage> MakeAsyncRequest(string url, Dictionary<string, string> content)
{
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 5, 0);
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");
if (content == null)
{
content = new Dictionary<string, string>();
}
var encodedContent = new FormUrlEncodedContent(content);
var result = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);
return result;
I would recommend wrapping the response in a generic ServiceResponse where you can store the exceptions. await methods can be included in try/catch blocks so the standard process can be followed.
E.G.
public async Task<ServiceResponse<T>> PostAsync<T>(String address, object dto){
var content = Serializer.SerializeObject (dto);
var response = await client.PostAsync (
address,
new StringContent (content));
if (response.IsSuccessStatusCode) {
try {
var responseString = await response.Content.ReadAsStringAsync ();
return new ServiceResponse<T> (Serializer.DeserializeObject<T> (responseString),
response.StatusCode);
} catch (Exception ex) {
return new ServiceResponse<T> (response.StatusCode, ex);
}
} else {
return new ServiceResponse<T> (response.StatusCode);
}
}
With the ServiceResponse defined as :
public class ServiceResponse<T>
{
public HttpStatusCode StatusCode { get; set;}
public T Value { get; set;}
public String Content { get; set;}
public Exception Error {get;set;}
public ServiceResponse(T value, HttpStatusCode httpStatusCode){
this.Value = value;
this.StatusCode = httpStatusCode;
}
public ServiceResponse(HttpStatusCode httpStatusCode, Exception error = null){
this.StatusCode = httpStatusCode;
this.Error = error;
}
}
This will give you a clean way of managing all your HTTP responses and any errors that may occur.

Resources