Esempio n. 1
0
        public ActionResult Gig(int id)
        {
            Gig gig = new Gig();
            List <Timeframe> timeframes = new List <Timeframe>();

            System.Diagnostics.Debug.WriteLine("Calling API now...");
            HttpResponseMessage response = ApiUtilities.PerformApiCall <Gig>(id);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                HttpResponseMessage response1 = ApiUtilities.PerformApiCall <Timeframe>();

                if (response1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var timeframeTask = response1.Content.ReadAsAsync(timeframes.GetType());
                    timeframes = (List <Timeframe>)timeframeTask.Result;

                    ViewBag.Timeframes = timeframes;

                    var gigTask = response.Content.ReadAsAsync(gig.GetType());
                    gig = (Gig)gigTask.Result;

                    return(View("GigDetails", gig));
                }
                else
                {
                    return(HttpNotFound());
                }
            }
            else
            {
                return(HttpNotFound());
            }
        }
        /// <summary>
        /// The GET TelematicsNodeV2/{telematicsNodeId}/Fields endpoint retrieves a list of fields associated with the provided telematics node.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public async Task <GetFieldResponse> GetTelematicsNodeFields(int nodeId)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}/fields");

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/{nodeId}/fields", headers);

            GetFieldResponse result = await Api.DeserializeContent <GetFieldResponse>(response);

            return(result);
        }
Esempio n. 3
0
        private async Task <string> getGuid(string template)
        {
            string result = await ApiUtilities.GetByIDforAPI(template);

            var jsondata   = JsonConvert.DeserializeObject <GetApiModel>(result);
            var data       = jsondata.Response.Data[0];
            var attachJson = JsonConvert.DeserializeObject <List <Attachments> >(data["AttachmentsA"]);

            return(attachJson[0].Guid);
        }
        /// <summary>
        /// The GET TelematicsNodeV2/Tree endpoint returns the entire telematics node tree for all of the equipment assets the user can access.
        ///  These assets are formatted in a tree structure with zero to many child nodes for each parent node.
        /// </summary>
        /// <returns></returns>

        public async Task <GetTreeResponse> GetTree()
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, "telematicsnodev2/tree");

            HttpResponseMessage response = await Api.Get("telematicsnodev2/tree", headers);

            GetTreeResponse result = await Api.DeserializeContent <GetTreeResponse>(response);

            return(result);
        }
        /// <summary>
        /// The GET TelematicsNodeV2/Notifications/User endpoint retrieves all enrolled notifications for the current user's telematics nodes.
        /// </summary>
        /// <returns></returns>
        public async Task <UserNotificationResponse> GetNotificationUser()
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/notifications/user");

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/notifications/user", headers);

            UserNotificationResponse result = await Api.DeserializeContent <UserNotificationResponse>(response);

            return(result);
        }
        /// <summary>
        /// The GET TelematicsNodeV2/{trackingCode}/FileStatus endpoint enables a user to obtain the current status of an FDA conversion using the provided trackingCode.
        /// The trackingCode was provided when the user downloaded a file from one of their API equipment connections, specifying to convert the file, or when a file was uploaded, when it required conversion first.
        /// </summary>
        /// <param name="trackingCode"></param>
        /// <returns></returns>
        public async Task <GetFileStatusResponse> GetFileStatus(string trackingCode)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{trackingCode}/filestatus");

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/{trackingCode}/filestatus", headers);

            GetFileStatusResponse result = await Api.DeserializeContent <GetFileStatusResponse>(response);

            return(result);
        }
        /// <summary>
        /// The DELETE TelematicsNodeV2/{telematicsNodeID} endpoint allows a user to delete their connection to an equipment. It only removes the users connection to the endpoint. If the user wishes to get the equipment data back they just need to use the Data Exchange 2 registration workflow and re-register the equipment.
        /// Only root nodes can be deleted. Once a user deletes their connection to the root node they lose access to that entire node tree unless they re-register.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public async Task <EquipmentResponse> DeleteTelematicsNode(int nodeId)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}", "DELETE");

            HttpResponseMessage response = await Api.Delete($"telematicsnodev2/{nodeId}", headers);

            EquipmentResponse result = await Api.DeserializeContent <EquipmentResponse>(response);

            return(result);
        }
        /// <summary>
        /// The GET TelematicsNodeV2/Notifications/{nodeId} endpoint retrieves all enrolled notifications for a single telematics node for all api partner users.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public async Task <NodeNotificationResponse> GetNotificationForApiPartnerByNode(int nodeId)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/notifications/{nodeId}");

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/notifications/{nodeId}", headers);

            NodeNotificationResponse result = await Api.DeserializeContent <NodeNotificationResponse>(response);

            return(result);
        }
        /// <summary>
        /// The GET TelematicsNodeV2/{telematicsNodeID}/PlantingSummary/{trackingCode}/Status endpoint will allow the user to check
        /// the status of their planting summary request using the tracking code they received as a result of their previous Planting Summary request.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="trackingCode"></param>
        /// <returns></returns>
        public async Task <GetPlantingSummaryStatusResponse> GetTelematicsNodePlantingSummaryStatus(int nodeId, string trackingCode)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}/plantingsummary/{trackingCode}/status");

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/{nodeId}/plantingsummary/{trackingCode}/status", headers);

            GetPlantingSummaryStatusResponse result = await Api.DeserializeContent <GetPlantingSummaryStatusResponse>(response);

            return(result);
        }
        /// <summary>
        /// The POST TelematicsNodeV2/{telematicsNodeID}/Files (Send File) endpoint uploads one file to the specified API equipment node.
        /// If the file is in a format not accepted by the equipment, and the user has permissions for FDA conversions,
        /// a request is sent to the FDA conversion service to convert the file before it is uploaded.
        /// This endpoint returns a status indicating successful and unsuccessful uploads and pending conversions with a tracking code.
        /// The trackingCode can be used in the GET TelematicsNodeV2/{trackingCode}/FileStatus endpoint to get the status of the FDA conversion.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="fileToSend"></param>
        /// <returns></returns>

        public async Task <PostSendFileResponse> PostSendFiles(int nodeId, FileInfo fileToSend)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}/files", "POST");

            MultipartFormDataContent content = new MultipartFormDataContent();
            HttpContent bytes = new ByteArrayContent(File.ReadAllBytes(fileToSend.FullName));

            content.Add(bytes, "fileToSend", fileToSend.Name);
            HttpResponseMessage response = await Api.Post($"telematicsnodev2/{nodeId}/files", headers, content);

            return(await Api.DeserializeContent <PostSendFileResponse>(response));
        }
Esempio n. 11
0
        public async Task <ActionResult> Pdf(string template, string id)
        {
            string result = await ApiUtilities.GetByIDforAPI(id);

            var jsondata = JsonConvert.DeserializeObject <GetApiModel>(result);
            var data     = jsondata.Response.Data[0];

            data.Add("PrintDate", DateTime.Now.ToLongDateString());
            var pdf = Reports.CreatePdfResume(data);

            return(new FileStreamResult(pdf, "application/pdf"));
        }
        /// <summary>
        /// The GET TelematicsNodeV2/Equipment/Register endpoint retrieves a url that redirects the user to the Data Exchange 2.0 Registration page.
        ///  There the user may register with the enabled equipment manufacturers.
        /// </summary>
        /// <returns></returns>

        public async Task <GetEquipmentRegisterResponse> GetEquipmentRegister()
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, "telematicsnodev2/equipment/register");

            HttpResponseMessage response = await Api.Get("telematicsnodev2/equipment/register", headers);

            GetEquipmentRegisterResponse result = await Api.DeserializeContent <GetEquipmentRegisterResponse>(response);

            System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\IExplore.exe", result.Url);

            return(result);
        }
        /// <summary>
        /// The POST /TelematicsNodeV2/Enrollment/File endpoint enrolls a list of Telematics Node(s) which have notifications for File Conversion and/or S3 Storage.
        /// Api partners with FDA permissions can include an FDA Configuration in the request to have the notification converted to a specified output preference
        /// </summary>
        /// <param name="fileRequest"></param>
        /// <returns></returns>
        public async Task <EnrollFilesResponse> PostNotificationFile(FileRequest fileRequest)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/notifications/file", "POST");

            string json = JsonConvert.SerializeObject(fileRequest);

            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await Api.Post($"telematicsnodev2/notifications/file", headers, content);

            EnrollFilesResponse result = await Api.DeserializeContent <EnrollFilesResponse>(response);

            return(result);
        }
        /// <summary>
        /// The POST TelematicsNodeV2/{telematicsNodeID}/PlantingSummary endpoint will
        /// allow the user to request a summary of their planting information based on a set of passed parameters.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="postPlantingSummaryRequest"></param>
        /// <returns></returns>
        public async Task <PostPlantingSummaryResponse> PostTelematicsNodePlantingSummary(int nodeId, PostPlantingSummaryRequest postPlantingSummaryRequest)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}/plantingsummary", "POST");

            string json = JsonConvert.SerializeObject(postPlantingSummaryRequest);

            HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await Api.Post($"telematicsnodev2/{nodeId}/plantingsummary", headers, content);

            PostPlantingSummaryResponse result = await Api.DeserializeContent <PostPlantingSummaryResponse>(response);

            return(result);
        }
        /// <summary>
        /// The POST TelematicsNodeV2/Notifications/{telematicsNodeID}/Post endpoint enrolls the Telematics Node for POST notifications, notifications will be sent to the designated POST URI.
        /// Api partners with FDA permissions can include an FDA Configuration in the request to have the notification converted to a specified output preference.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="postNotificationRequest"></param>
        /// <returns></returns>
        public async Task <NodeNotificationResponse> EnrollPostNotification(int nodeId, PostRequest postNotificationRequest)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/notifications/{nodeId}/post", "POST");

            string json = JsonConvert.SerializeObject(postNotificationRequest);

            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await Api.Post($"telematicsnodev2/notifications/{nodeId}/Post", headers, content);

            NodeNotificationResponse result = await Api.DeserializeContent <NodeNotificationResponse>(response);

            return(result);
        }
        /// <summary>
        /// * The GET TelematicsNodeV2/{telematicsNodeID}/Files/{fileId} (Download File) endpoint downloads the specified file from the API equipment.
        /// The user can optionally request that the file be converted by the FDA service, if the user has FDA access.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="fileId"></param>
        public async Task <FileInfo> GetDownloadFilesWithoutConversion(int nodeId, string fileId)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}/files/{fileId}");

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/{nodeId}/files/{fileId}", headers);

            string tempFile = Path.Combine(Path.GetTempPath(), fileId + ".zip");

            using (var fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
            {
                Stream file = await response.Content.ReadAsStreamAsync();

                file.CopyTo(fileStream);
            }
            return(new FileInfo(tempFile));
        }
        /// <summary>
        /// The GET TelematicsNodeV2/{telematicsNodeID}/Files/{fileId} (Download File) endpoint downloads the specified file from the API equipment.
        /// The user can optionally request that the file be converted by the FDA service, if the user has FDA access.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="fileId"></param>
        /// <param name="callbackUrl"></param>
        /// <param name="conversionType"></param>
        /// <returns></returns>

        public async Task <GetFileDownloadResponse> GetDownloadFilesWithConversion(int nodeId, string fileId, string callbackUrl, string conversionType)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/{nodeId}/files/{fileId}");

            Dictionary <string, string> queryParams = new Dictionary <string, string>();

            queryParams.Add("callBackUrl", callbackUrl);

            queryParams.Add("conversionType", conversionType);

            HttpResponseMessage response = await Api.Get($"telematicsnodev2/{nodeId}/files/{fileId}", headers, queryParams);

            GetFileDownloadResponse result = await Api.DeserializeContent <GetFileDownloadResponse>(response);

            return(result);
        }
Esempio n. 18
0
        public ActionResult Categories()
        {
            List <Category>     categories = new List <Category>();
            HttpResponseMessage response   = ApiUtilities.PerformApiCall <Category>();

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var gigTask = response.Content.ReadAsAsync(categories.GetType());
                categories = (List <Category>)gigTask.Result;
                return(View(categories));
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Error...");
                return(HttpNotFound());
            }
        }
Esempio n. 19
0
        public ActionResult Category(int id)
        {
            Category            category = new Category();
            HttpResponseMessage response = ApiUtilities.PerformApiCall <Category>(id);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var gigTask = response.Content.ReadAsAsync(category.GetType());
                category = (Category)gigTask.Result;
                return(View("CategoryDetails", category));
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Error...");
                return(HttpNotFound());
            }
        }
Esempio n. 20
0
        public ActionResult MyGigs()
        {
            Instructor instructor = new Instructor();

            List <Gig>          gigs     = new List <Gig>();
            HttpResponseMessage response = ApiUtilities.PerformApiCall <Instructor>(0);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var gigTask = response.Content.ReadAsAsync(instructor.GetType());
                instructor = (Instructor)gigTask.Result;
                return(View(instructor.Gigs));
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Error...");
                return(HttpNotFound());
            }
        }
Esempio n. 21
0
        public ActionResult MySchedules()
        {
            List <Schedule> schedules = new List <Schedule>();

            System.Diagnostics.Debug.WriteLine("Calling API now...");
            HttpResponseMessage response = ApiUtilities.PerformApiCall <Schedule>();

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var gigTask = response.Content.ReadAsAsync(schedules.GetType());
                schedules = (List <Schedule>)gigTask.Result;

                return(View("Schedules", schedules));
            }
            else
            {
                return(HttpNotFound());
            }
        }
Esempio n. 22
0
        public void Save(Benday.EasyAuthDemo.Api.DomainModels.Person saveThis)
        {
            if (saveThis == null)
            {
                throw new ArgumentNullException("saveThis", "saveThis is null.");
            }

            if (_ValidatorInstance.IsValid(saveThis) == false)
            {
                ApiUtilities.ThrowValidationException(saveThis, "Item is invalid.");
            }
            else
            {
                Benday.EasyAuthDemo.Api.DataAccess.Entities.PersonEntity toValue;

                if (saveThis.Id == 0)
                {
                    toValue = new Benday.EasyAuthDemo.Api.DataAccess.Entities.PersonEntity();
                }
                else
                {
                    toValue = _Repository.GetById(saveThis.Id);

                    if (toValue == null)
                    {
                        ApiUtilities.ThrowUnknownObjectException("Person", saveThis.Id);
                    }
                }

                PopulateAuditFieldsBeforeSave(saveThis);



                _Adapter.Adapt(saveThis, toValue);

                _Repository.Save(toValue);

                PopulateFieldsFromEntityAfterSave(toValue, saveThis);
            }
        }
Esempio n. 23
0
        public async Task <ActionResult> Excel(string template, string id)
        {
            string guid = await getGuid(template);

            string result = await ApiUtilities.GetByIDforAPI(id);

            var jsondata = JsonConvert.DeserializeObject <GetApiModel>(result);

            if (jsondata.StatusCode == 200)
            {
                var data = jsondata.Response.Data[0];
                data.Add("PrintDate", DateTime.Now.ToLongDateString());
                var xlsx = Reports.CreateXls(guid, data);

                //var log = new SysLogModel();
                //log.Finish();

                return(File(xlsx, "application / vnd.openxmlformats - officedocument.spreadsheetml.sheet", "result.xlsx"));
            }
            else
            {
                return(View());
            }
        }
Esempio n. 24
0
        public HttpResponseMessage Get()
        {
            string userName = ApiUtilities.GetUserName(User.Identity.Name);

            return(Request.CreateResponse(HttpStatusCode.OK, userName));
        }
Esempio n. 25
0
        public HttpResponseMessage Post([FromBody] TokenRequest tokenRequest)
        {
            // Impersonate User is only allowed if configured and NOT in PROD
            string userName = ApiUtilities.GetUserName(User.Identity.Name);

            if (!"PROD".Equals(ENVIRONMENT_NAME) && IS_IMPERSONATION_ALLOWED.Equals("true", StringComparison.CurrentCultureIgnoreCase))
            {
                if (!string.IsNullOrEmpty(tokenRequest?.ImpersonatedUser))
                {
                    userName = tokenRequest.ImpersonatedUser;
                }
            }

            Dictionary <string, string> clientSecret = new Dictionary <string, string>()
            {
                { "Machine", Environment.MachineName.ToUpper() },
                { "Environment", ENVIRONMENT_NAME }
            };

            // Request ID is used to verify the response matches the request
            string requestId = Math.Floor((double)(1 + (new Random()).Next()) * 0x10000).ToString();

            var request = WebRequest.Create(TOKEN_ENDPOINT) as HttpWebRequest;

            request.Method          = "POST";
            request.ContentType     = "application/json";
            request.CookieContainer = new CookieContainer();
            request.Accept          = "*/*";
            request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
            request.Headers.Add("X-Request-ID", requestId);
            request.Headers.Add("Client-Secret", clientSecret.EncryptJson <AesManaged>(ENVIRONMENT_NAME));
            string authCredentials = $"grant_type=password&username={userName}";

            byte[] bytes = Encoding.UTF8.GetBytes(authCredentials);
            request.ContentLength = bytes.Length;

            try
            {
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
            }
            catch (WebException)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, TOKEN_ENDPOINT));
            }

            try
            {
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    // Verify Request ID
                    if (!requestId.Equals(response.Headers["X-Request-ID"]))
                    {
                        return(Request.CreateResponse(HttpStatusCode.ExpectationFailed, "Server returned a Request ID mismatch!"));
                    }

                    using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        string responseJson = reader.ReadToEnd();
                        if (string.IsNullOrEmpty(responseJson))
                        {
                            return(Request.CreateResponse(HttpStatusCode.ExpectationFailed, "Not Authorized!"));
                        }
                        var obj   = JsonConvert.DeserializeObject <ExpandoObject>(responseJson) as IDictionary <string, Object>;
                        var links = ConfigurationManager.AppSettings.AllKeys
                                    .ToDictionary(k => k, v => ConfigurationManager.AppSettings[v]).Where(k => k.Key.StartsWith("LINK_"));
                        foreach (KeyValuePair <string, string> link in links)
                        {
                            obj.Add(link.Key, link.Value);
                        }
                        obj.Add("impersonation", IS_IMPERSONATION_ALLOWED);
                        obj.Add("production", PRODUCTION);
                        responseJson = JsonConvert.SerializeObject(obj);

                        object responseObject = JsonConvert.DeserializeObject(responseJson);
                        return(Request.CreateResponse(HttpStatusCode.OK, responseObject));
                    }
                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string error = reader.ReadToEnd();
                            return(new HttpResponseMessage(errorResponse.StatusCode)
                            {
                                Content = new StringContent(error)
                            });
                        }
                    }
                }
            }

            return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Authorization Failed!"));
        }