{"_id":"56a26500f4f3410d008a8436","category":{"_id":"56b200c0f48f270d00e0de6f","version":"568fce2b04440a1700e4cb4a","__v":9,"pages":["56b201173b6f690d00bdb68e","56b20ef3bf040b0d00588be4","56b214097ae4550d00062928","56b21502bf040b0d00588bea","56c1ffb1d07cc50d005e5f5e","56c74a05af5bc40d00d6bb5b","56d412b38001e30b00896dd5","56d85fc1c83c5f0b00d288a2","56d866f4a957fb1500765a40"],"project":"568fce2a04440a1700e4cb47","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2016-02-03T13:29:36.476Z","from_sync":false,"order":1,"slug":"c","title":"C# Quickstarts"},"project":"568fce2a04440a1700e4cb47","version":{"_id":"568fce2b04440a1700e4cb4a","project":"568fce2a04440a1700e4cb47","__v":20,"createdAt":"2016-01-08T14:56:43.101Z","releaseDate":"2016-01-08T14:56:43.101Z","categories":["568fce2b04440a1700e4cb4b","568fd1b8b700ce0d002f4b1c","568fd23804440a1700e4cb5b","568fd2444719c119002ce5d8","568ff21204440a1700e4cbc1","5693732c8aa8040d009f2c28","5693738393445b0d00abdad0","5693740093445b0d00abdad1","56937445974aaa0d001ca699","5693b82173f48f0d0075c90d","5694c4cd1005590d0062cb25","569f854466a5640d00efa54c","56a264cdd15dd70d008d825b","56aa56bf318e6c1700a19ddb","56b0e6347ae4550d000627bd","56b200c0f48f270d00e0de6f","56b200c6f48f270d00e0de70","56b22a9665ddf50d0076ba40","56e92ef71996862200fd7f42","574d6577fb835c0e00ca316a"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.0.0","version":"1.0"},"__v":45,"user":"55116f88e2990b0d00fb0552","parentDoc":null,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-01-22T17:21:04.927Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":0,"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"Full source for these quickstarts can be downloaded from http://download.dynmark.com/Files/API/Quickstart/CS.zip\"\n}\n[/block]\n##Prerequisites\nYou'll need a Dynmark account to be able to send messages. You can use a trial account to send a limited number of free messages for testing.\n\n##Hello World via SMS\nWe're going to create a simple MVC based web application that sends a hello message when the user enters their personal details. We'll make use of the RestSharp library to handle the REST call to the Dynmark API.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var client = new RestClient(\\\"https://services.dynmark.com/webapi/message/send\\\");\\nclient.Authenticator = new HttpBasicAuthenticator(username, password);\\nclient.Timeout = 130000;\\n\\nvar body = new[]\\n{\\n\\tnew\\n\\t{\\n\\t\\tfrom = \\\"Example\\\",\\n\\t\\tto = phoneNumber,\\n\\t\\tbody = \\\"Hello, this is a test message\\\"\\n\\t}\\n};\\n\\nvar request = new RestRequest();\\nrequest.AddJsonBody(body);\\n\\nvar response = client.Post(request);\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\nLets look at the details:\n1. You'll need your Dynmark username and password to authenticate calls.\n2. We use the [RestSharp](http://restsharp.org/) library to send our REST calls to the Dynmark API. You could alternatively use [WebRequest](https://msdn.microsoft.com/en-us/library/456dfw4f%28v=vs.110%29.aspx) or, if you're developing on .NET 4.5 or later, [HttpClient](https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx).\n3. We define a message request containing the bare minimum details to send an SMS.\n\nUsers often make mistakes entering their details. Let's add some code to check the response from the API for validation failures:\n\n1. Define a new class at the top of our cshtml file that will parse the response from the API\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \":::at:::functions {\\n    public class MessageResponse\\n    {\\n        public string To { get; set; }\\n        public bool Successful { get; set; }\\n        public List<ApiValidationFailure> ValidationFailures { get; set; }\\n    }\\n\\n    public class ApiValidationFailure\\n    {\\n        public string Property { get; set; }\\n        public string FailureCode { get; set; }\\n        public string Details { get; set; }\\n    }\\n} \",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\n2. Now we change the Post method to return typed results and add code to check for HTTP 200 OK. This shows that the API call was in a valid format.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    var response = client.Post<List<MessageResponse>>(request);\\n\\n    if (response.StatusCode == HttpStatusCode.OK)\\n    {\\n        if (response.Data[0].Successful)\\n        {\\n            <span>We sent you a message!</span>\\n        }\\n        else\\n        {\\n            <span class=\\\"userError\\\">Sorry, we couldn't sent you a message.</span>\\n            if (response.Data[0].ValidationFailures.Any(r => r.FailureCode == \\\"ToInvalid\\\"))\\n            {\\n                <span class=\\\"userError\\\"> Your phone number doesn't look like a valid number.</span>\\n            }\\n        }\\n    }\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\n3. We should also check for HTTP 401 Unauthorised to ensure we're using the right credentials, and since we're using an anonymous type to build the request, HTTP 400 Bad Request to ensure we've submitted a request with no typos or incorrect property names.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    else if (response.StatusCode == HttpStatusCode.BadRequest)\\n    {\\n        throw new ArgumentException(\\\"Invalid credentials\\\");\\n    }\\n\\t\\telse if (response.StatusCode == HttpStatusCode.BadRequest)\\n    {\\n        throw new ArgumentException(\\\"Bad request format\\\");\\n    }\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]\n4. This has become large enough to warrant a wrapping in a helper function:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"@functions {\\n\\t\\t// set our username and password\\n    string username = \\\"@Username@\\\";\\n    string password = \\\"@Password@\\\";\\n\\n  \\tpublic class MessageResponse\\n    {\\n        public string To { get; set; }\\n        public bool Successful { get; set; }\\n        public List<ApiValidationFailure> ValidationFailures { get; set; }\\n    }\\n\\n    public class ApiValidationFailure\\n    {\\n        public string Property { get; set; }\\n        public string FailureCode { get; set; }\\n        public string Details { get; set; }\\n    }\\n\\n\\t\\tList<MessageResponse> SendMessage(string phoneNumber)\\n    {\\n        // instantiate a new HttpClient\\n        var client = new RestClient(\\\"https://services.dynmark.com/webapi/message/send\\\");\\n        client.Authenticator = new HttpBasicAuthenticator(username, password);\\n        client.Timeout = 130000;\\n\\n        var sendBody = new[]\\n        {\\n                    new\\n                    {\\n                        from = \\\"Example\\\",\\n                        to = phoneNumber,\\n                        body = \\\"Hello, this is a test message\\\"\\n                    }\\n                };\\n\\n        var request = new RestRequest();\\n        request.AddJsonBody(sendBody);\\n\\n        // Send a new outgoing SMS by POSTing to the Message resource\\n        var response = client.Post<List<MessageResponse>>(request);\\n\\n        if (response.StatusCode == HttpStatusCode.Accepted)\\n        {\\n            return response.Data;\\n        }\\n        else if (response.StatusCode == HttpStatusCode.Unauthorized)\\n        {\\n            throw new ArgumentException(\\\"Invalid credentials\\\");\\n        }\\n        else if (response.StatusCode == HttpStatusCode.BadRequest)\\n        {\\n            throw new ArgumentException(\\\"Bad request format\\\");\\n        }\\n\\n        throw new ArgumentException(\\\"Non success response\\\");\\n    }\",\n      \"language\": \"csharp\"\n    }\n  ]\n}\n[/block]","excerpt":"Sending text messages via the REST API","slug":"qs-cs-send-sms-messages","type":"basic","title":"Send SMS Messages"}

Send SMS Messages

Sending text messages via the REST API

[block:callout] { "type": "info", "body": "Full source for these quickstarts can be downloaded from http://download.dynmark.com/Files/API/Quickstart/CS.zip" } [/block] ##Prerequisites You'll need a Dynmark account to be able to send messages. You can use a trial account to send a limited number of free messages for testing. ##Hello World via SMS We're going to create a simple MVC based web application that sends a hello message when the user enters their personal details. We'll make use of the RestSharp library to handle the REST call to the Dynmark API. [block:code] { "codes": [ { "code": "var client = new RestClient(\"https://services.dynmark.com/webapi/message/send\");\nclient.Authenticator = new HttpBasicAuthenticator(username, password);\nclient.Timeout = 130000;\n\nvar body = new[]\n{\n\tnew\n\t{\n\t\tfrom = \"Example\",\n\t\tto = phoneNumber,\n\t\tbody = \"Hello, this is a test message\"\n\t}\n};\n\nvar request = new RestRequest();\nrequest.AddJsonBody(body);\n\nvar response = client.Post(request);", "language": "csharp" } ] } [/block] Lets look at the details: 1. You'll need your Dynmark username and password to authenticate calls. 2. We use the [RestSharp](http://restsharp.org/) library to send our REST calls to the Dynmark API. You could alternatively use [WebRequest](https://msdn.microsoft.com/en-us/library/456dfw4f%28v=vs.110%29.aspx) or, if you're developing on .NET 4.5 or later, [HttpClient](https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx). 3. We define a message request containing the bare minimum details to send an SMS. Users often make mistakes entering their details. Let's add some code to check the response from the API for validation failures: 1. Define a new class at the top of our cshtml file that will parse the response from the API [block:code] { "codes": [ { "code": "@functions {\n public class MessageResponse\n {\n public string To { get; set; }\n public bool Successful { get; set; }\n public List<ApiValidationFailure> ValidationFailures { get; set; }\n }\n\n public class ApiValidationFailure\n {\n public string Property { get; set; }\n public string FailureCode { get; set; }\n public string Details { get; set; }\n }\n} ", "language": "csharp" } ] } [/block] 2. Now we change the Post method to return typed results and add code to check for HTTP 200 OK. This shows that the API call was in a valid format. [block:code] { "codes": [ { "code": " var response = client.Post<List<MessageResponse>>(request);\n\n if (response.StatusCode == HttpStatusCode.OK)\n {\n if (response.Data[0].Successful)\n {\n <span>We sent you a message!</span>\n }\n else\n {\n <span class=\"userError\">Sorry, we couldn't sent you a message.</span>\n if (response.Data[0].ValidationFailures.Any(r => r.FailureCode == \"ToInvalid\"))\n {\n <span class=\"userError\"> Your phone number doesn't look like a valid number.</span>\n }\n }\n }", "language": "csharp" } ] } [/block] 3. We should also check for HTTP 401 Unauthorised to ensure we're using the right credentials, and since we're using an anonymous type to build the request, HTTP 400 Bad Request to ensure we've submitted a request with no typos or incorrect property names. [block:code] { "codes": [ { "code": " else if (response.StatusCode == HttpStatusCode.BadRequest)\n {\n throw new ArgumentException(\"Invalid credentials\");\n }\n\t\telse if (response.StatusCode == HttpStatusCode.BadRequest)\n {\n throw new ArgumentException(\"Bad request format\");\n }", "language": "csharp" } ] } [/block] 4. This has become large enough to warrant a wrapping in a helper function: [block:code] { "codes": [ { "code": "@functions {\n\t\t// set our username and password\n string username = \"@Username@\";\n string password = \"@Password@\";\n\n \tpublic class MessageResponse\n {\n public string To { get; set; }\n public bool Successful { get; set; }\n public List<ApiValidationFailure> ValidationFailures { get; set; }\n }\n\n public class ApiValidationFailure\n {\n public string Property { get; set; }\n public string FailureCode { get; set; }\n public string Details { get; set; }\n }\n\n\t\tList<MessageResponse> SendMessage(string phoneNumber)\n {\n // instantiate a new HttpClient\n var client = new RestClient(\"https://services.dynmark.com/webapi/message/send\");\n client.Authenticator = new HttpBasicAuthenticator(username, password);\n client.Timeout = 130000;\n\n var sendBody = new[]\n {\n new\n {\n from = \"Example\",\n to = phoneNumber,\n body = \"Hello, this is a test message\"\n }\n };\n\n var request = new RestRequest();\n request.AddJsonBody(sendBody);\n\n // Send a new outgoing SMS by POSTing to the Message resource\n var response = client.Post<List<MessageResponse>>(request);\n\n if (response.StatusCode == HttpStatusCode.Accepted)\n {\n return response.Data;\n }\n else if (response.StatusCode == HttpStatusCode.Unauthorized)\n {\n throw new ArgumentException(\"Invalid credentials\");\n }\n else if (response.StatusCode == HttpStatusCode.BadRequest)\n {\n throw new ArgumentException(\"Bad request format\");\n }\n\n throw new ArgumentException(\"Non success response\");\n }", "language": "csharp" } ] } [/block]