{"id":6450,"date":"2022-01-05T01:40:37","date_gmt":"2022-01-05T00:40:37","guid":{"rendered":"https:\/\/help.cirrus-shield.com\/?post_type=docs&#038;p=6450"},"modified":"2022-01-11T09:43:01","modified_gmt":"2022-01-11T08:43:01","slug":"source-code-examples","status":"publish","type":"docs","link":"https:\/\/help.cirrus-shield.com\/en\/docs\/developer-guide\/rest-api\/source-code-examples\/","title":{"rendered":"Source code examples"},"content":{"rendered":"\n<p>You will find on this page sample code source that interacts with the Cirrus Shield REST API. We grouped the examples by either tool or programming language. If you don&#8217;t know where to start, start with the Postman collection.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Postman<\/h2>\n\n\n\n<p>Download the following Postman collection, it contains a various set of calls to the REST API of Cirrus Shield : <a href=\"https:\/\/help.cirrus-shield.com\/wp-content\/uploads\/2022\/01\/Cirrus-Shield-REST-API-Samples.postman_collection.json_.zip\">Download<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">.Net<\/h2>\n\n\n\n<p>Here are some samples of using Cirrrus Shield&#8217;s REST API with .Net<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Authenticate and get a token<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>                token = await Http.GetStringAsync(ServiceEndpoint + \"\/AuthToken?Username=\" + username + \"&amp;password=\" + password);\n                token = token.Replace(\"\\\"\", \"\");\n                Console.WriteLine(\"New token : \" + token);<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Select a list of projects<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>        public async Task&lt;List&lt;Project&gt;&gt; GetActiveProjects()\n        {\n            try\n            {\n                List&lt;Project&gt; listOfActiveProjects = new List&lt;Project&gt;();\n                var csProjectsStr = await Http.GetStringAsync(ServiceEndpoint + \"\/Query?authToken=\" + token + \"&amp;selectQuery=Select+Id,Name+from+Project+where+Status='In+Progress'\");\n\n                XElement csProjectsXml = XElement.Parse(csProjectsStr);\n\n                foreach (XElement xe in csProjectsXml.Descendants(\"Project\"))\n                {\n                    Project prj = new Project() { Id = xe.Element(\"Id\").Value, Name = xe.Element(\"Name\").Value };\n                    listOfActiveProjects.Add(prj);\n                }\n                return listOfActiveProjects.OrderBy(o =&gt; o.Name).ToList();\n            }\n            catch (Exception e)\n            {\n                throw e;\n            }\n        }<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Create a record (object : Time) <\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>public async Task&lt;Time&gt; SaveTimeItem(Time timeItem)\n        {\n            try\n            {\n                var xmlData = new XElement(\"Data\", \"\");\n                var xmlTime = new XElement(\"Time\", \"\");\n                xmlTime.Add(new XElement(\"Id\", timeItem.Id));\n                if (string.IsNullOrEmpty(timeItem.Name))\n                    xmlTime.Add(new XElement(\"Name\", timeItem.Name));\n                xmlTime.Add(new XElement(\"OwnerId\", timeItem.OwnerId));\n                xmlTime.Add(new XElement(\"Work_Site\", timeItem.Work_Site));\n                xmlTime.Add(new XElement(\"Date\", timeItem.Date.ToString(\"yyyy-MM-dd\"))); \/\/ DateTime format: yyyy-MM-dd HH-mm-sszz\n                xmlTime.Add(new XElement(\"Description\", timeItem.Description));\n                xmlTime.Add(new XElement(\"Hours\", timeItem.Hours.ToString(System.Globalization.CultureInfo.CurrentCulture)));\n                xmlTime.Add(new XElement(\"Project\", timeItem.ProjectId));\n                xmlTime.Add(new XElement(\"Project_Budget\", timeItem.ProjectBudgetId));\n                xmlTime.Add(new XElement(\"Check_out_Date_Time\", timeItem.CheckOutDateTime.ToString(\"yyyy-MM-dd HH:mm:sszz\")));\n                xmlTime.Add(new XElement(\"Check_in_Date_Time\", timeItem.CheckInDateTime.ToString(\"yyyy-MM-dd HH:mm:sszz\")));\n\n                xmlData.Add(xmlTime);\n\n                var content = new StringContent(\"=\" + HttpUtility.UrlEncode(xmlData.ToString()), Encoding.UTF8, \"application\/x-www-form-urlencoded\"); \/\/ we could also use FormUrlEncodedContent\n                var response = await Http.PostAsync(ServiceEndpoint + \"\/DataAction\/Time?authToken=\" + token + \"&amp;action=upsert&amp;matchingFieldName=id\", content);\n                var responseStatusCode = response.StatusCode;\n                var responseBody = await response.Content.ReadAsStringAsync();\n                var apiResponse = XElement.Parse(responseBody);\n                Console.WriteLine(\" ### Saving Time Item PAYLOAD \\n\" + apiResponse + \"\\n ### \");\n\n                timeItem.Id = apiResponse.Descendants(\"id\").First().Value;\n\n                if (string.IsNullOrEmpty(timeItem.Name))\n                    timeItem.Name = apiResponse.Descendants(\"name\").First().Value;\n\n                if ((responseStatusCode != System.Net.HttpStatusCode.OK) || (apiResponse.Descendants(\"Success\").First().Value == \"False\"))\n                {\n                    Console.WriteLine(\"ErrorMessage : \" + apiResponse.Descendants(\"ErrorMessage\").First().Value);\n                    Console.WriteLine(\"Response Body : \" + responseBody);\n                    throw new Exception (\"There was an issue saving this Time, the server replied with the following information -- Status code: \" + responseStatusCode + \" -- Error Message : \" + apiResponse.Descendants(\"ErrorMessage\").First().Value + \" -- Please contact your administrator\\n\");\n                }\n                return timeItem;\n            }\n            catch (Exception e)\n            {\n                throw e;\n            }\n        }<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Delete a record (object : Time)<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>        public async Task&lt;bool&gt; DeleteTimeItem(Time timeItem)\n        {\n            try\n            {\n                var xmlData = new XElement(\"Data\", \"\");\n                var xmlTime = new XElement(\"Time\", \"\");\n                xmlTime.Add(new XElement(\"Id\", timeItem.Id));\n                xmlData.Add(xmlTime);\n\n                var content = new StringContent(\"=\" + HttpUtility.UrlEncode(xmlData.ToString()), Encoding.UTF8, \"application\/x-www-form-urlencoded\"); \/\/ we could also use FormUrlEncodedContent\n                var response = await Http.PostAsync(ServiceEndpoint + \"\/DataAction\/Time?authToken=\" + token + \"&amp;action=delete&amp;matchingFieldName=id\", content);\n                Console.WriteLine(\"REST API DELETE call (careful with what you do on production data): \" + response);\n\n                var responseStatusCode = response.StatusCode;\n                var responseBody = await response.Content.ReadAsStringAsync();\n\n                if (responseStatusCode != System.Net.HttpStatusCode.OK)\n                {\n                    throw new Exception(\"There was an issue deleting this Time, the server replied with the following error -- Status code: \" + responseStatusCode + \" -- Response body : \" + responseBody + \" -- Please contact your administrator\\n\");\n                }\n\n                return true;\n            }\n            catch (Exception e)\n            {\n                throw e;\n            }\n        }<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">PHP<\/h2>\n\n\n\n<p>Here are some samples of using the REST API with PHP.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Create an Opportunity<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;html&gt;\n\n&lt;head&gt;\n    &lt;title&gt;REST API Test - Create Opportunity&lt;\/title&gt;\n\n&lt;\/head&gt;\n\n&lt;body&gt;\n    &lt;?php\n    function authenticate($username, $password)\n    {\n        $login = &#91;\n            \"Username\" =&gt; $username,\n\n            \"password\" =&gt; $password,\n        ];\n\n        $url = sprintf(\"%s?%s\", \"https:\/\/www.cirrus-shield.net\/RestApi\/AuthToken\", http_build_query($login));\n\n        $client = curl_init();\n\n        curl_setopt($client, CURLOPT_VERBOSE, true);\n        curl_setopt($client, CURLOPT_RETURNTRANSFER, true);\n        curl_setopt($client, CURLOPT_URL, $url);\n\n        $response = curl_exec($client);\n        curl_close($client);\n\n        return $response;\n    }\n\n    function createOpportunity($urlParams, $xmlData)\n    {\n        $url = sprintf(\"%s?%s\", \"http:\/\/www.cirrus-shield.net\/RestApi\/DataAction\/Opportunity\", http_build_query($urlParams));\n        $headers = array(\n            \"Content-Type: application\/x-www-form-urlencoded\",\n            \"charset=utf-8\",\n        );\n\n        $client = curl_init();\n\n        curl_setopt($client, CURLOPT_RETURNTRANSFER, true);\n        curl_setopt($client, CURLOPT_URL, $url);\n        curl_setopt($client, CURLOPT_HTTPHEADER, $headers);\n        curl_setopt($client, CURLOPT_POSTFIELDS, \"=\" . $xmlData);\n        curl_setopt($client, CURLOPT_POST, true);\n        curl_setopt($client, CURLINFO_HEADER_OUT, true);\n        curl_setopt($client, CURLOPT_SSLVERSION, 6);\n\n        $response = curl_exec($client);\n        curl_close($client);\n\n        echo \"&lt;br&gt;&lt;br&gt; HTTP Response content = \";\n        print_r('&lt;pre&gt;');\n        var_dump($response);\n        print_r('&lt;\/pre&gt;');\n\n        echo \"&lt;br&gt;&lt;br&gt; POST content = \";\n\n        return $response;\n    }\n\n    $username = \"mail@mail.com\";\n    $password = \"password\";\n\n    $authToken = authenticate($username, $password);\n    $authToken = str_replace(\"\", \"\", $authToken);\n\n    if ($authToken != '') {\n        $opportunityName = filter_input(INPUT_POST, 'Name', FILTER_SANITIZE_STRING);\n        $opportunityOwner = filter_input(INPUT_POST, 'Owner', FILTER_SANITIZE_STRING);\n        $xmlData =\n            \"&lt;Data&gt;\"\n            . \"&lt;Opportunity&gt;\"\n            . \"&lt;Id&gt;&lt;\/Id&gt;\"\n            . \"&lt;Name&gt;Test3&lt;\/Name&gt;\"\n            . \"&lt;OwnerId&gt;user.email@company.com&lt;\/OwnerId&gt;\"\n            . \"&lt;\/Opportunity&gt;\"\n            . \"&lt;\/Data&gt;\";\n\n        $urlParams = &#91;\"authToken\" =&gt; $authToken, \"action\" =&gt; \"insert\", \"matchingFieldName\" =&gt; \"Id\",];\n\n        $createOpportunity = createOpportunity($urlParams, $xmlData);\n    } else {\n        echo \"&lt;br&gt;Authentication Failed\";\n    }\n    ?&gt;\n&lt;\/body&gt;\n\n&lt;\/html&gt;<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Select a Lead<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;html&gt;\n\n&lt;head&gt;\n\n    &lt;title&gt;REST API Test - Select Lead&lt;\/title&gt;\n\n&lt;\/head&gt;\n\n&lt;body&gt;\n\n    &lt;?php\n    function authenticate($username, $password)\n    {\n        $login = &#91;\n            \"Username\" =&gt; $username,\n            \"password\" =&gt; $password,\n        ];\n\n        $url = sprintf(\"%s?%s\", \"https:\/\/www.cirrus-shield.net\/RestApi\/AuthToken\", http_build_query($login));\n        $client = curl_init();\n\n        curl_setopt($client, CURLOPT_VERBOSE, true);\n        curl_setopt($client, CURLOPT_RETURNTRANSFER, true);\n        curl_setopt($client, CURLOPT_URL, $url);\n\n        $response = curl_exec($client);\n        curl_close($client);\n        return $response;\n    }\n\n    function SelectLead($authToken)\n    {\n        $selectparam = &#91;\n            \"authToken\" =&gt; $authToken,\n            \"selectQuery\" =&gt; \"SELECT Email FROM Lead WHERE Last_Name=Smith\",\n        ];\n\n        $url = sprintf(\"%s?%s\", \"https:\/\/www.cirrus-shield.net\/RestApi\/Query\", http_build_query($selectparam));\n        $client = curl_init();\n\n        curl_setopt($client, CURLOPT_VERBOSE, true);\n        curl_setopt($client, CURLOPT_RETURNTRANSFER, true);\n        curl_setopt($client, CURLOPT_URL, $url);\n\n        $response = curl_exec($client);\n        curl_close($client);\n\n        $array_data = json_decode($response, true);\n        print_r('&lt;pre&gt;');\n        var_dump($response);\n        print_r('&lt;\/pre&gt;');\n        return $response;\n    }\n\n    $username = \"mail@mail.com\";\n    $password = \"password\";\n\n    $authToken = authenticate($username, $password);\n    $authToken = str_replace(\"\", \"\", $authToken);\n\n    if ($authToken != '') {\n        $selectLead = SelectLead($authToken);\n    } else {\n        echo \"&lt;br&gt;Authentication Failed\";\n    } ?&gt;\n\n&lt;\/body&gt;\n\n&lt;\/html&gt;<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Get the ID of the Organization<\/strong><\/li><\/ul>\n\n\n\n<p>You can get the ID of the Organization by sending the following query: &#8220;SELECT Id FROM Organization&#8221;<\/p>\n\n\n\n<p>This Query returns a record containing the ID of the Orgnization.<\/p>\n\n\n\n<p>Sample return data in JSON :<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\u00ab Data \u00bb:{\u00ab Organization \u00bb:&#91;{\u00ab Id \u00bb: \u00bb1453301944234805898\u2033}]}}<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Get the timezone of a user<\/strong><\/li><\/ul>\n\n\n\n<p>You can get the timezone of a user by sending the following query to the REST API :<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT TimeZoneSidKey FROM User WHERE Username=user.name@company.com<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p>This request returns a record that contains the timezone of the user. Here a sample return XML :<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;Data&gt;\n  &lt;User&gt;\n    &lt;TimeZoneSidKey&gt;Europe_Paris&lt;\/TimeZoneSidKey&gt;\n  &lt;\/User&gt;\n&lt;\/Data&gt;<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p> <\/p>\n","protected":false},"author":1,"featured_media":0,"parent":944,"menu_order":9,"comment_status":"open","ping_status":"closed","template":"","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"doc_tag":[],"class_list":["post-6450","docs","type-docs","status-publish","hentry"],"comment_count":0,"_links":{"self":[{"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs\/6450","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs"}],"about":[{"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/types\/docs"}],"author":[{"embeddable":true,"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/comments?post=6450"}],"version-history":[{"count":2,"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs\/6450\/revisions"}],"predecessor-version":[{"id":6453,"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs\/6450\/revisions\/6453"}],"up":[{"embeddable":true,"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs\/944"}],"next":[{"title":"Important Notes","link":"https:\/\/help.cirrus-shield.com\/en\/docs\/developer-guide\/rest-api\/important-notess\/","href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs\/6522"}],"prev":[{"title":"9. SendEmailWithAttachments","link":"https:\/\/help.cirrus-shield.com\/en\/docs\/developer-guide\/rest-api\/sendemailwithattachments\/","href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/docs\/6517"}],"wp:attachment":[{"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/media?parent=6450"}],"wp:term":[{"taxonomy":"doc_tag","embeddable":true,"href":"https:\/\/help.cirrus-shield.com\/en\/wp-json\/wp\/v2\/doc_tag?post=6450"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}