Ejemplo n.º 1
0
        public IHttpActionResult GetKGPCategorySubCategoryWiseDataV2(KitchenGardenEntity objkgpList)
        {
            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }

                ReasonStatusBal _rsbal = new ReasonStatusBal();
                // DataSet ds1 = new DataSet();
                var ds1 = _rsbal.GetKGPCategorySubCategoryWiseData(objkgpList, x_StateName, x_DistrictName);
                ds1.Tables[0].TableName = "Product";
                ds1.Tables[1].TableName = "Count";
                return(Ok(new { ProductsApiReponse = ds1, Status = true }));
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { ProductsApiReponse = "", Status = false }));
            }
        }
        public CreatedOrderResult OrderCreateV2(OrderCreateModel obj)
        {
            ReasonStatusBal    _rsbal             = new ReasonStatusBal();
            CreatedOrderResult objCreateOrderData = new CreatedOrderResult();
            int flag = 0;
            Dictionary <string, int> returndata = new Dictionary <string, int>();

            returndata.Add("status", 0);

            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }
                objCreateOrderData = _rsbal.OrderCreateV2(obj, x_StateName, x_DistrictName);
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, obj.userid);
            }

            // string json = JsonConvert.SerializeObject(returndata);
            //HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
            //HttpContext.Current.Response.Write(json);
            return(objCreateOrderData);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Method to generate a DB Connection from HTTP Request
        /// </summary>
        /// <param name="apiRequest"></param>
        /// <returns></returns>
        public static IDbConnection Connect(System.Net.Http.Headers.HttpRequestHeaders apiRequest)
        {
            string hdbKey, userKey, passKey;

            if (apiRequest.Contains("api_hdb") && apiRequest.Contains("api_user") && apiRequest.Contains("api_pass"))
            {
                hdbKey  = apiRequest.GetValues("api_hdb").AsList <string>()[0];
                userKey = apiRequest.GetValues("api_user").AsList <string>()[0];
                passKey = apiRequest.GetValues("api_pass").AsList <string>()[0];
            }
            else
            {
                throw new KeyNotFoundException("HTTP Request Header Keys missing. Refer to the API guide for proper formatting of the API Request.");
            }

            // Log-in
            System.Data.IDbConnection db;
            if (hdbKey.ToLower() == "pnhyd" || hdbKey.ToLower() == "gphyd")
            {
                db = null;
            }
            else
            {
                db = Connect(hdbKey, userKey, passKey);
            }

            // Check ref_user_groups
            //string sqlString = "select * from ref_user_groups where lower(user_name) = '" + userKey + "'";

            return(db);
        }
        public IHttpActionResult GetCartItems(string version, string UserId)
        {
            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }
                DataSet ds = new DataSet();
                ds = BzWebsite.GetCartItems(version, x_StateName, x_DistrictName, UserId);

                ds.Tables[0].TableName = "Items";

                return(Ok(new { CartApiReponse = ds, ItemCount = ds.Tables[1].Rows[0]["ItemCount"].ToString(), Status = true }));
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { CartApiReponse = "", Status = false }));
            }
        }
        public IHttpActionResult GetHumTumOffer(string version)
        {
            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }
                DataSet ds = new DataSet();
                ds = LiveStocks.GetHumTumOffer(version, x_StateName, x_DistrictName);

                //ds.Tables[0].TableName = "TrendsProducts";Product,ProductsApiReponse
                ds.Tables[0].TableName = "Product";
                //return Ok(new { TrendsProductsApiReponse = ds, Status = true });
                return(Ok(new { ProductsApiReponse = ds, Status = true }));
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { ProductsApiReponse = "", Status = false }));
            }
        }
        public IHttpActionResult GetBzAppActiveBrands(string version)
        {
            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }
                DataSet ds = new DataSet();
                ds = BzCatagory.ActiveBrands(version, x_StateName, x_DistrictName);

                ds.Tables[0].TableName = "BZActiveBrands";
                return(Ok(new { BZBrands = ds, Status = true }));
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { BZBrands = "", Status = false }));
            }
        }
        // GET api/values
        public IEnumerable <string> Get()
        {
            ProcessClientCertificate pCert = new ProcessClientCertificate();

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            List <string> lst = new List <string>();

            foreach (var header in headers)
            {
                if (headers.Contains(header.Key))
                {
                    string token = headers.GetValues(header.Key).First();
                    if (!string.IsNullOrEmpty(token))
                    {
                        lst.Add(header.Key + " : " + token);
                    }
                }

                else
                {
                    lst.Add(header.Key + " : No value ");
                }
            }

            if (headers.Contains("X-ARR-ClientCert"))
            {
                string           token = headers.GetValues("X-ARR-ClientCert").First();
                X509Certificate2 cert  = pCert.GetClientCertificateFromHeader(token);
                return(new string[] { cert.Thumbprint, cert.Issuer });
            }

            return(lst.ToArray <string>()); //new string[] { "value1", "value2" };
        }
        public async Task <HttpResponseMessage> PostMatchedDataFiles([FromBody] DataMatchUploadRequestBody UploadedFile)
        {
            var result  = new List <ValidationResult>();
            var context = new ValidationContext(UploadedFile, null, null);

            if (!(!Validator.TryValidateProperty(UploadedFile, new ValidationContext(UploadedFile, null, null), result) ||
                  !Validator.TryValidateProperty(UploadedFile.requestheader, new ValidationContext(UploadedFile.requestheader, null, null), result) ||
                  !Validator.TryValidateProperty(UploadedFile.requestdetail, new ValidationContext(UploadedFile.requestdetail, null, null), result)
                  ))
            {
                DataMatchUploadResponse _response = new DataMatchUploadResponse();
                _response.statusCode       = 500;
                _response.errorExplanation = result[0].ErrorMessage;
                return(GenerateResponse(_response));
            }

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string businessId = string.Empty;
            string fileId     = string.Empty;

            if (headers.Contains("businessId"))
            {
                businessId = headers.GetValues("businessId").FirstOrDefault();
            }
            if (headers.Contains("businessId"))
            {
                fileId = headers.GetValues("fileId").FirstOrDefault();
            }
            return(GenerateResponse(await _dataMatchUploadResponse.UploadDataMatchFile(UploadedFile, businessId, fileId)));
        }
        public IHttpActionResult BZFarmerAppServices(string version)
        {
            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }
                DataSet ds = new DataSet();
                ds = LiveStocks.AppServices(version, x_StateName, x_DistrictName);
                if (ds.Tables.Count > 0)
                {
                    List <dynamic> objlist = new List <dynamic>();
                    if (ds.Tables.Count > 2)
                    {
                        ds.Tables[0].TableName = "BZFarmerAppServices";
                        ds.Tables[1].TableName = "District";
                        ds.Tables[2].TableName = "State";
                        var Location = new
                        {
                            DistrictId = ds.Tables[1].Rows[0]["DistrictId"],
                            StateId    = ds.Tables[2].Rows[0]["State"]
                        };
                        objlist.Add(Location);
                    }
                    else
                    {
                        var Location = new
                        {
                            DistrictId = "",
                            StateId    = ""
                        };
                        objlist.Add(Location);
                    }
                    DataSet ds1 = new DataSet();
                    ds.Tables[0].TableName = "BZFarmerAppServices";
                    ds1.Tables.Add(ds.Tables[0].Copy());

                    return(Ok(new { BZApiReponse = ds1, Location = objlist, Status = true }));
                }
                else
                {
                    return(Ok(new { BZApiReponse = "", Msg = "Jankari", Status = false }));
                }
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { BZApiReponse = "", Msg = "Jankari", Status = false }));
            }
        }
Ejemplo n.º 10
0
        // POST api/<controller>
        //public void Post([FromBody]string message)
        public void Post([FromBody] JObject value)
        {
            string Id      = value["Id"].ToString();
            string message = value["Message"].ToString();


            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string token = string.Empty;
            string pwd   = string.Empty;

            if (headers.Contains("username"))
            {
                token = headers.GetValues("username").First();
            }
            if (headers.Contains("password"))
            {
                pwd = headers.GetValues("password").First();
            }
            //to do check and authenticate
            //code to authenticate and return some thing

            var request = Request;

            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                var ctx = request.Properties["MS_HttpContext"] as HttpContextWrapper;
                if (ctx != null)
                {
                    var ip = ctx.Request.UserHostAddress;

                    //to do check from config and authenticate
                }
            }
            MessageDetails msg = new MessageDetails();
            //new IMIchatHub().BoardcastToAgent(teamId, message);

            var context = GlobalHost.ConnectionManager.GetHubContext <IMIchatHub>();

            // context.Clients.All.Send("Admin", "stop the chat");
            context.Clients.All.addChatMessage(message);
            var ConnectedUsers = IMIchatHub.ConnectedUsers;
            //  string fromUserId = Context.ConnectionId;

            var toUser = ConnectedUsers.FirstOrDefault(x => x.connectionId == Id);

            // var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);

            if (toUser != null)
            {
                // send to
                context.Clients.Client(toUser.connectionId).sendPrivateMessage(message);

                // send to caller user
                // Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserId, message);
            }
        }
        [HttpPost] //Always explicitly state the accepted HTTP method
        public IHttpActionResult Div([FromBody] RootDivRequest rootRequest)
        {
            double           remainder    = 0;
            ContextOperation context      = new ContextOperation();
            RootDivResponse  rootResponse = new RootDivResponse()
            {
                Quotient  = context.Division(rootRequest.Dividend, rootRequest.Divisor, out remainder),
                Remainder = remainder
            };


            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string XEviTrackingId = string.Empty;

            if (headers.Contains("XEviTrackingId"))
            {
                XEviTrackingId = headers.GetValues("XEviTrackingId").FirstOrDefault();


                OperationDTO operation = new OperationDTO()
                {
                    Calculation = (rootRequest.Dividend + context.BinaryOperationStrategy.OperatorCode + rootRequest.Divisor) + "=" + rootResponse.Quotient,
                    Id          = XEviTrackingId,
                    Date        = DateTime.Now,
                    Operation   = context.BinaryOperationStrategy.Name
                };
                this.journalDBOperations.PersistOperation(operation);
            }


            return(Ok(rootResponse));
        }
Ejemplo n.º 12
0
        public static ErrorResponse TeleyumaLogin(System.Net.Http.Headers.HttpRequestHeaders headers)
        {
            return(new ErrorDictionary().Errors.First(x => x.ErrorType == Diccionario.errors.NoError));

            string apiKey = null;

            if (headers.Contains("apiKey"))
            {
                apiKey = headers.GetValues("apiKey").First();
            }
            if (string.IsNullOrEmpty(apiKey))
            {
                return(apiKeyNull());
            }

            try
            {
                var users = db.Credenciales.Where(x => x.Proveedor == "teleyuma").ToList();
                var keys  = users.Where(x => x.KeyGenerate == apiKey);

                if (keys.Any())
                {
                    return(new ErrorDictionary().Errors.First(x => x.ErrorType == Diccionario.errors.NoError));
                }
                else
                {
                    return(new ErrorDictionary().Errors.First(x => x.ErrorCode == 1));
                }
            }
            catch
            {
                return(new ErrorDictionary().Errors.First(x => x.ErrorType == Diccionario.errors.KeyError));
            }
        }
        [HttpPost] //Always explicitly state the accepted HTTP method
        public IHttpActionResult Mult([FromBody] RootMultRequest rootRequest)
        {
            ContextOperation context      = new ContextOperation();
            RootMultResponse rootResponse = new RootMultResponse()
            {
                Product = context.Multiply(rootRequest.Factors)
            };

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string XEviTrackingId = string.Empty;

            if (headers.Contains("XEviTrackingId"))
            {
                XEviTrackingId = headers.GetValues("XEviTrackingId").FirstOrDefault();

                OperationDTO operation = new OperationDTO()
                {
                    Calculation = String.Join(context.MultipleArgsOperationStrategy.OperatorCode, rootRequest.Factors) + "=" + rootResponse.Product,
                    Id          = XEviTrackingId,
                    Date        = DateTime.Now,
                    Operation   = context.MultipleArgsOperationStrategy.Name
                };

                this.journalDBOperations.PersistOperation(operation);
            }

            return(Ok(rootResponse));
        }
Ejemplo n.º 14
0
        public async Task <IHttpActionResult> Create(invoiceDetailListDTO newDTO)
        {
            sapi.db db = new sapi.db();
            try
            {
                db.connect();
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                string token = "";
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                if (headers.Contains("token"))
                {
                    foreach (var s in headers.GetValues("token"))
                    {
                        token = s;
                    }
                }
                return(Ok(await xcrm.UploadInvoice(db, newDTO, token)));
                //return Ok(await repository.Create(saleOrderItem, token));
            }
            catch (HttpException ex)
            {
                return(BadRequest(ex.Message));
            }
            finally
            {
                db.close();
            }
        }
        [HttpPost] //Always explicitly state the accepted HTTP method
        public IHttpActionResult Sub([FromBody] RootSubRequest rootRequest)
        {
            ContextOperation context      = new ContextOperation();
            RootSubResponse  rootResponse = new RootSubResponse()
            {
                Difference = context.Diff(rootRequest.Minuend, rootRequest.Subtrahend)
            };


            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string XEviTrackingId = string.Empty;

            if (headers.Contains("XEviTrackingId"))
            {
                XEviTrackingId = headers.GetValues("XEviTrackingId").FirstOrDefault();


                OperationDTO operation = new OperationDTO()
                {
                    Calculation = (rootRequest.Minuend + context.BinaryOperationStrategy.OperatorCode + rootRequest.Subtrahend) + "=" + rootResponse.Difference,
                    Id          = XEviTrackingId,
                    Date        = DateTime.Now,
                    Operation   = context.BinaryOperationStrategy.Name
                };
                this.journalDBOperations.PersistOperation(operation);
            }

            return(Ok(rootResponse));
        }
        [HttpPost] //Always explicitly state the accepted HTTP method
        public IHttpActionResult Sqrt([FromBody] RootSqrtRequest rootRequest)
        {
            ContextOperation context      = new ContextOperation();
            RootSqrtResponse rootResponse = new RootSqrtResponse()
            {
                Square = context.Square(rootRequest.Number),
            };

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string XEviTrackingId = string.Empty;

            if (headers.Contains("XEviTrackingId"))
            {
                XEviTrackingId = headers.GetValues("XEviTrackingId").FirstOrDefault();

                OperationDTO operation = new OperationDTO()
                {
                    Calculation = (context.UnaryOperationStrategy.OperatorCode + rootRequest.Number) + "=" + rootResponse.Square,
                    Id          = XEviTrackingId,
                    Date        = DateTime.Now,
                    Operation   = context.UnaryOperationStrategy.Name
                };
                this.journalDBOperations.PersistOperation(operation);
            }

            return(Ok(rootResponse));
        }
        public IHttpActionResult GetSubCategory(string version, int?CategoryId)
        {
            try
            {
                #region Authentication Token
                //System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                //string token = string.Empty;
                //string pwd = string.Empty;
                //if (headers.Contains("username"))
                //{
                //    token = headers.GetValues("username").First();
                //}
                //if (headers.Contains("password"))
                //{
                //    pwd = headers.GetValues("password").First();
                //}
                #endregion

                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("x_StateName"))
                {
                    x_StateName = headers.GetValues("x_StateName").First();
                }
                if (headers.Contains("x_DistrictName"))
                {
                    x_DistrictName = headers.GetValues("x_DistrictName").First();
                }
                DataSet ds1 = new DataSet();
                //if (CategoryId == 2)
                //{
                //    ds1 = LiveStocks.GetCropDetails(version, CategoryId);
                //}
                //else
                //{
                ds1 = LiveStocks.GetSubCategories(version, CategoryId, true, x_StateName, x_DistrictName);
                //}
                ds1.Tables[0].TableName = "SubCategory";
                return(Ok(new { ProductsApiReponse = ds1, Status = true }));
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { ProductsApiReponse = "", Status = false }));
            }
        }
Ejemplo n.º 18
0
 public static string GetCultureInfo(System.Net.Http.Headers.HttpRequestHeaders headers)
 {
     if (!headers.Contains("Culture-Info"))
     {
         return(null);
     }
     return(headers.GetValues("Culture-Info").FirstOrDefault());
 }
Ejemplo n.º 19
0
        public IHttpActionResult GenerateAccessToken()
        {
            string bearerAuth = string.Empty;
            string grantType  = string.Empty;

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            if (headers.Contains("Authorization"))
            {
                bearerAuth = headers.GetValues("Authorization").First();
                if (!IsBearerValid(bearerAuth))
                {
                    return(Unauthorized());
                }
                ;
            }
            else
            {
                return(Unauthorized());
            }
            if (headers.Contains("Grant-type"))
            {
                grantType = headers.GetValues("Grant-type").First();
                if (!grantType.Equals("client_credentials"))
                {
                    return(Unauthorized());
                }
                ;
            }
            else
            {
                return(Unauthorized());
            }

            var response = NameEnquiryLogic.GenerateToken();

            if (response != null)
            {
                return(Ok(response));
            }
            else
            {
                return(NotFound());
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Permet de retourner la valeur à part de header de request.
        /// </summary>
        /// <param name="request"><seealso cref="HttpRequestMessage"/></param>
        /// <param name="key">le clé</param>
        /// <returns></returns>
        public static string GetHeaderValue(HttpRequestMessage request, string key)
        {
            System.Net.Http.Headers.HttpRequestHeaders headers = request.Headers;

            if (headers.Contains(key))
            {
                return(headers.GetValues(key).FirstOrDefault());
            }

            return("");
        }
        public IHttpActionResult GetProductsBySearch(string version, string SearchText)
        {
            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }

                DataSet ds  = new DataSet();
                DataSet ds1 = new DataSet();
                ds = LiveStocks.GetProductsBySearch(version, x_StateName, x_DistrictName, SearchText);

                ds.Tables[0].TableName = "Product";
                var     productData  = ds.Tables[0].AsEnumerable();
                var     distinctData = productData.Select(x => x.Field <string>("ProductHindiName")).Distinct();
                DataSet ds2          = new DataSet();
                ds2.Tables.Add(ds.Tables[0].Copy());
                //ds2.Tables.Add(ds1.Tables[0].Copy());
                if (ds2.Tables[0].Rows.Count > 0)
                {
                    return(Ok(new { ProductsApiReponse = ds2, Status = true }));
                }
                else
                {
                    return(Ok(new { ProductsApiReponse = "", Status = false }));
                }
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, 0);
                return(Ok(new { ProductsApiReponse = "", Status = false }));
            }
        }
Ejemplo n.º 22
0
        public IHttpActionResult DoDebit(DebitRequest req)
        {
            string bearerAccessToken = string.Empty;
            string signature         = string.Empty;

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            if (headers.Contains("Authorization"))
            {
                bearerAccessToken = headers.GetValues("Authorization").First();
                if (!bearerAccessToken.Trim().StartsWith("Bearer "))
                {
                    return(Unauthorized());
                }
                ;
                if (!Utils.IsAccessTokenValid(bearerAccessToken.Replace("Bearer ", "")))
                {
                    return(Unauthorized());
                }
                ;
            }
            else
            {
                return(Unauthorized());
            }
            if (headers.Contains("signature"))
            {
                signature = headers.GetValues("signature").First();
                if (!IsSignatureValid(signature, req))
                {
                    return(Unauthorized());
                }
                ;
            }
            else
            {
                return(Unauthorized());
            }
            var response = NameEnquiryLogic.DoDebit(req);

            return(Ok(response));
        }
Ejemplo n.º 23
0
        /**
         * Helper function. Returns Time To Live value for a document according to either the value
         * in seconds corresponding to custom header "Custom-Ttl" or, if no such header exists, a
         * default value of 30 seconds.
         *
         * returns:
         *  int
         *      - Time To Live value to be passed to repository .Add and .Get function parameters.
         */
        private int GetTimeToLive()
        {
            int TimeToLive = 30;

            System.Net.Http.Headers.HttpRequestHeaders headers = Request.Headers;
            if (headers.Contains("Custom-Ttl"))
            {
                String customTtl = headers.GetValues("Custom-Ttl").First();
                TimeToLive = Convert.ToInt32(customTtl);
            }
            return(TimeToLive);
        }
Ejemplo n.º 24
0
        public IHttpActionResult DeleteCSUser(int id)
        {
            // sm ------ start
            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;

            if (!headers.Contains("secretkey") || (headers.Contains("secretkey") &&
                                                   headers.GetValues("secretkey").First() != "secret"))
            {
                // return Unauthorized();  this does not work as response.IsSuccessStatusCode==true  (why????).
                //  return NotFound();
                return(BadRequest());
            }
            // sm end

            CSUser csUser = repository.GetCSUserByID(id);

            if (csUser == null)
            {
                return(NotFound());
            }
            repository.DeleteCSUser(csUser);
            return(Ok(csUser));
        }
Ejemplo n.º 25
0
        public async Task <IHttpActionResult> GetDetail(int id, [FromUri] int currentPage, [FromUri] string search)
        {
            string token = "";

            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            if (headers.Contains("token"))
            {
                foreach (var s in headers.GetValues("token"))
                {
                    token = s;
                }
            }
            return(Ok(await repository.GetList(id, currentPage, token, search)));
        }
Ejemplo n.º 26
0
        public IHttpActionResult Get(int id)
        {
            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            string token = string.Empty;
            string pwd   = string.Empty;

            if (headers.Contains("username"))
            {
                token = headers.GetValues("username").First();
            }
            if (headers.Contains("password"))
            {
                pwd = headers.GetValues("password").First();
            }
            //code to authenticate and return some thing
            int userId = _userService.GetByUserNameAndPassword(token, pwd).Id;


            if (userId == 0)
            {
                return(NotFound());
            }
            return(Ok(userId));
        }
Ejemplo n.º 27
0
        public AddProjectResponse AddProject(string partnerName, ProjectDTO projectDTO)
        {
            int userIdentifier, userId = -1;

            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;

                if (headers.Contains("user-identifier") && int.TryParse(headers.GetValues("user-identifier").First(), out userIdentifier))
                {
                    userId = (userIdentifier > 0) ? userIdentifier : -1;
                }
            }
            catch {
                userId = -1;
            }

            // add project inot DB
            return(new Facade.ProjectFacade().AddProject(partnerName, userId, projectDTO));
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Copies headers from one <see cref="System.Net.Http.HttpRequestMessage"/> instance to another.
        /// </summary>
        /// <param name="source">The source <see cref="System.Net.Http.HttpRequestMessage"/> to copy from.</param>
        /// <param name="destination">The destination <see cref="System.Net.Http.HttpRequestMessage"/> to copy to.</param>
        public static void CopyHeadersTo(this System.Net.Http.Headers.HttpRequestHeaders source, System.Net.Http.Headers.HttpRequestHeaders destination)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            foreach (var header in source)
            {
                if (destination.Contains(header.Key))
                {
                    destination.Remove(header.Key);
                }

                destination.Add(header.Key, header.Value);
            }
        }
Ejemplo n.º 29
0
        private IApiResult VerificationHeaders(System.Net.Http.Headers.HttpRequestHeaders headers)
        {
            if (!headers.Contains("Authorization"))
            {
                return(new IApiResult()
                {
                    code = Interface.StatusCode.accreditation, message = "Lack of authentication parameters.", result = new { a = "a" }
                });
            }
            string authorization = string.Join("", headers.GetValues("Authorization")); // 格式: Authorization@地图类型

            string[] arr  = authorization.Split('@');
            string[] keys = new string[] { "MGOO", "CARRENT" };
            authorization = arr[0];
            if (!keys.Contains(authorization) || arr.Length != 2)
            {
                return(new IApiResult()
                {
                    code = Interface.StatusCode.accreditation, message = "Authentication failure."
                });
            }

            return(null);
        }
        //// GET: api/Users
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}

        // GET: api/Users/5
        public List <Person> Get(int id)
        {
            System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
            DBManage      MyDBManager = new DBManage();
            SqlCommand    Command     = null;
            SqlDataReader Reader      = null;
            List <Person> Person      = new List <Person>();
            string        SqlString   = string.Empty;
            int           RecsAff     = 0;

            SqlString = "i_tefteri_sp_Get_Active_Users";
            MyDBManager.CommandTimeOut = 30;
            MyDBManager.ConStr         = Constr();
            if (id == -1)
            {
                try
                {
                    if (headers.Contains("Currentuser"))
                    {
                        string user = headers.GetValues("Currentuser").First();
                    }
                    MyDBManager.ConOpen();
                    Command             = new SqlCommand();
                    Command.CommandText = SqlString;
                    Command.CommandType = System.Data.CommandType.StoredProcedure;
                    Command.Parameters.Add("@What2Do", SqlDbType.VarChar, 50);
                    //Command.Parameters.Add("@Mobile_Num", SqlDbType.VarChar, 12);
                    Command.Parameters["@What2Do"].Value = "All Person";
                    //Command.Parameters["@Mobile_Num"].Value = id;
                    Reader = MyDBManager.ExecuteReader(Command);

                    while (Reader.Read())
                    {
                        Person MyPerson = new Person();
                        MyPerson.UserID        = Convert.ToInt32(Reader["UserID"]);
                        MyPerson.iBankuserID   = Reader["iBankuserID"].ToString();
                        MyPerson.BASIKOS_LOGAR = Reader["BASIKOS_LOGAR"].ToString();
                        Person.Add(MyPerson);
                        MyPerson = null;
                    }
                    Reader.Close();
                    Reader  = null;
                    Command = null;
                    Write2LogFile(MyDBManager, "Controller=Users, " + "Get ALL Active Users", 1);
                    MyDBManager.ConClose();
                    MyDBManager = null;
                    //var jsonSerialiser = new JavaScriptSerializer();
                    //var json = jsonSerialiser.Serialize(Person);
                    return(Person);//JsonConvert.SerializeObject(Person);
                }
                catch (Exception ex)
                {
                    Person MyPerson = new Person();
                    RecsAff = Write2LogFile(MyDBManager, "Controller=Users, " + "Error: " + ex.Message, 1);
                    MyDBManager.ConClose();
                    MyDBManager          = null;
                    MyPerson.iBankuserID = "Error";
                    Person.Add(MyPerson);
                    return(Person);
                }
            }
            else
            {
                try
                {
                    string Currentuser = string.Empty;
                    if (headers.Contains("Currentuser"))
                    {
                        Currentuser = headers.GetValues("Currentuser").First();
                    }
                    MyDBManager.ConOpen();
                    Command             = new SqlCommand();
                    Command.CommandText = SqlString;
                    Command.CommandType = System.Data.CommandType.StoredProcedure;
                    Command.Parameters.Add("@What2Do", SqlDbType.VarChar, 50);
                    //Command.Parameters.Add("@Mobile_Num", SqlDbType.VarChar, 12);
                    Command.Parameters["@What2Do"].Value = Currentuser;
                    //Command.Parameters["@Mobile_Num"].Value = id;
                    Reader = MyDBManager.ExecuteReader(Command);

                    while (Reader.Read())
                    {
                        Person MyPerson = new Person();
                        MyPerson.UserID        = Convert.ToInt32(Reader["UserID"]);
                        MyPerson.iBankuserID   = Reader["iBankuserID"].ToString();
                        MyPerson.BASIKOS_LOGAR = Reader["BASIKOS_LOGAR"].ToString();
                        Person.Add(MyPerson);
                        MyPerson = null;
                    }
                    Reader.Close();
                    Reader  = null;
                    Command = null;
                    Write2LogFile(MyDBManager, "Controller=Users, " + "Get 1 Active Users", 1);
                    MyDBManager.ConClose();
                    MyDBManager = null;
                    //var jsonSerialiser = new JavaScriptSerializer();
                    //var json = jsonSerialiser.Serialize(Person);
                    return(Person);//JsonConvert.SerializeObject(Person);
                }
                catch (Exception ex)
                {
                    Person MyPerson = new Person();
                    RecsAff = Write2LogFile(MyDBManager, "Controller=Users, " + "Error: " + ex.Message, 1);
                    MyDBManager.ConClose();
                    MyDBManager          = null;
                    MyPerson.iBankuserID = "Error";
                    Person.Add(MyPerson);
                    return(Person);
                }
            }
        }