Beispiel #1
0
        public virtual async Task <JsonResult> CreatePopup(T item)
        {
            var r = new JsonResultViewModel();

            if (!OnCreateAuthCheck())
            {
                r.Error = "FORBIDDEN";
                return(Json(r));
            }
            try
            {
                OnCreateSaveItem(item);
                if (OnCreateSaveCheck(item))
                {
                    if (await Repo.CreateAsync(item))
                    {
                        OnAfterCreateSaveItem(item);
                        r.Ok = true;
                        if (!CreateJsAction.IsEmpty())
                        {
                            r.JsFunction = CreateJsAction;
                        }
                    }
                    else
                    {
                        r.Error = MvcLogger.GetErrorMessage(ModelState);
                    }
                }
            }
            catch (Exception ex)
            {
                r.Error = MvcLogger.GetErrorMessage(ex);
            }
            return(Json(r));
        }
        public virtual async Task <JsonResult> EditPopup(T item)
        {
            var r            = new JsonResultViewModel();
            var keyFieldName = Digger2.GetKeyFieldNameFirst(typeof(T));
            var v            = Digger.GetObjectValue(item, keyFieldName);

            if (v != null)
            {
                int.TryParse(v.ToString(), out _editId);
                if (_editId > 0)
                {
                    var org = Repo.GetItem(_editId);
                    var x   = await TryUpdateModelAsync(org);

                    OnEditSaveItem(org);
                    if (Repo.Edit(org))
                    {
                        r.Ok = true;
                        if (!EditJsAction.IsEmpty())
                        {
                            r.JsFunction = EditJsAction;
                        }
                    }
                    else
                    {
                        r.Error = MvcLogger.GetErrorMessage(ModelState);
                    }
                }
            }
            else
            {
                r.Error = "NOT FOUND";
            }
            return(Json(r));
        }
        // POST api/values
        public object Post()
        {
            JsonResultViewModel result = new JsonResultViewModel();

            result.status      = true;
            result.message     = "Coupon successfully claimed";
            result.messageCode = "S";

            var    httpRequest = HttpContext.Current.Request;
            long   id          = string.IsNullOrEmpty(httpRequest["msCouponId"]) ? 0 : long.Parse(httpRequest["msCouponId"]);
            string userId      = httpRequest["UserId"];


            try
            {
                using (PatuhEntities db = new PatuhEntities())
                {
                    MsCoupon msCoupon = db.MsCoupons.Where(x => x.Id == id).FirstOrDefault();

                    TrUserCoupon userCoupon = db.TrUserCoupons.Where(x => x.MsCouponId == id).FirstOrDefault();

                    if (userCoupon == null)
                    {
                        userCoupon            = new TrUserCoupon();
                        userCoupon.MsCouponId = id;
                        userCoupon.UserID     = userId;
                        userCoupon.cCreated   = userId;
                        userCoupon.dCreated   = DateTime.Now;
                        db.TrUserCoupons.AddObject(userCoupon);
                    }

                    userCoupon.cStatus = "Y";

                    /*
                     * if (httpRequest.Files.Count > 0)
                     *  {
                     *
                     *      foreach (string file in httpRequest.Files)
                     *      {
                     *          var postedFile = httpRequest.Files[file];
                     *          Type fileType = postedFile.GetType();
                     *          byte[] couponImage = new byte[postedFile.ContentLength];
                     *
                     *          postedFile.InputStream.Read(couponImage, 0, postedFile.ContentLength);
                     *          userCoupon.c
                     *      }
                     */
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.status      = false;
                result.message     = e.Message;
                result.messageCode = "Error in claiming Coupon";
            }

            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// Returns the standard JSON response model indicating success, along with optionally the model specified as the data.
        /// </summary>
        public JsonNetResult JsonSuccess(object model = null)
        {
            var standardModel = new JsonResultViewModel
            {
                Success = true,
                Data    = model
            };

            return(JsonNetResult.New(standardModel));
        }
Beispiel #5
0
        /// <summary>
        /// Returns the standard JSON response model indicating failure, copying any ModelState errors to the Messages collection.
        /// </summary>
        public JsonNetResult JsonFailure()
        {
            IEnumerable <UiMessageViewModel> messages = ModelState.GetErrorUiMessages();

            var standardModel = new JsonResultViewModel
            {
                Success  = false,
                Messages = new List <UiMessageViewModel>(messages)
            };

            return(JsonNetResult.New(standardModel));
        }
Beispiel #6
0
        // POST api/values

        public object Post([FromBody] ArticleReportViewModel trArticleReport)
        {
            JsonResultViewModel result = new JsonResultViewModel();

            result.status      = true;
            result.message     = "Article successfully reported";
            result.messageCode = "S";

            var httpRequest = HttpContext.Current.Request;

            try
            {
                using (PatuhEntities db = new PatuhEntities())
                {
                    IList <TrArticleReport> articleReports = db.TrArticleReports.Where(x => x.ArticleId == trArticleReport.ArticleId && x.cCreated == trArticleReport.cCreated).ToList();
                    TrArticleReport         articleReport;

                    if (articleReports == null || articleReports.Count == 0)
                    {
                        articleReport                = new TrArticleReport();
                        articleReport.ArticleId      = trArticleReport.ArticleId;
                        articleReport.ReportCategory = trArticleReport.ReportCategory;
                        articleReport.ReportDesc     = trArticleReport.ReportDesc;
                        articleReport.cStatus        = trArticleReport.cStatus;
                        articleReport.cCreated       = trArticleReport.cCreated;
                        articleReport.dCreated       = DateTime.Now;
                        db.TrArticleReports.AddObject(articleReport);
                    }
                    else
                    {
                        articleReport = articleReports.FirstOrDefault();
                    }

                    articleReport.cLastUpdated = trArticleReport.cLastUpdated;
                    articleReport.dLastUpdated = DateTime.Now;

                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.status      = false;
                result.message     = e.Message;
                result.messageCode = "Error in reporting Article";
            }

            return(result);
        }
        public JsonResult Login([FromBody] LoginViewModel.Request request)
        {
            var response = new JsonResultViewModel();

            try
            {
                var user = UnitOfWork.UserRepository.FindUserByEmail(request.email);

                if (user == null)
                {
                    return(Json(new JsonResultViewModel
                    {
                        error_message = "User not found",
                        error_type = ResponseErrorType.UserNotFound
                    }));
                }

                if (user.Password != Hashing.GetSha1(request.hash.ToLower() + "ConstValue"))
                {
                    return(Json(new JsonResultViewModel
                    {
                        error_message = "Wrong password",
                        error_type = ResponseErrorType.WrongPassword
                    }));
                }

                var accessToken = JWT.GetToken(request.email);

                response.data = new LoginViewModel.Response
                {
                    access_token = accessToken,
                    email        = user.Email,
                    role_id      = user.RoleId
                };
                response.is_successful = true;
            }
            catch (Exception ex)
            {
                response = new JsonResultViewModel
                {
                    error_message = ex.Message,
                    error_type    = ResponseErrorType.UnexpectedError
                };
            }

            return(Json(response));
        }
Beispiel #8
0
        public JsonResult GetPost([FromBody] GetPostViewModel.Request request)
        {
            var response = new JsonResultViewModel();

            var limit   = 1413;
            var passage =
                "Waking up to an email from your bank is never fun. I’m used to receiving emails about my bank balance or recent transfers. I read them with bored, glazed-over eyes, and then archive them. However, I recently received an email that caused me to lose faith in a bank that I used to trust.\r\nNobody wants to hear that their bank PIN code may have been compromised. On August 5, 2019, me and 479,999 other customers of Monzo, a British app-based bank, found out that unauthorized staff had access to to our PIN numbers for six months. While many use Monzo and other app-based banks as a secondary account, I am all in. I made this decision after being frustrated with slow payment notifications and exorbitant fees from mainstream banks while traveling internationally.\r\nWith Monzo, I had so far enjoyed fee-free international credit-card payments. I liked the instant payment notifications and the way the app automatically filed my spending into categories like “Eating Out” and “Bills.” Opening an account was also quick and easy, as was transferring funds from my previous account. I was so happy with my user experience that I recommended it to my partner who, as a new arrival to the UK, had struggled to open a bank account with one of the Big Four banking corporations here.\r\nAll this made the news of the exposed PIN numbers even harder to take. (Monzo responded to the situation in a blog post on August 9.)\r\nWhile not yet prevalent in the United States, digital banks are becoming increasingly popular with the millennial crowd across Europe. In the wake of the 2008 financial crisis, the U.K. passed the Financial Services Act 2012 in order to open up the market to new banks. This facilitated the rise of Monzo, Revolut, and other digital-only banks that undercut traditional banking costs by doing away with physical-branch locations and serving customers purely through an app. Also, because these companies don’t currently offer a full suite of services like mortgages and loans, they’re less hampered by regulation, according to the major accounting firm KPMG. These benefits, along with unique features such as fee-free international spending, have allowed banks such as Monzo to attract worldwide attention from investors and a £2 billion ($2.4 billion) valuation, despite being founded only in 2015.\r\nInitially, I thought this was a good thing. However, news such as the fact that my PIN number was possibly visible to 110 unauthorized engineers has caused me to question that. With relatively little experience compared to legacy banks, perhaps Monzo and other fintech unicorns are not yet qualified to hold our money.\r\nThere’s more evidence to suggest that this may be the case. For example, recent Monzo technical problems resulted in transactions and card payments being declined because of a technical glitch.\r\nCompared to other fintech startups however, Monzo has seen fewer scandals. The U.K. FCA (Financial Conduct Authority) has been investigating Revolut, one of Monzo’s biggest competitors, for an alleged compliance lapse that may have resulted in illegal transactions via its app. (A Revolut spokesperson told Bloomberg in response to the investigation that “at no point did we fail to meet our legal and regulatory sanctions.”)\r\nThat’s not to mention, Revolut’s reportedly toxic work culture and also its usage of advertisements that many found to be single-shaming and which reportedly used fake data. (Revolut apologized for the advertisements.)\r\nIt’s not just British app-based banks that have landed themselves in legal hot water. Berlin-based N26 has been ordered by the German government to improve its ability to prevent money laundering and terrorist financing. A tweet responding to this inquiry prompted many to share their stories of how they had been unable to access their funds.";

            try
            {
                string email;
                if (JWT.ValidateToken(request.token ?? Request?.Headers?.Get("token"), out email))
                {
                    if (UnitOfWork.UserRepository.FindUserByEmail(email).Role.Permissions.Any(permission =>
                                                                                              permission.PermissionId == (int)Permission.ReadFullPassage))
                    {
                        response.data = new GetPostViewModel.Response
                        {
                            passage             = passage,
                            is_complete_passage = true
                        }
                    }
                    ;
                }
                else
                {
                    response.data = new GetPostViewModel.Response
                    {
                        passage             = passage.Substring(0, limit) + "...",
                        is_complete_passage = false
                    };
                }

                response.is_successful = true;
            }
            catch (Exception ex)
            {
                response = new JsonResultViewModel
                {
                    error_message = ex.Message,
                    error_type    = ResponseErrorType.UnexpectedError
                };
            }

            return(Json(response));
        }
        public virtual JsonResult CreatePopup(T item)
        {
            var r = new JsonResultViewModel();

            OnCreateSaveItem(item);
            if (Repo.Create(item))
            {
                OnAfterCreateSaveItem(item);
                r.Ok = true;
                if (!CreateJsAction.IsEmpty())
                {
                    r.JsFunction = CreateJsAction;
                }
            }
            else
            {
                r.Error = MvcLogger.GetErrorMessage(ModelState);
            }
            return(Json(r));
        }
Beispiel #10
0
        public JsonResult GetRegisteredUsers([FromBody] GetRegisteredUsersViewModel.Request request)
        {
            var response = new JsonResultViewModel();

            try
            {
                string email;
                if (!JWT.ValidateToken(request.token ?? Request?.Headers?.Get("token"), out email) || UnitOfWork
                    .UserRepository.FindUserByEmail(email).Role.Permissions.All(permission =>
                                                                                permission.PermissionId != (int)Permission.GetUsers))
                {
                    return(Json(new JsonResultViewModel
                    {
                        error_message = "Permission Denied",
                        error_type = ResponseErrorType.PermissionDenied
                    }));
                }

                var users = UnitOfWork.UserRepository.GetUsers().Select(user => new UserViewModel
                {
                    id = user.UserId, email = user.Email, register_date = user.RegisterDate
                })
                            .ToList();

                response.data = new GetRegisteredUsersViewModel.Response
                {
                    users = users
                };
                response.is_successful = true;
            }
            catch (Exception ex)
            {
                response = new JsonResultViewModel
                {
                    error_message = ex.Message,
                    error_type    = ResponseErrorType.UnexpectedError
                };
            }

            return(Json(response));
        }
Beispiel #11
0
        public IActionResult Delete(int id)
        {
            var result = new JsonResultViewModel <string>
            {
                IsValid = true,
                Message = "Deleted."
            };

            try
            {
                var response = _productService.RemoveProduct(new ContractRequest <GetProductRequest> {
                    Data = new GetProductRequest {
                        Id = id
                    }
                });

                if (!response.IsValid)
                {
                    foreach (var error in response.ErrorMessages)
                    {
                        result.ErrorMessage += error;
                        result.ErrorMessage += Environment.NewLine;
                    }
                }


                return(Json(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Deleting product");
                result.ErrorMessage = ex.Message;
            }
            result.IsValid = false;
            return(Json(result));
        }
        // POST api/values
        public object Post()
        {
            JsonResultViewModel result = new JsonResultViewModel();

            result.status      = true;
            result.message     = "Coupon successfully claimed";
            result.messageCode = "S";

            var    httpRequest = HttpContext.Current.Request;
            long   id          = string.IsNullOrEmpty(httpRequest["msCouponId"]) ? 0 : long.Parse(httpRequest["msCouponId"]);
            string userId      = httpRequest["UserId"];


            try
            {
                using (PatuhEntities db = new PatuhEntities())
                {
                    MsCoupon msCoupon = db.MsCoupons.Where(x => x.Id == id).FirstOrDefault();

                    long totalPoint = db.TrPoints.Where(x => x.UserID == userId).Sum(x => x.PointValue) ?? 0;

                    if ((totalPoint - msCoupon.PointNeeded) < 0)
                    {
                        result.status      = false;
                        result.message     = "User Points is not enough to claim the coupon";
                        result.messageCode = "Error in claiming Coupon";
                        return(result);
                    }

                    TrUserCoupon userCoupon = db.TrUserCoupons.Where(x => x.MsCouponId == id).FirstOrDefault();

                    if (userCoupon == null)
                    {
                        CouponCode.CouponCodeBuilder couponBuilder = new CouponCode.CouponCodeBuilder();
                        CouponCode.Options           opt           = new CouponCode.Options();
                        string couponCode = couponBuilder.Generate(opt);

                        userCoupon            = new TrUserCoupon();
                        userCoupon.MsCouponId = id;
                        userCoupon.UserID     = userId;
                        userCoupon.CouponCode = couponCode;
                        userCoupon.cCreated   = userId;
                        userCoupon.dCreated   = DateTime.Now;
                        db.TrUserCoupons.AddObject(userCoupon);

                        TrPoint trPoint = new TrPoint();
                        trPoint.ArticleId    = 0;
                        trPoint.UserID       = userId;
                        trPoint.ActionCode   = "CLAIM";
                        trPoint.PointValue   = (msCoupon.PointNeeded * -1);
                        trPoint.cCreated     = userId;
                        trPoint.dCreated     = DateTime.Now;
                        trPoint.cLastUpdated = userId;
                        trPoint.dLastUpdated = DateTime.Now;

                        db.TrPoints.AddObject(trPoint);
                    }

                    userCoupon.cStatus = "Y";

                    /*
                     * if (httpRequest.Files.Count > 0)
                     *  {
                     *
                     *      foreach (string file in httpRequest.Files)
                     *      {
                     *          var postedFile = httpRequest.Files[file];
                     *          Type fileType = postedFile.GetType();
                     *          byte[] couponImage = new byte[postedFile.ContentLength];
                     *
                     *          postedFile.InputStream.Read(couponImage, 0, postedFile.ContentLength);
                     *          userCoupon.c
                     *      }
                     */
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.status      = false;
                result.message     = e.Message;
                result.messageCode = "Error in claiming Coupon";
            }

            return(result);
        }
        public JsonResult Register([FromBody] RegisterViewModel.Request request)
        {
            var response = new JsonResultViewModel();

            try
            {
                if (request.hash.Length < 8)
                {
                    return(Json(new JsonResultViewModel
                    {
                        error_message = "Weak password",
                        error_type = ResponseErrorType.ShortPassword
                    }));
                }

                var emailAddressAttribute = new EmailAddressAttribute();
                if (!emailAddressAttribute.IsValid(request.email))
                {
                    return(Json(new JsonResultViewModel
                    {
                        error_message = "Invalid email",
                        error_type = ResponseErrorType.InvalidEmail
                    }));
                }

                if (UnitOfWork.UserRepository.GetUsers().Any(user => user.Email == request.email))
                {
                    return(Json(new JsonResultViewModel
                    {
                        error_message = "Duplicate email",
                        error_type = ResponseErrorType.DuplicateEmail
                    }));
                }

                UnitOfWork.UserRepository.AddUser(new User
                {
                    Email        = request.email,
                    Password     = Hashing.GetSha1(request.hash.ToLower() + "ConstValue"),
                    RegisterDate = DateTime.Now.ToString("MM/dd/yyyy HH:mm"),
                    RoleId       = 2
                });

                var accessToken = JWT.GetToken(request.email);

                if (!request.email.Equals("*****@*****.**"))
                {
                    UnitOfWork.Save();
                }

                response.data = new RegisterViewModel.Response
                {
                    access_token = accessToken,
                    email        = request.email,
                    role_id      = 2
                };
                response.is_successful = true;
            }
            catch (Exception ex)
            {
                response = new JsonResultViewModel
                {
                    error_message = ex.Message,
                    error_type    = ResponseErrorType.UnexpectedError
                };
            }

            return(Json(response));
        }
Beispiel #14
0
        // POST api/values
        public object Post()
        {
            JsonResultViewModel result = new JsonResultViewModel();

            result.status      = true;
            result.message     = "News successfully updated";
            result.messageCode = "S";

            var    httpRequest = HttpContext.Current.Request;
            long   id          = string.IsNullOrEmpty(httpRequest["Id"]) ? 0 : long.Parse(httpRequest["Id"]);
            string title       = httpRequest["title"];
            string story       = httpRequest["story"];
            string location    = httpRequest["location"];
            double latitude    = string.IsNullOrEmpty(httpRequest["latitude"]) ? 0 : double.Parse(httpRequest["latitude"]);
            double longitude   = string.IsNullOrEmpty(httpRequest["longitude"]) ? 0 : double.Parse(httpRequest["longitude"]);
            string userId      = httpRequest["userId"];


            try
            {
                using (PatuhEntities db = new PatuhEntities())
                {
                    TrArticle article = db.TrArticles.Where(x => x.Id == id).FirstOrDefault();

                    if (article == null)
                    {
                        article          = new TrArticle();
                        article.cCreated = userId;
                        article.dCreated = DateTime.Now;
                        db.TrArticles.AddObject(article);
                    }


                    article.Category    = "ARTICLE";
                    article.Title       = title;
                    article.Story       = story;
                    article.GPSLocation = location;
                    article.GPSLong     = longitude;
                    article.GPSLat      = latitude;

                    article.cLastUpdated = userId;
                    article.dLastUpdated = DateTime.Now;

                    db.SaveChanges();

                    try
                    {
                        if (httpRequest.Files.Count > 0)
                        {
                            IList <TrImageAttachment> currentImages = db.TrImageAttachments.Where(x => x.HeaderId == article.Id).ToList();
                            if (currentImages != null && currentImages.Count > 0)
                            {
                                foreach (TrImageAttachment dbImg in currentImages)
                                {
                                    db.TrImageAttachments.DeleteObject(dbImg);
                                }
                            }

                            string extention = "";
                            string guid      = "";

                            string[] supportedTypes = new string[] { "jpg", "jpeg", "bmp", "png" };
                            int      fileSequence   = 0;

                            foreach (string file in httpRequest.Files)
                            {
                                var  postedFile = httpRequest.Files[file];
                                Type fileType   = postedFile.GetType();
                                if (postedFile != null)
                                {
                                    if (postedFile.FileName != "")
                                    {
                                        byte[] theImage = new byte[postedFile.ContentLength];
                                        extention = (Path.GetExtension(postedFile.FileName).TrimStart('.')).ToLower();

                                        if (supportedTypes.Contains(extention))
                                        {
                                            postedFile.InputStream.Read(theImage, 0, postedFile.ContentLength);


                                            TrImageAttachment imageAtt = new TrImageAttachment();// db.TrImageAttachments.Where(x => x.Id == id).FirstOrDefault();


                                            imageAtt          = new TrImageAttachment();
                                            imageAtt.HeaderId = article.Id;

                                            imageAtt.cCreated = userId;
                                            imageAtt.dCreated = DateTime.Now;

                                            imageAtt.Sequence     = ++fileSequence;
                                            imageAtt.Image        = theImage;
                                            imageAtt.cLastUpdated = userId;
                                            imageAtt.dLastUpdated = DateTime.Now;

                                            db.TrImageAttachments.AddObject(imageAtt);
                                            db.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        result.status      = false;
                        result.message     = e.Message;
                        result.messageCode = "Error in saving article";
                        return(result);
                    }
                }
            }
            catch (Exception e)
            {
                result.status      = false;
                result.message     = e.Message;
                result.messageCode = "Error in saving Article";
            }

            return(result);
        }
        // POST api/values
        public object Post()
        {
            JsonResultViewModel result = new JsonResultViewModel();

            result.status      = true;
            result.message     = "Comment successfully updated";
            result.messageCode = "S";

            var    httpRequest   = HttpContext.Current.Request;
            long   id            = string.IsNullOrEmpty(httpRequest["Id"]) ? 0 : long.Parse(httpRequest["Id"]);
            long   articleId     = string.IsNullOrEmpty(httpRequest["ArticleId"]) ? 0 : long.Parse(httpRequest["ArticleId"]);
            string postedComment = httpRequest["Comment"];
            string userId        = httpRequest["userId"];


            try
            {
                using (PatuhEntities db = new PatuhEntities())
                {
                    TrComment comment = db.TrComments.Where(x => x.Id == id).FirstOrDefault();

                    if (comment == null)
                    {
                        comment          = new TrComment();
                        comment.cCreated = userId;
                        comment.dCreated = DateTime.Now;
                        db.TrComments.AddObject(comment);

                        MsPoint msPoint = db.MsPoints.Where(x => x.ActionCode == "COMMENTART").FirstOrDefault();

                        if (msPoint != null)
                        {
                            TrArticle trArticle = db.TrArticles.Where(x => x.Id == articleId).FirstOrDefault();

                            if (trArticle != null)
                            {
                                TrPoint trPoint = new TrPoint();

                                trPoint.ArticleId    = trArticle.Id;
                                trPoint.UserID       = trArticle.cCreated;
                                trPoint.ActionCode   = "COMMENTART";
                                trPoint.PointValue   = msPoint.RewardPoint;
                                trPoint.cCreated     = userId;
                                trPoint.dCreated     = DateTime.Now;
                                trPoint.cLastUpdated = userId;
                                trPoint.dLastUpdated = DateTime.Now;

                                db.TrPoints.AddObject(trPoint);
                                //db.SaveChanges();
                            }
                        }
                    }



                    comment.ArticleId = articleId;
                    comment.Comment   = postedComment;

                    comment.cLastUpdated = userId;
                    comment.dLastUpdated = DateTime.Now;

                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.status      = false;
                result.message     = e.Message;
                result.messageCode = "Error in saving Comment";
            }

            return(result);
        }
Beispiel #16
0
        // POST api/values
        public object Post()
        {
            JsonResultViewModel result = new JsonResultViewModel();

            result.status      = true;
            result.message     = "User Profile successfully updated";
            result.messageCode = "S";

            var    httpRequest = HttpContext.Current.Request;
            string userId      = httpRequest["userId"];
            string password    = httpRequest["password"];
            string userName    = httpRequest["userName"];
            string email       = httpRequest["email"];
            string phoneNo     = httpRequest["phoneNo"];
            string location    = httpRequest["location"];
            string birthday    = httpRequest["birthday"];


            try
            {
                using (PatuhEntities db = new PatuhEntities())
                {
                    MsMobileUserProfile profile = db.MsMobileUserProfiles.Where(x => x.UserID == userId).FirstOrDefault();


                    byte[] profImage = null;

                    Guid   userGuid       = System.Guid.NewGuid();
                    string hashedPassword = Security.HashSHA1(password + userGuid.ToString());

                    string profilePicPath = "";
                    try
                    {
                        if (httpRequest.Files.Count > 0)
                        {
                            string extention = "";
                            string guid      = "";

                            string[] supportedTypes = new string[] { "jpg", "jpeg", "bmp", "png" };

                            foreach (string file in httpRequest.Files)
                            {
                                var  postedFile = httpRequest.Files[file];
                                Type fileType   = postedFile.GetType();
                                if (postedFile != null)
                                {
                                    if (postedFile.FileName != "")
                                    {
                                        profImage = new byte[postedFile.ContentLength];
                                        extention = (Path.GetExtension(postedFile.FileName).TrimStart('.')).ToLower();

                                        if (supportedTypes.Contains(extention))
                                        {
                                            guid = DateTime.Now.ToString("yyyyMMddhhmmss") + System.Guid.NewGuid().ToString("n") + Path.GetExtension(postedFile.FileName);

                                            //string filePath = Path.Combine(httpRequest.MapPath("~/PhotoUploads"), guid);// Path.GetFileName(postedFile.FileName));

                                            postedFile.InputStream.Read(profImage, 0, postedFile.ContentLength);

                                            //postedFile.SaveAs(filePath);


                                            //FileInfo TheFile = new FileInfo(filePath);
                                            //if (TheFile.Exists)
                                            //{
                                            //    TheFile.MoveTo(Path.Combine(httpRequest.MapPath("~/PhotoUploads"), Path.GetFileName(guid)));
                                            //}

                                            //profilePicPath = TheFile.FullName;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        result.status      = false;
                        result.message     = e.Message;
                        result.messageCode = "Error in saving User Profile child";
                        return(result);
                    }

                    if (profile == null)
                    {
                        profile = new MsMobileUserProfile();
                        db.MsMobileUserProfiles.AddObject(profile);
                    }


                    profile.UserID         = userId;
                    profile.FullName       = userName;
                    profile.Email          = email;
                    profile.PhoneNo        = phoneNo;
                    profile.Location       = location;
                    profile.DOB            = string.IsNullOrEmpty(birthday) ? new DateTime() : DateTime.ParseExact(birthday, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
                    profile.Pwd            = hashedPassword;
                    profile.UserGuid       = userGuid;
                    profile.ProfilePicPath = profilePicPath;
                    profile.ProfilePic     = profImage;
                    profile.dCreated       = DateTime.Now;
                    profile.dLastUpdated   = DateTime.Now;

                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.status      = false;
                result.message     = e.Message;
                result.messageCode = "Error in saving User Profile";
            }

            return(result);
        }