Click here to Skip to main content
15,912,493 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am using Sendgrid API to send and retrieve statistics of mail sent. I want to store the response of API in database.
C#
protected void btnBounces_Click(object sender, EventArgs e)
{
    try
    {
        string url = "https://api.sendgrid.com/api/bounces.get.json";
        GetResult(url);
    }
    catch (Exception ex)
    {
        lblError.Text = ex.Message.ToString();
    }
}
 public void GetResult(string url)
{
    string parameters = "api_user=xxxx&api_key=xxxx&date=1&start_date="+txtStartDate.Text+"&end_date="+txtEndDate.Text;
    // Start the request
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    StreamWriter streamWriter = new StreamWriter(req.GetRequestStream());
    streamWriter.Write(parameters);
    streamWriter.Flush();
    streamWriter.Close();
    // Get the response
    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    StreamReader streamReader = new StreamReader(res.GetResponseStream());
    string result = streamReader.ReadToEnd();
}

The response I will get will be like:

[ { "status": "4.0.0", "created": "2011-09-16 22:02:19", "reason": "Unable to resolve MX host sendgrid.ne", "email": "esting@sendgrid.ne" }, { "status": "4.0.0", "created": "2011-09-19 17:47:15", "reason": "Connection timed out", "email": "rawest@gmail.co" } }

How can i extract value of each of the four fields and store them in table containing four fields?
Posted

1 solution

I got the answer

C#
public class BouncesAndBlocks
{
    public string status { get; set; }
    public string created { get; set; }
    public string email { get; set; }
    public string reason { get; set; }
}
     protected void btnBounces_Click(object sender, EventArgs e)
{
    string url = "https://api.sendgrid.com/api/bounces.get.json";
    string JS = GetResult(url);
    List<bouncesandblocks> res = (List<bouncesandblocks>)JsonConvert.DeserializeObject(JS, typeof(List<bouncesandblocks>));
    foreach (var item in res)
    {
        //Store in database
        lbl.Text = "Date:" + item.created.ToString() + "    Status:" + item.status.ToString() + "     Email:" + item.email.ToString() + "       Message:" + item.reason.ToString() + "";

    }
}
</bouncesandblocks></bouncesandblocks></bouncesandblocks>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900