I'm developing WP8 app and i'm new to it.. i want to know my post method is correct or not because i'm unable to post my data in the url it produces an exception..
My Class Contents...
public class Register
{
public int id { get; set; }
public string password_reset_hash { get; set; }
public string temp_password { get; set; }
public bool remember_me { get; set; }
public string activation_hash { get; set; }
public string ip_address { get; set; }
public bool status { get; set; }
public bool activated { get; set; }
public string permissions { get; set; }
public DateTime last_login { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string email { get; set; }
public string password { get; set; }
public string conformpassword { get; set; }
public string username { get; set; }
}
here is my code..
public void btn_register_click(object sender, RoutedEventArgs e)
{
string url="myurl";
Register res=new Register();// my class
res.email = txt_email.Text;
res.password = txt_password.Text;
res.conformpassword = txt_conf_psswrd.Text;
res.username = txt_username.Text;
res.created_at = DateTime.Now;
res.last_login = DateTime.Now;
res.updated_at = DateTime.Now;
res.status = true;
json = JsonConvert.SerializeObject(res);
WebClient wc = new WebClient();
var URI = new Uri(url);
wc.Headers["Content-Type"] = "application/json";
wc.Headers["ACCEPT"] = "application/json";
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(URI, "POST", json);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
//e.result fetches you the response against your POST request.
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString()); //i'm getting error here..
}
}
My Screen Design..
Error is..
Thanks
It looks to me like there is a problem with the URI you are using. The error message you posted shows the server returning a "Not found" header. Maybe it just is not quite correct? I did not see the exact URI in the code you posted. string url="myurl"; does not look like this is the url you want to use.
That's also why you can't access the response stream without an exception with this line: MessageBox.Show(e.Result);. There just is no valid response. This is documented here: http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs.result%28v=vs.110%29.aspx.
You can determine if such an error occurred by checking the Error property of UploadStringCompletedEventArgs (http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs%28v=vs.110%29.aspx).
Related
I'm implementing an ASP.NET Core 3.1 app. I have implemented following code to insert record in SQL Server database via EF Core but each time I save data, it inserts two records in PersonRequester and Requester table. I appreciate if anyone suggests me how I can prevent reinserting records.
Requester ap = new Requester();
ap.Address = RequesterViewModel.Requestervm.Address;
ap.RequesterType = RequesterViewModel.Requestervm.RequesterType;
ap.Description = RequesterViewModel.Requestervm.Description;
ap.Name = RequesterViewModel.Requestervm.Name;
var pa = new PersonRequester()
{
BirthCertificateNo = RequesterViewModel.personRequestervm.BirthCertificateNo,
IssuePlace = RequesterViewModel.personRequestervm.IssuePlace,
NationalCode = RequesterViewModel.personRequestervm.NationalCode,
Requester = ap
};
using (var context = new DBContext())
{
context.PersonRequester.Attach(pa);
try
{
context.SaveChanges();
}
catch (Exception e)
{
throw e;
}
}
public partial class Requester
{
public Requester()
{
PersonRequester = new HashSet<PersonRequester>();
}
public int RequesterId { get; set; }
public int RequesterType { get; set; }
public string Address { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
public virtual ICollection<PersonRequester> PersonRequester { get; set; }
}
public partial class PersonRequester
{
public int RequesterId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int RequesterType { get; set; }
public string NationalCode { get; set; }
public string BirthCertificateNo { get; set; }
public string IssuePlace { get; set; }
public virtual Requester Requester { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
}
I'm having problems resolving this error message. I've looked at some other answers on here and changed some things but I still receive this error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Clocker.Models.PeopleLocationForUser]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
This is my class:
namespace Clocker.Models
{
public class PeopleLocationForUser
{
string locationPeople { get; set; }
public users users { get; set; }
}
public class users
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int TATokenValue { get; set; }
}
}
This is the method that errors on the deserialize line:
public static async Task<PeopleLocationForUser> GetPeopleLocationForUser(string UserName, int LocationId)
{
Uri uri = new Uri(URL + "GetPeopleLocationForUser" + "?username=" + UserName + "&locationid=" + LocationId);
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
var content = await response.Content.ReadAsStringAsync();
var test = JsonConvert.DeserializeObject<List<PeopleLocationForUser>>(content);
//return something when it's working
return null;
}
This is the start of the Json data:
{"result":true,"locationPeople":[{"EB_Counter":101,"FirstName":"RSS","LastName":"13.11.1","TATokenValue":"TS_101_1_RSS_SWIPE"},{"EB_Counter":102,"FirstName":"RSS","LastName":"13.11.2","TATokenValue":"TS_102_1_RSS_SWIPE"},{"EB_Counter":93,"FirstName":"RSS","LastName":"13.7.1","TATokenValue":"TS_93_1_RSS_SWIPE"},{"EB_Counter":94,"FirstName":"RSS","LastName":"13.7.10","TATokenValue":"TS_94_1_RSS_SWIPE"},{"EB_Counter":95,"FirstName":"RSS","LastName":"13.8.2","TATokenValue":"TS_95_1_RSS_SWIPE"},{"EB_Counter":99,"FirstName":"RSS","LastName":"13.9.2","TATokenValue":"TS_99_1_RSS_SWIPE"},
This is what my Json data looks like when it arrives:
I hope you can help. The end result is that I'm trying to get this data into a list so I can use it in a Xamarin ListView.
You are receiving list and in the class you are expecting just one instance of user, this is how the class should be:
public class LocationPeople
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string TATokenValue { get; set; }
}
public class RootObject
{
public bool result { get; set; }
public List<LocationPeople> locationPeople { get; set; }
}
var test = JsonConvert.DeserializeObject<RootObject>(content);
I'm using mandrill for managing email service, and it's features of inbound email webhook (HTTP POST) for retrieving the attached image.
Details of Mandrill inbound webhook.
http://help.mandrill.com/forums/21092258-Inbound-Email-Basics
I've tried to get the HTTP inbound webhook but unable to deserialize it into json, and unable to retrieve the attached image.
I've used class and method from following github link.
https://github.com/martydill/mandrill-inbound-classes
after fetching the attached image I need to upload it to imgur website using API,
Am able to upload images to imgur website but i'm facing problem while retrieving attachment from inbound webhook from mandrill.
kindly help me as soon as possible.
I've gone through the class as you stated in github and I've added one more field in the class to get the attachment value from the email.
here is the required class for mandrill webhook.
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Mandrill
{
public class MailEvent
{
[JsonProperty(PropertyName = "ts")]
public string TimeStamp { get; set; }
[JsonProperty(PropertyName = "event")]
public string Event { get; set; }
[JsonProperty(PropertyName = "msg")]
public Message Msg { get; set; }
}
public class Message
{
[JsonProperty(PropertyName = "raw_msg")]
public string RawMessage { get; set; }
[JsonProperty(PropertyName = "headers")]
public Header Header { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "html")]
public string Html { get; set; }
[JsonProperty(PropertyName = "from_email")]
public string FromEmail { get; set; }
[JsonProperty(PropertyName = "from_name")]
public string FromName { get; set; }
// Not sure why Mandrill sends an array of arrays here...
[JsonProperty(PropertyName = "to")]
public string[][] To { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
[JsonProperty(PropertyName = "tags")]
public string[] Tags { get; set; }
[JsonProperty(PropertyName = "sender")]
public string Sender { get; set; }
[JsonProperty(PropertyName = "dkim")]
public DKIM DKIM { get; set; }
[JsonProperty(PropertyName = "spf")]
public SPF SPF { get; set; }
[JsonProperty(PropertyName = "spam_report")]
public SpamReport SpamReport { get; set; }
//[JsonProperty(PropertyName = "attachments")]
//public attachments attachments { get; set; }
[JsonProperty(PropertyName = "attachments")]
public IDictionary<string, IDictionary<string,string>> attachments { get; set; }
}
[JsonDictionary()]
public class Header : Dictionary<string, object>
{
// Need to find a nicer way of doing this... Dictionary<string, object> is kinda dumb
}
public class attachments
{
[JsonProperty(PropertyName = "name ")]
public string name { get; set; }
[JsonProperty(PropertyName = "type ")]
public string type { get; set; }
[JsonProperty(PropertyName = "content ")]
public string content { get; set; }
[JsonProperty(PropertyName = "base64 ")]
public bool base64 { get; set; }
}
public class SpamReport
{
[JsonProperty(PropertyName = "score")]
public decimal Score { get; set; }
[JsonProperty(PropertyName = "matched_rules")]
public SpamRule[] MatchedRules { get; set; }
}
public class SpamRule
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "score")]
public decimal Score { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
}
public class DKIM
{
[JsonProperty(PropertyName = "signed")]
public bool Signed { get; set; }
[JsonProperty(PropertyName = "valid")]
public bool Valid { get; set; }
}
public class SPF
{
[JsonProperty(PropertyName = "result")]
public string Result { get; set; }
[JsonProperty(PropertyName = "detail")]
public string Detail { get; set; }
}
}
and you have to call the imgur api like this.
[HttpPost]
[ValidateInput(false)]
public ActionResult past_mandrill(FormCollection fc)
{
string json = fc["mandrill_events"];
//SqlConnection con = new SqlConnection(WebConfigurationManager.AppSettings[0]);
var events = JsonConvert.DeserializeObject<IEnumerable<Mandrill.MailEvent>>(json);
foreach (var mailEvent in events)
{
//Label2.Text = Label2.Text + mailEvent.Msg.To[0][0] + "<br>";
try
{
foreach (KeyValuePair<string, IDictionary<string, string>> attch in mailEvent.Msg.attachments)
{
//Label2.Text = Label2.Text + attch.Key + "<br>";
byte[] temp;
string albumid = "zBBCDbRcNhE493I"; //use your own album id where you want to store the image.
foreach (KeyValuePair<string, string> attchcnt in attch.Value)
{
//Label2.Text = Label2.Text + attchcnt.Key + " " + attchcnt.Value + "<br>";
if (attchcnt.Key.Equals("content"))
{
using (var w = new WebClient())
{
string base64String = "";
base64String = attchcnt.Value.ToString();
var values = new NameValueCollection
{
{"image", base64String},
{"album", albumid}
};
w.Headers.Add("Authorization", "Client-ID dac37a6b08b4974"); // user your own client-id of imgur website
byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
temp = response;
}
}
}
}
}
catch (Exception e)
{
}
//Label2.Text = mailEvent.Msg.attachments.Values.ToString();
}
return new HttpStatusCodeResult((int)HttpStatusCode.OK);
}
I build a simple model. The reason StartDate is DateTime2 is because previously it gave me an error when i tried to have the DateTime.
public class Auction
{
[Key]
public string Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
[Column(TypeName = "DateTime2")]
[Display(Name = "StartTime")]
public DateTime StartTime { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime EndTime { get; set; }
public int StartPrice { get; set; }
public int CurrentPrice { get; set; }
public string category { get; set; }
public virtual Collection<Bid> Bids { get; private set; }
public int BidCount
{
get { return Bids.Count; }
}
public Auction()
{
Bids = new Collection<Bid>();
}
and i created a create() function in controller.
[HttpPost]
public ActionResult create(Auction auction)
{
var categoryList = new SelectList(new[] { "auto", "elec", "games", "Home" });
ViewBag.categoryList = categoryList;
auction.StartTime= DateTime.Now;
auction.EndTime = DateTime.Now.AddDays(7);
if (ModelState.IsValid)
{
//Save the form
var db = new AuctionsDataContext();
db.Auctions.Add(auction);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I get this error when i try to save changes:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
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.
Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have an UserProfile model
public class UserProfile
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Key]
[Required]
public string EmailAddress { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
[Required]
public string BusinessUnit { get; set; }
[Required]
public string JobRole { get; set; }
public bool IsEnabled { get; set; }
public string Password { get; set; }
}
I want to update only the password field.
This is the code I am trying
if (ModelState.IsValid)
{
var context = new JhaDbContext();
using (JhaDbContext jdc = new JhaDbContext())
{
try
{
jdc.UserProfiles.Attach(userProfile);
userProfile.Password = model.NewPassword;
jdc.SaveChanges();
httpStatus = HttpStatusCode.OK;
}
catch (InvalidOperationException ioe)
{
httpStatus = HttpStatusCode.BadRequest;
}
catch (DbEntityValidationException ev)
{
httpStatus = HttpStatusCode.BadRequest;
}
}
}
I get the DbEntityValidationException on the required fields. Please guide me in solving this.
Regards
Sudheep
I usually would do a
var myEntity = jdc.(tableName).find(userID);
then set
myEntity.Password = "new password";
jdc.Entry(userProfile).State = System.Data.EntityState.Modified;
/* why do you have it as unchanged? */
jdc.saveChanges()