Beispiel #1
0
        protected virtual WebApiResponse <bool> GetWebApiResponse(bool responseValue, HttpResponseMessage response)
        {
            var responseMessage = CreateResponseMessage(response);
            var errors          = GetContentErrors(response);

            return(WebApiResponse <bool> .Create(responseValue, responseMessage, errors));
        }
Beispiel #2
0
        public async Task GenericHttpRequest()
        {
            string testFilePath = Path.Combine(BaseFilePath, "RestTest\\MyTest");
            //string testOutputFilePath = Path.Combine(BaseFilePath, "RestTest\\MyTest\\Output");
            string testOutputFilePath = "c:\\temp";
            string error = null;

            GenericHTTPTester GenericHTTPTester = new GenericHTTPTester(base.xUnitTestConfig.UnitTestConfig.BaseHttpsURL);

            GenericHTTPTester.Load(testFilePath, out error);
            Assert.Null(error);

            WebApiResponse WebApiResponse = await GenericHTTPTester.Dispatch();

            Assert.True((GenericHTTPTester.ResponseDataReceived.StatusCode == GenericHTTPTester.ResponseDataExpected.StatusCode), "Status code mismatch");


            //this is optional
            GenericHTTPTester.Persist(testOutputFilePath, out error);
            Assert.Null(error);

            HeadersTestResult headersTestResult = GenericHTTPTester.CompareHeaders(out error);

            Assert.Null(error);
            Assert.True((headersTestResult.headersWrongValue.Count == 0), "Wrong header content detected.");
            Assert.True((headersTestResult.headersNotFoundInRequest.Count == 0), "Response missed some headers.");

            //string result1 = GenericHTTPTester.CompareBody(out error); this is used in json objects
            string result2 = GenericHTTPTester.CompareArray(out error);

            Assert.Null(error);
            Assert.True((result2 == ""), result2);
        }
        public ActionResult Delete(int id)
        {
            ServiceRepository   serviceObj = new ServiceRepository();
            HttpResponseMessage response   = serviceObj.DeleteResponse("api/GazettedHolidays/DeleteGH?id=" + id.ToString());

            response.EnsureSuccessStatusCode();

            if (response.IsSuccessStatusCode)
            {
                string         jsonResponse = response.Content.ReadAsStringAsync().Result;
                var            JsonLinq     = JObject.Parse(jsonResponse);
                WebApiResponse getreponse   = new WebApiResponse();
                getreponse.Status  = Convert.ToBoolean(JsonLinq["Status"]);
                getreponse.Message = JsonLinq["Message"].ToString();
                getreponse.Data    = JsonLinq["Data"].ToString();

                if (getreponse.Status == true)
                {
                    TempData["DataStatus"] = getreponse.Message;
                }
                else
                {
                    TempData["DataStatus"] = getreponse.Message;
                }
            }
            UtilityClass.ActivityMonitor(Convert.ToInt32(Session["UserID"]), Session.SessionID, Request.UserHostAddress.ToString(), new Guid().ToString(), JsonConvert.SerializeObject(id), this.RouteData.Values["action"].ToString(), Request.RawUrl.ToString());
            return(RedirectToAction("GazettedHoliday"));
        }
Beispiel #4
0
 private void TestHttpResults <T>(WebApiResponse <T> response)
 {
     Assert.IsTrue(response.ResponseMessage.IsSuccessStatusCode);
     Assert.AreEqual("OK", response.ResponseMessage.ReasonPhrase);
     Assert.AreEqual(200, response.ResponseMessage.StatusCode);
     Assert.AreEqual(0, response.Errors.Count());
 }
    /// <summary>
    ///To Update the device Lock Status (Lock/unlock)
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage updateDeviceLockStatus(DeviceLock DL)
    {
        ar = new WebApiResponse();
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + DL.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                {
                    dr.Close();
                }

                qry = "delete from MDM_PushNotification where DeviceID='" + DL.uuid + "'";
                string qry1 = "update MDM_DeviceMaster set";
                if (DL.status == false)//successfully unlocked
                {
                    // SendSmsOrMail(DL.uuid); //to inform that device is unlocked
                    qry  += " and Command ='Unlocked'";
                    qry1 += " Status=2 ";
                }
                else if (DL.status == true)//successfully locked
                {
                    // SendLockDeviceDetails(DL.uuid);//To send unlock details of locked device by sms/email
                    qry  += " and Command ='Locked'";
                    qry1 += " Status=1 ";
                }
                rcnt        = databaseHelper.ExecuteQuery(qry);
                qry1       += " where DeviceID='" + DL.uuid + "'";
                rcnt        = databaseHelper.ExecuteQuery(qry1);
                ar.response = true;
                response    = Request.CreateResponse(HttpStatusCode.Created, ar);
                return(response);
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response  = false;
                response     = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return(response);
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);
            ar.errorCode = "Device Lock Status Failed";
            ar.response  = false;
            response     = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
            {
                dr.Close();
            }
        }
        return(response);
    }
Beispiel #6
0
        public async Task <WebApiResponse> OsztalyTorol(Osztalyok req)
        {
            InitHttpClient();
            var resp = new WebApiResponse();

            try
            {
                var endpoint = string.Format(baseUrlApi + "/Osztalyok/OsztalyTorol");



                var json = JsonConvert.SerializeObject(req);
                var r    = await HttpClient.PostAsync(endpoint, new StringContent(json, Encoding.UTF8, "application/json"));

                if (r.IsSuccessStatusCode)
                {
                    var contents = await r.Content.ReadAsStringAsync();

                    var returnValue = JsonConvert.DeserializeObject(contents);
                    resp = JsonConvert.DeserializeObject <WebApiResponse>(returnValue.ToString());
                }
                else
                {
                    resp.ErrorCode    = ERROR_NET;
                    resp.ErrorMessage = r.StatusCode.ToString();
                }
                return(resp);
            }
            catch (Exception ex)
            {
                resp.ErrorCode    = ERROR_GENERIC;
                resp.ErrorMessage = ex.ToString();
                return(resp);
            }
        }
    public string Test(WebApiResponse Name)
    {

        serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        sl_post = serializer.Deserialize<SortedList<string, string>>(Name.errorCode);
        return Name.errorCode;
    }
Beispiel #8
0
        /// <summary>
        /// 调用1688接口方法
        /// </summary>
        /// <param name="secret">授权信息</param>
        /// <param name="funName">方法名eg:cn.alibaba.open/caigou.api.account.listSubAcccounts</param>
        /// <param name="urlParams">api参数集合</param>
        /// <returns></returns>
        public string doPost()
        {
            if (!_UseWebApiClient)
            {
                return(Post());
            }
            JObject ret;

            //获取签名
            string sign = GetSignature();
            //拼装api参数
            ParameterCollection ps     = GetUrlParmCollection(sign);
            WebApiClient        client = GetWebApiClient();
            WebApiResponse      resp   = client.Post(FunName + "/" + Secret.AppKey, null, ps);

            if (resp.IsError)
            {
                throw new Exception(string.Format("调用1688接口{0}错误:{1}", FunName, JsonConvert.SerializeObject(UrlParams)));
            }
            ret = JsonConvert.DeserializeObject <JObject>(resp.Content);
            if (ret == null)
            {
                throw new Exception(string.Format("调用1688接口{0}返回空对象{1},返回内容{2}", FunName, JsonConvert.SerializeObject(UrlParams), JsonConvert.SerializeObject(resp)));
            }
            return(ret.ToString());
        }
        public String OrarendHozzaad([FromBody] dynamic value)
        {
            WebApiResponse resp = new WebApiResponse();

            try
            {
                Guid Osztaly  = Guid.Parse(value.OsztalyID.ToString());
                Guid Tanterem = Guid.Parse(value.TanteremID.ToString());
                Guid Tanar    = Guid.Parse(value.TanarID.ToString());
                Guid Tantargy = Guid.Parse(value.TantargyID.ToString());
                int  Nap      = int.Parse(value.Nap.ToString());
                int  Ora      = int.Parse(value.Ora.ToString());

                dbmngr.OrarendHozzaad(Osztaly, Tanterem, Tanar, Tantargy, Nap, Ora);
                resp.ErrorCode = 0;
            }
            catch (OrarendMarLetezikError e)
            {
                resp.ErrorMessage = e.ErrorMessage;
                resp.ErrorCode    = e.ErrorCode;
            }
            catch (Exception e)
            {
                resp.ErrorCode    = -1;
                resp.ErrorMessage = e.Message;
            }

            return(JsonConvert.SerializeObject(resp));
        }
Beispiel #10
0
        public async Task <IHttpActionResult> GetSafetyInstruction(int id)
        {
            WebApiResponse <SafetyInstruction> response = new WebApiResponse <SafetyInstruction>();

            try
            {
                response.RequestUrl = Request.RequestUri.ToString();
                response.Version    = WebApi.Version;
                response.Data       = await db.SafetyInstructions.FindAsync(id);

                response.Exception  = null;
                response.StatusCode = "200";
                if (response.Data == null)
                {
                    return(NotFound());
                }

                response.Includes = new Dictionary <string, string>();
                foreach (var property in typeof(SafetyInstruction).GetProperties())
                {
                    Type propertyType = property.PropertyType;
                    if (!(propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime)))
                    {
                        response.Includes.Add(property.Name, response.RequestUrl + "/" + property.Name);
                    }
                }
            }
            catch (Exception e)
            {
                response.Exception  = e;
                response.StatusCode = "500";
            }
            return(Ok(response));
        }
        private async Task HandleException(IOwinContext context, Exception exception)
        {
            var result = new WebApiResponse {
                Message = exception?.Message
            };

            if (exception is AuthorizationException)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            }
            else if (exception is SmsOutBoundException)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                result.Error = "unknown faliure.";
            }
            string content = GetContent(result);

            context.Response.ContentLength = content.Length;
            context.Response.ContentType   = context.Request.ContentType ?? "application/json";
            await context.Response.WriteAsync(content);
        }
Beispiel #12
0
 protected override void Initialize(HttpControllerContext controllerContext)
 {
     response          = new WebApiResponse();
     testMode          = System.Configuration.ConfigurationManager.AppSettings["testMode"].Equals("N") ? false : true;
     errorMessage      = "";
     ControllerContext = controllerContext;
 }
Beispiel #13
0
        public void OnException(ExceptionContext context)
        {
            var httpStatusCode = HttpStatusCode.InternalServerError;

            if (context.Exception is ArgumentNullException)
            {
                httpStatusCode = HttpStatusCode.BadRequest;
            }

            var response = new WebApiResponse
            {
                Success = false,
                Error   = new ErrorDescriber
                {
                    Code        = httpStatusCode.ToString(),
                    Description = context.Exception.GetErrorMessage()
                }
            };

            context.Result = new ObjectResult(response)
            {
                StatusCode   = (int)HttpStatusCode.OK,
                DeclaredType = typeof(WebApiResponse)
            };

            if (httpStatusCode != HttpStatusCode.BadRequest)
            {
                m_Logger.LogError(context.Exception, response.Error.Description);
            }
        }
Beispiel #14
0
        public async Task <WebApiResponse> Send(string responseUrl, HttpClient client = null)
        {
            var content       = new StringContent(JsonConvert.SerializeObject(this), Encoding.UTF8, "application/json");
            var currentClient = client ?? new HttpClient();
            var response      = await currentClient.PostAsync(new Uri(responseUrl, UriKind.Absolute), content);

            var rawResponse = await response.Content.ReadAsStringAsync();

            if (response.Content.Headers.ContentType.MediaType != "text/html")
            {
                return(JsonConvert.DeserializeObject <WebApiResponse>(rawResponse));
            }

            var webApiResponse = new WebApiResponse();

            if (rawResponse == "ok")
            {
                webApiResponse.OK = true;
            }
            else
            {
                webApiResponse.OK    = false;
                webApiResponse.Error = rawResponse;
            }

            return(webApiResponse);
        }
Beispiel #15
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext executionContext)
        {
            string skillName = executionContext.FunctionName;

            log.LogInformation("Object detection function: C# HTTP trigger function processed a request.");

            var response = new WebApiResponse();

            response.values = new List <OutputRecord>();

            string requestBody = new StreamReader(req.Body).ReadToEnd();
            var    data        = JsonConvert.DeserializeObject <WebApiRequest>(requestBody);

            // Do some schema validation
            if (data == null)
            {
                return(new BadRequestObjectResult("The request schema does not match expected schema."));
            }
            if (data.Values == null)
            {
                return(new BadRequestObjectResult("The request schema does not match expected schema. Could not find values array."));
            }

            // Calculate the response for each value.
            foreach (var record in data.Values)
            {
                if (record == null || record.RecordId == null)
                {
                    continue;
                }

                OutputRecord responseRecord = new OutputRecord();
                responseRecord.RecordId = record.RecordId;

                try
                {
                    responseRecord.Data = GetObjects(record.Data.Url).Result;
                }
                catch (Exception e)
                {
                    // Something bad happened, log the issue.
                    var error = new OutputRecord.OutputRecordMessage
                    {
                        Message = e.Message
                    };

                    responseRecord.Errors = new List <OutputRecord.OutputRecordMessage>();
                    responseRecord.Errors.Add(error);
                }
                finally
                {
                    response.values.Add(responseRecord);
                }
            }

            return((ActionResult) new OkObjectResult(response));
        }
        private JsonResult Json <T>(string errorCode, string errorMessage, T result)
        {
            var error = new ErrorDescriber {
                Code = errorCode, Description = errorMessage
            };

            return(Json(WebApiResponse.Fail(error, result)));
        }
 protected JsonResult Json(IEnumerable <SimplyResult> results)
 {
     return(Json(results.Select(r => r.IsSuccess
         ? WebApiResponse.Ok()
         : WebApiResponse.Fail(new ErrorDescriber {
         Code = r.ErrorCode, Description = r.ErrorMessage
     }))));
 }
        protected JsonResult Fail(string errorCode, string errorMessage)
        {
            var error = new ErrorDescriber {
                Code = errorCode, Description = errorMessage
            };

            return(Json(WebApiResponse.Fail(error)));
        }
Beispiel #19
0
        protected virtual WebApiResponse <T> GetWebApiResponse <T>(HttpResponseMessage response)
        {
            var responseValue   = GetResponsePayload <T>(response);
            var responseMessage = CreateResponseMessage(response);
            var errors          = GetContentErrors(response);

            return(WebApiResponse <T> .Create(responseValue, responseMessage, errors));
        }
Beispiel #20
0
        /// <inheritdoc />
        public virtual Task <IWebApiResponse> OnRequestAsync(MiddlewareContext context, Func <MiddlewareContext, CancellationToken, Task <IWebApiResponse> > callNext, CancellationToken cancellationToken = default)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (callNext is null)
            {
                throw new ArgumentNullException(nameof(callNext));
            }
            return(ExecAsync());

            async Task <IWebApiResponse> ExecAsync()
            {
                var httpResponse = await callNext(context, cancellationToken).ConfigureAwait(false);

                if (httpResponse == null)
                {
                    return(null !);
                }

                if ((int)httpResponse.StatusCode >= 200 && (int)httpResponse.StatusCode <= 299)
                {
                    return(httpResponse);
                }

                ErrorObject error;

                try
                {
                    error = JsonSerializer.Deserialize <ErrorObject>(httpResponse.Content, deserializerOptions);
                }
                catch (JsonException)
                {
                    // Fallback message
                    throw new UnexpectedStatusException(context.Request, httpResponse, httpResponse.Content ?? string.Empty);
                }

                var errorResponse = new WebApiResponse <ErrorObject>(error, httpResponse.StatusCode, httpResponse.ResponseHeaders);

                throw httpResponse.StatusCode switch
                      {
                          HttpStatusCode.BadRequest => BadRequestException.CreateFromResponse(context.Request, errorResponse),
                          HttpStatusCode.Unauthorized => AuthorizationRequiredException.CreateFromResponse(context.Request, errorResponse),
                          HttpStatusCode.Forbidden => AuthorizationRequiredException.CreateFromResponse(context.Request, errorResponse),
                          HttpStatusCode.NotFound => new NotFoundException(context.Request, errorResponse),
#if NETSTANDARD
                          (HttpStatusCode)429 => new TooManyRequestsException(context.Request, errorResponse),
#else
                          HttpStatusCode.TooManyRequests => new TooManyRequestsException(context.Request, errorResponse),
#endif
                          HttpStatusCode.InternalServerError => new ServerErrorException(context.Request, errorResponse),
                          HttpStatusCode.ServiceUnavailable => new ServiceUnavailableException(context.Request, errorResponse),
                          _ => new UnexpectedStatusException(context.Request, httpResponse, httpResponse.Content ?? string.Empty)
                      };
            }
        }
    }
Beispiel #21
0
        private async Task <HttpResponseMessage> ResponseAsync(string errorMessage, HttpStatusCode httpStatusCode, string message = "")
        {
            var result = new WebApiResponse {
                Message = message, Error = errorMessage
            };
            var response = Request.CreateResponse(httpStatusCode, result);

            return(await Task.FromResult(response));
        }
    public HttpResponseMessage getBrowseHistory(BrowseHistoryList BH)
    {
        ar = new WebApiResponse();
        try
        {
            string qry = "select * from MDM_BrowseHistory where DeviceID='" + BH.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                {
                    dr.Close();
                }

                qry  = "delete from MDM_BrowseHistory where DeviceID='" + BH.uuid + "'";
                rcnt = databaseHelper.ExecuteQuery(qry);
            }

            if (!dr.IsClosed)
            {
                dr.Close();
            }

            foreach (SortedList <string, string> key_val in BH.BrowseHistory)
            {
                qry = "insert into MDM_BrowseHistory(DeviceID,URL,BrowseTimeStamp)values('" + BH.uuid + "','" + key_val["url"] + "',convert(datetime,'" + key_val["BrowseTimeStamp"] + "',120))";

                //linfo.LogException(null, "Browse History Query = " + qry);

                databaseHelper.ExecuteQuery(qry);
            }

            qry  = "delete from MDM_PushNotification where DeviceID='" + BH.uuid + "' and Command='Browse History'";
            rcnt = databaseHelper.ExecuteQuery(qry);

            ar.errorCode = "Successfully Completed";
            ar.response  = true;
            response     = Request.CreateResponse(HttpStatusCode.Created, ar);
            return(response);
        }
        catch (Exception ex)
        {
            ar.errorCode = "Browse History Submission Failed";
            ar.response  = false;
            response     = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
            {
                dr.Close();
            }
        }
        return(response);
    }
Beispiel #23
0
        public static async Task <WebApiResponse> AssertEncodedWebApi(Func <ISlackApiClient, Task <WebApiResponse> > func, string methodName, Action <NameValueCollection> requestAssertion)
        {
            var response = await CheckApi(func,
                                          methodName,
                                          requestAssertion, WebApiResponse.Success());

            Assert.True(response.OK);
            return(response);
        }
Beispiel #24
0
        public WebApiException(WebApiResponse response, object request) : base()
        {
            ApiResponse  = response;
            ErrorMessage = ApiResponse.ToString();

            if (request != null)
            {
                ErrorMessage += $"\nPayLoad: {JsonConvert.SerializeObject(request)}";
            }
        }
        public ActionResult GazettedHoliday(FormCollection form)
        {
            #region Added by shakir (Currency parameter)
            var selectCurrency = (dynamic)null;

            if (form["selectCurrency"] != null)
            {
                selectCurrency = Convert.ToInt32(form["selectCurrency"].ToString());
            }
            else
            {
                selectCurrency = Convert.ToInt32(Session["SelectedCurrency"].ToString());
            }

            UtilityClass.GetSelectedCurrecy(selectCurrency);

            #endregion

            ServiceRepository   serviceObj = new ServiceRepository();
            HttpResponseMessage response   = serviceObj.GetResponse("/api/GazettedHolidays/GetAllBlotterGH?UserID=" + Session["UserID"].ToString());
            response.EnsureSuccessStatusCode();
            List <Models.SP_GetSBPBlotterGH_Result> blotterGH = new List <Models.SP_GetSBPBlotterGH_Result>();
            if (response.IsSuccessStatusCode)
            {
                string         jsonResponse = response.Content.ReadAsStringAsync().Result;
                var            JsonLinq     = JObject.Parse(jsonResponse);
                WebApiResponse getreponse   = new WebApiResponse();
                getreponse.Status  = Convert.ToBoolean(JsonLinq["Status"]);
                getreponse.Message = JsonLinq["Message"].ToString();
                getreponse.Data    = JsonLinq["Data"].ToString();

                if (getreponse.Message == "Success")
                {
                    JavaScriptSerializer         ser        = new JavaScriptSerializer();
                    Dictionary <string, dynamic> ResponseDD = ser.Deserialize <Dictionary <string, dynamic> >(JsonLinq.ToString());
                    blotterGH = JsonConvert.DeserializeObject <List <Models.SP_GetSBPBlotterGH_Result> >(ResponseDD["Data"]);
                }
                else
                {
                    TempData["DataStatus"] = "Data not available";
                }
            }
            if (blotterGH.Count < 1)
            {
                ViewData["DataStatus"] = "Data Not Availavle";
            }
            ViewBag.Title = "All Blotter Setup";
            var PAccess = Session["CurrentPagesAccess"].ToString().Split('~');
            UtilityClass.ActivityMonitor(Convert.ToInt32(Session["UserID"]), Session.SessionID, Request.UserHostAddress.ToString(), new Guid().ToString(), JsonConvert.SerializeObject(blotterGH), this.RouteData.Values["action"].ToString(), Request.RawUrl.ToString());

            ViewData["isDateChangable"] = Convert.ToBoolean(PAccess[2]);
            ViewData["isEditable"]      = Convert.ToBoolean(PAccess[3]);
            ViewData["IsDeletable"]     = Convert.ToBoolean(PAccess[4]);
            return(PartialView("_BlotterGH", blotterGH));
        }
Beispiel #26
0
        /// <summary>
        /// Get PEIN Items (only 10 Sample records. Useful for testing)
        /// </summary>
        /// <returns>SearchResult containing a list of results and additional information</returns>
        public IWebApiResponse GetAll()
        {
            var sr = BL.GetPeinItemBySearch("", 0, 10);

            sr.Info.Text = "Get PEIN Items (only 10 Sample records with all available fields. Useful for testing)";

            var response = new WebApiResponse <SearchResult>(sr);

            response.ApiSuccess = true;
            return(response);
        }
        // FILE UPLOAD FOR IMAGE, VIDEO, AUDIO
        // FOR API FILE UPLOAD CALL
        public async Task <WebApiResponse <T> > FileUploadToApi <T>(HttpPostedFileBase file)
        {
            var res = new WebApiResponse <T>();

            T   result;
            var url = GetWebApiUrl();

            try
            {
                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        byte[] Bytes = new byte[file.InputStream.Length + 1];
                        file.InputStream.Read(Bytes, 0, Bytes.Length);
                        var fileContent = new ByteArrayContent(Bytes);
                        fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                        {
                            FileName = file.FileName
                        };

                        content.Add(fileContent);
                        var requestUri = $"{url}{FileUploadApiUrl.UploadFile}";

                        var response = await client.PostAsync(requestUri, content);

                        if (response.IsSuccessStatusCode)
                        {
                            result = await response.Content.ReadAsAsync <T>();

                            res.isSuccess    = true;
                            res.ErrorMessage = "";
                            res.Data         = result;
                        }
                        else
                        {
                            var str = await response.Content.ReadAsStringAsync();

                            res.isSuccess    = false;
                            res.Data         = default(T);
                            res.ErrorMessage = str;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res.isSuccess    = false;
                res.Data         = default(T);
                res.ErrorMessage = ex.Message;
            }

            return(res);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Custom skill: C# HTTP trigger function processed a request.");

            // Read input, deserialize it and validate it.
            var data = GetStructuredInput(req.Body);

            if (data == null)
            {
                return(new BadRequestObjectResult("The request schema does not match expected schema."));
            }

            // Calculate the response for each value.
            var response = new WebApiResponse();

            foreach (var record in data.Values)
            {
                if (record == null || record.RecordId == null)
                {
                    continue;
                }

                OutputRecord responseRecord = new OutputRecord();
                responseRecord.RecordId = record.RecordId;

                try
                {
                    responseRecord.Data = DoWork(record.Data).Result;
                }
                catch (Exception e)
                {
                    // Something bad happened, log the issue.
                    var error = new OutputRecord.OutputRecordMessage
                    {
                        Message = e.Message
                    };

                    responseRecord.Errors = new List <OutputRecord.OutputRecordMessage>
                    {
                        error
                    };
                }
                finally
                {
                    response.values.Add(responseRecord);
                }
            }

            return(new OkObjectResult(response));
        }
        public ActionResult _Create(GazettedHoliday BlotterGH, FormCollection form)
        {
            try
            {
                #region Added by shakir (Currency parameter)
                var selectCurrency = (dynamic)null;
                if (form["selectCurrency"] != null)
                {
                    selectCurrency = Convert.ToInt32(form["selectCurrency"].ToString());
                }
                else
                {
                    selectCurrency = Convert.ToInt32(Session["SelectedCurrency"].ToString());
                }

                UtilityClass.GetSelectedCurrecy(selectCurrency);
                #endregion

                if (ModelState.IsValid)
                {
                    BlotterGH.UserID     = Convert.ToInt16(Session["UserID"].ToString());
                    BlotterGH.createDate = DateTime.Now;
                    ServiceRepository   serviceObj = new ServiceRepository();
                    HttpResponseMessage response   = serviceObj.PostResponse("api/GazettedHolidays/InsertGH", BlotterGH);
                    response.EnsureSuccessStatusCode();

                    if (response.IsSuccessStatusCode)
                    {
                        string         jsonResponse = response.Content.ReadAsStringAsync().Result;
                        var            JsonLinq     = JObject.Parse(jsonResponse);
                        WebApiResponse getreponse   = new WebApiResponse();
                        getreponse.Status  = Convert.ToBoolean(JsonLinq["Status"]);
                        getreponse.Message = JsonLinq["Message"].ToString();
                        getreponse.Data    = JsonLinq["Data"].ToString();

                        if (getreponse.Status == true)
                        {
                            TempData["DataStatus"] = getreponse.Message;
                        }
                        else
                        {
                            TempData["DataStatus"] = getreponse.Message;
                        }
                    }
                    UtilityClass.ActivityMonitor(Convert.ToInt32(Session["UserID"]), Session.SessionID, Request.UserHostAddress.ToString(), new Guid().ToString(), JsonConvert.SerializeObject(BlotterGH), this.RouteData.Values["action"].ToString(), Request.RawUrl.ToString());
                    return(RedirectToAction("GazettedHoliday"));
                }
            }
            catch (Exception ex) { }

            return(PartialView("_Create", BlotterGH));
        }
    /// <summary>
    ///To Update the Device Location status to admin
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage updateDeviceLocation(DeviceLocation DL)
    {
        ar = new WebApiResponse();
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + DL.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                {
                    dr.Close();
                }

                DeviceTrackingDetail DT = new DeviceTrackingDetail();

                var list = DL.locations;
                foreach (var c in list)
                {
                    qry  = "insert into MDM_DeviceTrackingDetail(DeviceId,latitude,longitude,CreatedDate)values('" + DL.uuid + "','" + c.latitude + "','" + c.longitude + "','" + c.timestamp.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                    rcnt = databaseHelper.ExecuteQuery(qry);
                }
                ar.response = true;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ar);

                qry  = "delete from MDM_PushNotification where DeviceID='" + DL.uuid + "' and Command='GetDeviceLocation'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                return(response);
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response  = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return(response);
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
            {
                dr.Close();
            }
        }
        return(null);
    }
    /// <summary>
    ///Process Remotely Un-installed Apk
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage ProcessRemoteUnInstall(RemoteUninstall RU)
    {
        ar = new WebApiResponse();
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + RU.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                {
                    dr.Close();
                }

                qry  = "delete from MDM_PushNotification where DeviceID='" + RU.uuid + "' and Command like '%Remote Uninstall%'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                qry = "delete from MDM_InstalledApps where DeviceID='" + RU.uuid + "' and isDownloaded=1 and ApplicationPackage='" + RU.packageName + "'";

                //linfo.LogException(null,"Process Remote Uninstall Delete Qry = "+qry);
                rcnt = databaseHelper.ExecuteQuery(qry);

                ar.response = true;
                response    = Request.CreateResponse(HttpStatusCode.Created, ar);
                return(response);
            }
            else
            {
                ar.errorCode = "No Device Found";
                ar.response  = false;
                response     = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return(response);
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, "Problem in ProcessRemoteUninstall()", null);
            ar.errorCode = "WebService Exception in function ProcessRemoteUninstall()";
            ar.response  = false;
            response     = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
            {
                dr.Close();
            }
        }
        return(response);
    }
    /// <summary>
    ///To Update the PushNotification During Remote Installed App
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage RemotelyInstalledAPK(SortedList<string, string> pm)
    {
        ar = new WebApiResponse();
        try
        {

            if (pm.ContainsKey("uuid"))
            {
                string qry = "select * from MDM_DeviceMaster where DeviceID='" + pm["uuid"] + "'";
                dr = databaseHelper.getDataReader(qry);

                if (dr.Read())
                {
                    if (!dr.IsClosed)
                        dr.Close();

                    if (pm.ContainsKey("packageName") && pm.ContainsKey("applicationName"))
                    {
                        qry = "update MDM_RemoteInstallApp set ApplicationPackage='" + pm["packageName"] + "' where ApplicationName='" + pm["applicationName"].ToString() + "'";
                        rcnt = databaseHelper.ExecuteQuery(qry);
                    }
                    qry = "delete from MDM_PushNotification where DeviceID='" + pm["uuid"] + "' and Command like '%Remote Install%'";
                    rcnt = databaseHelper.ExecuteQuery(qry);

                    ar.response = true;
                    response = Request.CreateResponse(HttpStatusCode.Created, ar);
                    return response;
                }
                else
                {
                    ar.errorCode = "Error in service RemotelyInstalledAPK";
                    ar.response = false;
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                    return response;
                }
            }
            else
            {
                ar.errorCode = "uuid is empty";
                ar.response = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);
            ar.errorCode = "Remote Install APK Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }
    public HttpResponseMessage getBrowseHistory(BrowseHistoryList BH)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_BrowseHistory where DeviceID='" + BH.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                    dr.Close();

                qry = "delete from MDM_BrowseHistory where DeviceID='" + BH.uuid + "'";
                rcnt = databaseHelper.ExecuteQuery(qry);
            }

            if (!dr.IsClosed)
                dr.Close();

            foreach (SortedList<string, string> key_val in BH.BrowseHistory)
            {
                qry = "insert into MDM_BrowseHistory(DeviceID,URL,BrowseTimeStamp)values('" + BH.uuid + "','" + key_val["url"] + "',convert(datetime,'"+key_val["BrowseTimeStamp"]+"',120))";

                //linfo.LogException(null, "Browse History Query = " + qry);

                databaseHelper.ExecuteQuery(qry);
            }

            qry = "delete from MDM_PushNotification where DeviceID='" + BH.uuid + "' and Command='Browse History'";
            rcnt = databaseHelper.ExecuteQuery(qry);

            ar.errorCode = "Successfully Completed";
            ar.response = true;
            response = Request.CreateResponse(HttpStatusCode.Created, ar);
            return response;
        }
        catch (Exception ex)
        {
            ar.errorCode = "Browse History Submission Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            linfo.LogFile(enLogType.EXCEPTION, ex.Message,null);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }
    public HttpResponseMessage VerifyUserAuthentication(SortedList<string, string> sl_post)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from AppUsers where UserName='******' and password = '******' and Status ='Active'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                ar.errorCode = "Valid User";
                ar.response = true;
            }
            else
            {
                ar.errorCode = "Invalid User";
                ar.response = false;
            }

            if (!dr.IsClosed)
                dr.Close();

            response = Request.CreateResponse(HttpStatusCode.Created, ar);
            return response;
        }
        catch (Exception ex)
        {
            ar.errorCode = "Submission Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            linfo.LogFile(enLogType.EXCEPTION, ex.Message,null);           
        }
        finally
        {
            if (dr!=null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }
    /// <summary>
    ///For Registering a Device From Android Device 
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage registerDevice(SortedList<string, string> sl_post)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry,EmpCode=null,UserType=null,Mobile=null,UserName=null;

            try
            {
                if (sl_post.ContainsKey("EmpCode"))
                {
                    EmpCode = sl_post["EmpCode"];                    
                    qry = "Select UserType,Mobile,UserName from AppUsers where EmpCode='" + sl_post["EmpCode"] + "'";
                    dr = databaseHelper.getDataReader(qry);                    
                    if(dr.Read())
                    {
                        UserType = dr["UserType"]!=DBNull.Value ? dr["UserType"].ToString() : null;
                        Mobile = dr["Mobile"] != DBNull.Value ? dr["Mobile"].ToString() : null;
                        UserName = dr["UserName"] != DBNull.Value ? dr["UserName"].ToString() : null;
                    }

                    if (!dr.IsClosed)
                        dr.Close();
                }

                qry = "select * from MDM_DeviceMaster where DeviceID='" + sl_post["uuid"] + "'";
                dr = databaseHelper.getDataReader(qry);

                ar.response = true;
                if (dr.Read())
                {
                    if (!dr.IsClosed)
                        dr.Close();

                    qry = "update MDM_DeviceMaster set Make='" + sl_post["make"] + "',osVersion='" + sl_post["osVersion"] + "',imeiNumber='" + sl_post["imeiNumber"] + "',macAddress='" + sl_post["macAddress"] + "',registrationId='" + sl_post["registrationId"] + "',GPSStatus=" + sl_post["gpsStatus"] + ",UserId='"+EmpCode+"',UserName='******', UserType='"+UserType+"',ContactNo='"+Mobile+"' where DeviceID='" + sl_post["uuid"] + "'";

                    rcnt = databaseHelper.ExecuteQuery(qry);
                    response = Request.CreateResponse(HttpStatusCode.Created, ar);
                }
                else
                {
                    if (!dr.IsClosed)
                        dr.Close();

                    qry = "insert into MDM_DeviceMaster(DeviceID,Make,UserId,UserName,UserType,ContactNo, osVersion,imeiNumber,macAddress,registrationId,GPSStatus,Manufacturer,DeviceSerialNumber,KernelVersion,APILevel,BuildNumber,ProcessorName,ProcessorSpeed,RAM,InternalStorage,TotalFreeStorage,FreeInternal,FreeExternal,DeviceRooted,ScreenResolution,ScreenLanguage,ScreenWidth,TimeZone,CameraPresent,GPSPresent,BluetoothPresent,NFCPresent,BatteryLevel,BatteryCondition)values('" + sl_post["uuid"] + "','" + sl_post["make"] + "','"+EmpCode+"','"+UserName+"','"+UserType+"','"+Mobile+"','" + sl_post["osVersion"] + "','" + sl_post["imeiNumber"] + "','" + sl_post["macAddress"] + "','" + sl_post["registrationId"] + "'," + sl_post["gpsStatus"] + ",'" + sl_post["Manufacturer"] + "','" + sl_post["DeviceSerialNumber"] + "','" + sl_post["KernelVersion"] + "','" + sl_post["APILevel"] + "','" + sl_post["BuildNumber"] + "','" + sl_post["ProcessorName"] + "','" + sl_post["ProcessorSpeed"] + "','" + sl_post["RAM"] + "','" + sl_post["InternalStorage"] + "','" + sl_post["TotalFreeStorage"] + "','" + sl_post["FreeInternal"] + "','" + sl_post["FreeExternal"] + "'," + sl_post["DeviceRooted"] + ",'" + sl_post["ScreenResolution"] + "','" + sl_post["ScreenLanguage"] + "','" + sl_post["ScreenWidth"] + "','" + sl_post["TimeZone"] + "'," + sl_post["CameraPresent"] + "," + sl_post["GPSPresent"] + "," + sl_post["BluetoothPresent"] + "," + sl_post["NFCPresent"] + ",'" + sl_post["BatteryLevel"] + "','" + sl_post["BatteryCondition"] + "')";

                    rcnt = databaseHelper.ExecuteQuery(qry);
                    response = Request.CreateResponse(HttpStatusCode.Created, ar);
                }

                /*qry = "delete from MDM_PushNotification where DeviceID='" + sl_post["uuid"] + "'";
                rcnt = databaseHelper.ExecuteQuery(qry);*/

                return response;

            }
            catch (Exception ex)
            {
                if (!dr.IsClosed)
                    dr.Close();

                linfo.LogFile(enLogType.EXCEPTION, "Problem in Register Device.Internal try catch "+ex.InnerException.ToString(), null);
            }
            finally
            {
                if (!dr.IsClosed)
                    dr.Close();
            }            
        }
        catch (Exception ex)
        {
            ar.errorCode = "Submission Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            linfo.LogFile(enLogType.EXCEPTION, "Problem in Register Device. External try catch ", null);                        
        }
        return response;
    }
    /// <summary>
    ///To Get all List of Applications From Device which are currently installed on device to Admin(Database)
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage sendInstalledApps(SendInstalledApps SI)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + SI.uuid + "'";
            dr = databaseHelper.getDataReader(qry);
            if (dr.Read())
            {
                InstalledApp IA = new InstalledApp();
                IA.Device = dr["DeviceID"].ToString();
                IA.CreatedBy = 1;
                IA.UpdatedBy = 1;
                var list = SI.applications;
                if (!dr.IsClosed)
                    dr.Close();

                qry = "select * from MDM_InstalledApps where DeviceID='" + SI.uuid + "'";
                dr = databaseHelper.getDataReader(qry);
                if (dr.Read())
                {
                    if (!dr.IsClosed)
                        dr.Close();

                    qry = "Delete from MDM_InstalledApps where DeviceID='" + SI.uuid + "'";

                    rcnt = databaseHelper.ExecuteQuery(qry);

                }

                if (!dr.IsClosed)
                    dr.Close();

                foreach (var c in list)
                {
                    //Check that application package exist in installed apps(accessible application db) if not then insert application details
                    #region Accessible Apps //Check Application Package in (Accessible Apps database)/Installed apps if not then Add

                    /*qry = "select * from MDM_AccessibleApplication where ApplicationPackage='"+c.applicationPackage+"'";
                   dr = databaseHelper.getDataReader(qry);
                   if (!dr.Read())
                   {
                       if (!dr.IsClosed)
                           dr.Close();

                       qry = "insert into MDM_AccessibleApplication(ApplicationPackage,ApplicationName,CreatedDate)values('"+c.applicationPackage+"','"+c.applicationName+"','"+DateTime.Now+"')";

                       rcnt = databaseHelper.ExecuteQuery(qry);
                   }*/
                    #endregion
                    if (c.applicationName == null)//if application name recieved null then insert application package as name also
                    {
                        IA.ApplicationName = c.applicationPackage;
                    }
                    else
                    {
                        IA.ApplicationName = c.applicationName;
                    }

                    IA.ApplicationPackage = c.applicationPackage;
                    IA.CreatedDate = c.installedOn;
                    IA.UpdatedDate = DateTime.Now;
                    IA.isDownloaded = c.isDownloaded;
                    IA.applicationVersion = c.applicationVersion;
                    IA.applicationSize = c.applicationSize;
                    qry = "insert into MDM_InstalledApps(DeviceID,CreatedBy,UpdatedBy,ApplicationName,ApplicationPackage,CreatedDate,UpdatedDate,isDownloaded,ApplicationVersion,ApplicationSize) values('" + IA.Device + "'," + IA.CreatedBy + "," + IA.UpdatedBy + ",'" + IA.ApplicationName + "','" + IA.ApplicationPackage + "','" + IA.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss") + "','" + IA.UpdatedDate.ToString("yyyy-MM-dd HH:mm:ss") + "'," + IA.isDownloaded + ",'" + IA.applicationVersion + "','" + IA.applicationSize + "')";

                    //linfo.LogFile(enLogType.INFO, qry, "rizwan");

                    rcnt = databaseHelper.ExecuteQuery(qry);

                    ar.errorCode += c.applicationPackage + " Added Successfully";
                }
                ar.response = true;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ar);

                qry = "delete from MDM_PushNotification where DeviceID='" + SI.uuid + "' and Command='Update Application List'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                return response;
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.PartialContent, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message + "Problem in SendInstalledApp", null);                                    
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return null;
    }
    public HttpResponseMessage getAccessibleApps(postmethod pm)
    {
        getConfigurationDetails gc = new getConfigurationDetails();        
        getAccessibleApps gaa = new getAccessibleApps();
        List<application> ga = new List<application>();

        string qry = "select * from MDM_DeviceMaster where DeviceID='" + pm.uuid + "'";
        dr = databaseHelper.getDataReader(qry);
        if (dr.Read())
        {
            string UserId = dr["UserId"] != DBNull.Value ? dr["UserId"].ToString().ToUpper() : null;

            if (!dr.IsClosed)
                dr.Close();

            string Designation = null;

            qry = "select UserType from AppUsers where UserName='******'";
            dr = databaseHelper.getDataReader(qry);
            if (dr.Read())
            {
                Designation = dr["UserType"].ToString().ToUpper();
            }

            if (!dr.IsClosed)
                dr.Close();

            qry = "select ApplicationName,ApplicationPackage,UserId,UserDesignation from MDM_AccessibleApplication";
            dtable = databaseHelper.getDataTable(qry);
            if (dtable.Rows.Count > 0)
            {
                foreach (DataRow drow in dtable.Rows)
                {
                    //linfo.LogFile(enLogType.QUERY, "drow[UserId] = " + drow["UserId"] + " drow[UserDesignation] = " + drow["UserDesignation"] + " UserId = " + UserId + ". UserDesignation = " + Designation + "", "rizwan");
                    if (drow["UserId"] == DBNull.Value && drow["UserDesignation"] == DBNull.Value) // Default Application
                    {
                        ga.Add(new application
                        {

                            applicationName = (drow["ApplicationName"] == DBNull.Value) ? "" : drow["ApplicationName"].ToString(),
                            applicationPackage = (drow["ApplicationPackage"] == DBNull.Value) ? "" : drow["ApplicationPackage"].ToString()
                        });

                        //linfo.LogFile(enLogType.INFO, "UserID,UserDesignation are null. ApplicationName = " + drow["ApplicationName"] + " ApplicationPackage = "+drow["ApplicationPackage"]+"", "rizwan");
                    }
                    else if (drow["UserId"] != DBNull.Value && drow["UserDesignation"] != DBNull.Value && drow["UserId"].ToString().Length > 0 && drow["UserDesignation"].ToString().Length > 0 && drow["UserId"].ToString().Split(',').Contains(UserId) && drow["UserDesignation"].ToString().Split(',').Contains(UserId))// Application Valid only to specific user.
                    {
                        ga.Add(new application
                        {

                            applicationName = (drow["ApplicationName"] == DBNull.Value) ? "" : drow["ApplicationName"].ToString(),
                            applicationPackage = (drow["ApplicationPackage"] == DBNull.Value) ? "" : drow["ApplicationPackage"].ToString()
                        });

                        //linfo.LogFile(enLogType.INFO, "Userid and UserDesignation are not null . drow[UserId] = " + drow["UserId"] + " and Userid=" + UserId + ". drow[UserDesignation] = " + drow["UserDesignation"] + " and Designation = " + Designation + " ApplicationName = " + drow["ApplicationName"] + " ApplicationPackage = " + drow["ApplicationPackage"] + "", "rizwan");
                    }
                    else if (drow["UserId"] != DBNull.Value && drow["UserDesignation"] == DBNull.Value && drow["UserID"].ToString().Length > 0 && drow["UserID"].ToString().Split(',').Contains(UserId))// Application Valid only to specific user.
                    {
                        ga.Add(new application
                        {

                            applicationName = (drow["ApplicationName"] == DBNull.Value) ? "" : drow["ApplicationName"].ToString(),
                            applicationPackage = (drow["ApplicationPackage"] == DBNull.Value) ? "" : drow["ApplicationPackage"].ToString()
                        });
                        //linfo.LogFile(enLogType.INFO, "Userid is not null. drow[UserId] = " + drow["UserId"] + " and Userid=" + UserId + ". drow[UserDesignation] = " + drow["UserDesignation"] + " and Designation = " + Designation + " ApplicationName = " + drow["ApplicationName"] + " ApplicationPackage = " + drow["ApplicationPackage"] + "", "rizwan");
                    }
                    else if (drow["UserDesignation"] != DBNull.Value && drow["UserId"] == DBNull.Value && drow["UserDesignation"].ToString().Length > 0 && drow["UserDesignation"].ToString().Split(',').Contains(Designation)) //application valid only to specific designation (multiple user can come to same designation)
                    {
                        ga.Add(new application
                        {

                            applicationName = (drow["ApplicationName"] == DBNull.Value) ? "" : drow["ApplicationName"].ToString(),
                            applicationPackage = (drow["ApplicationPackage"] == DBNull.Value) ? "" : drow["ApplicationPackage"].ToString()
                        });
                        //linfo.LogFile(enLogType.INFO, "UserDesignation is not null. drow[UserId] = " + drow["UserId"] + " and Userid=" + UserId + ". drow[UserDesignation] = " + drow["UserDesignation"] + " and Designation = " + Designation + " ApplicationName = " + drow["ApplicationName"] + " ApplicationPackage = " + drow["ApplicationPackage"] + "", "rizwan");
                    }
                }
            }
            gaa.applications = ga;

            #region     Website list

            qry = "Select WebsiteName from MDM_AccessibleWebsite";
            dtable = databaseHelper.getDataTable(qry);
            List<weblist> website = new List<weblist>();
            foreach (DataRow drow in dtable.Rows)
            {
                website.Add(new weblist
                 {
                     WebsiteName = (drow["WebsiteName"] == DBNull.Value) ? "" : drow["WebsiteName"].ToString()
                 });
            }
            gaa.websiteurl = website;
            #endregion

            gaa.response = true;
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, gaa);

            qry = "delete from MDM_PushNotification where DeviceID='" + pm.uuid + "' and Command='Get Accessible Apps'";
            rcnt = databaseHelper.ExecuteQuery(qry);

            return response;
        }
        else
        {
            ar = new WebApiResponse();
            ar.errorCode = "Authentication failed";
            ar.response = false;
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            return response;
        }
    }
    /// <summary>
    ///To Get all the Log activities From the Device to Admin (database)
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage logActivities(logActivities LA)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + LA.uuid + "'";
            //linfo.LogFile(enLogType.QUERY, "Query = " + qry + "Device ID = " + LA.uuid, "Rizwan");
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                ActivityLog la = new ActivityLog();
                DeviceTrackingDetail dt = new DeviceTrackingDetail();
                var list = LA.activity;

                string id = LA.uuid;
                if (!dr.IsClosed)
                    dr.Close();

                foreach (var c in list)
                {
                    la.DeviceID = id;
                    la.ActivityCode = c.activityCode;
                    la.LogText = c.actitivyDetail;
                    la.CreatedBy = 1;
                    la.UpdatedBy = 1;
                    la.LogDateTime = c.activityOn;
                    la.activityType = c.activityType;
                    if (c.activityCode == 2)
                    {
                        la.LogText = c.actitivyDetail + " Latitude : " + c.latitude + " Longitude : " + c.longitude;
                    }
                    qry = "insert into MDM_ActivityLog(LogText,DeviceID,EmployeeID,LogDateTime,ActivityCode,ActivityType)values('" + la.LogText + "','" + la.DeviceID + "','1','" + DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss") + "','" + la.ActivityCode + "','" + la.activityType + "')";

                    //linfo.LogFile(enLogType.QUERY, "\n\n Query = " + qry , "Rizwan");

                    rcnt = databaseHelper.ExecuteQuery(qry);
                }
                ar.response = true;
                response = Request.CreateResponse(HttpStatusCode.Created, ar);

                return response;
            }
            else
            {
                ar.errorCode = "No Device Found";
                ar.response = false;
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            if (!dr.IsClosed)
                dr.Close();
            linfo.LogFile(enLogType.EXCEPTION, "Function = logActivities() Error Message = "+ex.Message+"  InnerException ="+ex.InnerException.ToString(),null);

            ar.errorCode = "Problem in logActivities() WS";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();            
        }
        return response;
    }
    public HttpResponseMessage getAccessibleWebsites(postmethod pm)
    {        
        getAccessibleWebsites gaw = new getAccessibleWebsites();
        List<weblist> wl = new List<weblist>();
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + pm.uuid + "'";
            dr = databaseHelper.getDataReader(qry);
            if (dr.Read())
            {
                string UserId = dr["UserId"].ToString().ToUpper();

                if (!dr.IsClosed)
                    dr.Close();

                string Designation = null;

                qry = "select UserType from AppUsers where UserName='******'";
                dr = databaseHelper.getDataReader(qry);
                if (dr.Read())
                {
                    Designation = dr["UserType"].ToString().ToUpper();
                }

                if (!dr.IsClosed)
                    dr.Close();

                qry = "Select WebsiteName,UserId,UserDesignation from MDM_AccessibleWebsite";
                dtable = databaseHelper.getDataTable(qry);
                List<weblist> website = new List<weblist>();
                foreach (DataRow drow in dtable.Rows)
                {
                    //linfo.LogFile(enLogType.QUERY, "drow[UserId] = " + drow["UserId"] + " drow[UserDesignation] = "+drow["UserDesignation"]+" UserId = "+UserId+". UserDesignation = "+Designation+"","rizwan");
                    if (drow["UserId"] == DBNull.Value && drow["UserDesignation"] == DBNull.Value) // Default Application
                    {
                        website.Add(new weblist
                        {
                            WebsiteName = (drow["WebsiteName"] == DBNull.Value) ? "" : drow["WebsiteName"].ToString()
                        });
                        //linfo.LogFile(enLogType.INFO, "UserID,UserDesignation are null. WebsiteName = " + drow["WebsiteName"] + "", "rizwan");
                    }
                    else if (drow["UserId"] != DBNull.Value && drow["UserDesignation"] != DBNull.Value && drow["UserId"].ToString().Length > 0 && drow["UserDesignation"].ToString().Length > 0 && drow["UserID"].ToString().Split(',').Contains(UserId) && drow["UserDesignation"].ToString().Split(',').Contains(UserId))// Application Valid only to specific user.
                    {
                        website.Add(new weblist
                        {
                            WebsiteName = (drow["WebsiteName"] == DBNull.Value) ? "" : drow["WebsiteName"].ToString()
                        });
                        //linfo.LogFile(enLogType.INFO, "UserId and UserDesignation are not null . drow[UserId] = " + drow["UserId"] + " drow[UserDesignation] = " + drow["UserDesignation"] + " UserId = " + UserId + ". UserDesignation = " + Designation + "", "rizwan");
                    }
                    else if (drow["UserId"] != DBNull.Value && drow["UserDesignation"] == DBNull.Value && drow["UserId"].ToString().Length > 0 && drow["UserId"].ToString().Split(',').Contains(UserId)) // Accessible to specific user.
                    {
                        website.Add(new weblist
                        {
                            WebsiteName = (drow["WebsiteName"] == DBNull.Value) ? "" : drow["WebsiteName"].ToString()
                        });
                       // linfo.LogFile(enLogType.INFO, "Userid is not null. drow[UserId] = "+drow["UserId"]+" and Userid="+UserId+". drow[UserDesignation] = "+drow["UserDesignation"]+" and Designation = "+Designation+" WebsiteName = " + drow["WebsiteName"] + "", "rizwan");
                    }
                    else if (drow["UserDesignation"] != DBNull.Value && drow["UserId"] == DBNull.Value && drow["UserDesignation"].ToString().Length > 0 && drow["UserDesignation"].ToString().Contains(Designation))//accessible to user of specific designation
                    {
                        website.Add(new weblist
                        {
                            WebsiteName = (drow["WebsiteName"] == DBNull.Value) ? "" : drow["WebsiteName"].ToString()
                        });

                        //linfo.LogFile(enLogType.INFO, "UserDesignation is not null. drow[UserId] = " + drow["UserId"] + " and Userid=" + UserId + ". drow[UserDesignation] = " + drow["UserDesignation"] + " and Designation = " + Designation + " WebsiteName = " + drow["WebsiteName"] + "", "rizwan");
                    }
                }

                gaw.websiteurl = website;
                gaw.response = true;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, gaw);

                qry = "delete from MDM_PushNotification where DeviceID='" + pm.uuid + "' and Command='Get Accessible Website'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                return response;
            }
            else
            {
                ar = new WebApiResponse();
                ar.errorCode = "Authentication failed";
                ar.response = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch(Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, "Problem in getAccessibleWebsites function."+ex.Message+"",null);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return null;
    }
    /// <summary>
    ///To Update the Device Location status to admin
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage updateDeviceLocation(DeviceLocation DL)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + DL.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                    dr.Close();

                DeviceTrackingDetail DT = new DeviceTrackingDetail();

                var list = DL.locations;
                foreach (var c in list)
                {
                    qry = "insert into MDM_DeviceTrackingDetail(DeviceId,latitude,longitude,CreatedDate)values('" + DL.uuid + "','" + c.latitude + "','" + c.longitude + "','" + c.timestamp.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                    rcnt = databaseHelper.ExecuteQuery(qry);
                }
                ar.response = true;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ar);

                qry = "delete from MDM_PushNotification where DeviceID='" + DL.uuid + "' and Command='GetDeviceLocation'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                return response;
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch(Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message,null);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return null;
    }
    /// <summary>
    ///To Update the device Lock Status (Lock/unlock)
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage updateDeviceLockStatus(DeviceLock DL)
    {
        ar = new WebApiResponse();
        try
        {

            string qry = "select * from MDM_DeviceMaster where DeviceID='" + DL.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                    dr.Close();

                qry = "delete from MDM_PushNotification where DeviceID='" + DL.uuid + "'";
                string qry1 = "update MDM_DeviceMaster set";
                if (DL.status == false)//successfully unlocked
                {
                    // SendSmsOrMail(DL.uuid); //to inform that device is unlocked
                    qry += " and Command ='Unlocked'";
                    qry1 += " Status=2 ";
                }
                else if (DL.status == true)//successfully locked
                {
                    // SendLockDeviceDetails(DL.uuid);//To send unlock details of locked device by sms/email
                    qry += " and Command ='Locked'";
                    qry1 += " Status=1 ";
                }
                rcnt = databaseHelper.ExecuteQuery(qry);
                qry1 += " where DeviceID='" + DL.uuid + "'";
                rcnt = databaseHelper.ExecuteQuery(qry1);
                ar.response = true;
                response = Request.CreateResponse(HttpStatusCode.Created, ar);
                return response;
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response = false;
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);
            ar.errorCode = "Device Lock Status Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }
    /// <summary>
    ///Process Remotely Un-installed Apk
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage ProcessRemoteUnInstall(RemoteUninstall RU)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + RU.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                    dr.Close();

                qry = "delete from MDM_PushNotification where DeviceID='" + RU.uuid + "' and Command like '%Remote Uninstall%'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                qry = "delete from MDM_InstalledApps where DeviceID='" + RU.uuid + "' and isDownloaded=1 and ApplicationPackage='" + RU.packageName + "'";

                //linfo.LogException(null,"Process Remote Uninstall Delete Qry = "+qry);
                rcnt = databaseHelper.ExecuteQuery(qry);

                ar.response = true;
                response = Request.CreateResponse(HttpStatusCode.Created, ar);
                return response;
            }
            else
            {
                ar.errorCode = "No Device Found";
                ar.response = false;
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, "Problem in ProcessRemoteUninstall()",null);
            ar.errorCode = "WebService Exception in function ProcessRemoteUninstall()";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }
    /// <summary>
    ///Process The Received Gps Status from the device.
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage ProcessGPSStatus(SortedList<string, string> pm)
    {
        ar = new WebApiResponse();
        try
        {

            if (pm.ContainsKey("uuid"))
            {
                string qry = "select * from MDM_DeviceMaster where DeviceID='" + pm["uuid"] + "'";
                dr = databaseHelper.getDataReader(qry);

                if (dr.Read())
                {
                    if (!dr.IsClosed)
                        dr.Close();

                    if (pm.ContainsKey("gpsStatus"))
                    {
                        qry = "Update MDM_DeviceMaster set GPSStatus=" + pm["gpsStatus"] + " where DeviceID='" + pm["uuid"] + "'";
                        rcnt = databaseHelper.ExecuteQuery(qry);
                    }

                    qry = "delete from MDM_PushNotification where DeviceID='" + pm["uuid"] + "' and Command like '%Get GPS Status%'";
                    rcnt = databaseHelper.ExecuteQuery(qry);

                    ar.response = true;
                    response = Request.CreateResponse(HttpStatusCode.Created, ar);
                    return response;
                }
                else
                {
                    ar.errorCode = "No Such Device Found";
                    ar.response = false;
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                    return response;
                }
            }
            else
            {
                ar.errorCode = "uuid is empty";
                ar.response = false;
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            ar.errorCode = "GPS Status Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }
    /// <summary>
    ///Process The Remotely Enabled GPS. A webservice which is called after the gps of the selected
    ///devices are enabled
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage ProcessRemotelyEnableGPS(postmethod pm)
    {
        ar = new WebApiResponse();        
        string qry = "select * from MDM_DeviceMaster where DeviceID='" + pm.uuid + "'";
        dr = databaseHelper.getDataReader(qry);
        try
        {

            if (dr.Read())
            {
                if (!dr.IsClosed)
                    dr.Close();

                qry = "update MDM_DeviceMaster set GPSStatus=1 where DeviceID='" + pm.uuid + "'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                qry = "delete from MDM_PushNotification where DeviceID='" + pm.uuid + "' and Command like '%Remotely Enable GPS%'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                ar.response = true;
                response = Request.CreateResponse(HttpStatusCode.Created, ar);
                return response;
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response = false;
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch(Exception ex)
        {
            ar.errorCode = "Remote Enable GPS Failed";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return response;
    }