Esempio n. 1
0
        public ActionResult Edit(User user, HttpPostedFileBase ProfilePic)
        {
            if (Functions.CurrentUserID() == user.ID)
            {
                //if (!aclService.HasRight(Rights.EditUserSelf))
                if (!aclService.HasRight(Rights.EditUserSelf))
                {
                    return(RedirectToAction("AccessDenied", "Home"));
                }
            }
            else
            {
                //if (!aclService.HasRight(Rights.EditOtherUsers))
                if (!aclService.HasRight(Rights.EditOtherUsers))
                {
                    return(RedirectToAction("AccessDenied", "Home"));
                }
            }
            if (!user.IsChangePassword)
            {
                ModelState.Remove("Password");
            }
            if (ModelState.IsValid)
            {
                if (ProfilePic != null && !Functions.IsValidImage(ProfilePic.FileName.ToLower()))
                {
                    TempData["ErrorMessage"] = "Please upload valid profile picture";
                }
                else
                {
                    int duplicateUser = context.User.Where(m => m.Email == user.Email && m.ID != user.ID && m.IsDeleted == false).Count();
                    if (duplicateUser == 0)
                    {
                        User userUpdate = context.User.Find(user.ID);

                        userUpdate.Email = user.Email;
                        if (user.IsChangePassword)
                        {
                            userUpdate.SaltKey  = CryptoUtility.GetNewSalt();
                            userUpdate.Password = CryptoUtility.GetPasswordHash(user.Password, userUpdate.SaltKey);
                        }
                        userUpdate.FirstName = user.FirstName;
                        userUpdate.LastName  = user.LastName;
                        if (ProfilePic != null && ProfilePic.ContentLength > 0)
                        {
                            string relativePath = Functions.GetNewFileName("/Areas/Admin/assets/images/avatars/", ProfilePic.FileName);
                            ProfilePic.SaveAs(Server.MapPath(relativePath));
                            userUpdate.ProfilePicURL = relativePath;
                        }
                        userUpdate.RoleID    = user.RoleID;
                        user.ModifiedOn      = DateTime.UtcNow;
                        user.ModifiedBy      = Functions.CurrentUserID();
                        userUpdate.IsActive  = user.IsActive;
                        userUpdate.IsDefault = user.IsDefault;
                        context.SaveChanges();
                        aclService.SetRights(user.ID, userUpdate.RoleID);
                        TempData["SuccessMessage"] = "User updated successfully.";
                        return(RedirectToAction("List"));
                    }
                    else
                    {
                        TempData["ErrorMessage"] = "User already exist with same email address. Please enter different email.";
                    }
                }
            }
            ViewBag.RoleList = new SelectList(context.Role.Where(m => m.IsDeleted != true).ToList(), "ID", "Name", user.RoleID);
            return(View(user));
        }
Esempio n. 2
0
        public JsonResult InviteRegister(int cityId, string info, string password, string from = "")
        {
            if (String.IsNullOrEmpty(info))
            {
                return(Json(new { status = -1, msg = "无效的参数" }));
            }
            UserModels userModels = new UserModels();

            info       = CryptoUtility.TripleDESDecrypt(info);
            userModels = JsonConvert.DeserializeObject <UserModels>(info);
            string tel = string.IsNullOrEmpty(userModels.Tel) ? "" : StringUtility.StripWhiteSpace(userModels.Tel.Replace("-", ""), false);

            if (tel.StartsWith("0"))
            {
                tel = tel.Substring(1);
            }
            userModels.Tel = tel;
            if (!StringUtility.ValidateMobile(userModels.Tel))
            {
                return(Json(new { status = -1, msg = "手机号码格式不正确" }));
            }
            PublicUser publicUser =
                ncBase.CurrentEntities.PublicUser.Where(o => o.Tel == userModels.Tel).FirstOrDefault();

            if (publicUser.IsNoNull())
            {
                return(Json(new { status = -1, msg = "该手机号码已经注册过了" }));
            }
            publicUser =
                ncBase.CurrentEntities.PublicUser.Where(o => o.Name == userModels.UserName).FirstOrDefault();
            string userName = userModels.UserName;

            if (publicUser.IsNoNull())
            {
                userModels.UserName = userModels.UserName + "_" + userModels.UserId + StringUtility.GetValiCode();
            }
            PublicUserModel user = new PublicUserModel();

            string  strCompany = string.IsNullOrEmpty(userModels.Company) ? userModels.Store : userModels.Company;
            string  strStore   = string.IsNullOrEmpty(userModels.Company) ? "" : userModels.Store;
            Company company    = ncBase.CurrentEntities.Company.Where(o => o.Name == strCompany && o.CityID == cityId).FirstOrDefault();

            if (company.IsNull())
            {
                company         = new Company();
                company.Name    = strCompany;
                company.Tel     = "";
                company.Address = "";
                company.CityID  = cityId;
                ncBase.CurrentEntities.AddToCompany(company);
                ncBase.CurrentEntities.SaveChanges();
            }


            CompanyStore companyStore = ncBase.CurrentEntities.CompanyStore.Where(o => o.StoreName == strStore && o.CompanyId == company.CompanyId).FirstOrDefault();

            if (!string.IsNullOrEmpty(strStore) && companyStore.IsNull())
            {
                companyStore           = new CompanyStore();
                companyStore.Address   = "";
                companyStore.CityID    = cityId;
                companyStore.CompanyId = company.CompanyId;
                companyStore.StoreName = strStore;
                companyStore.Tel       = "";
                ncBase.CurrentEntities.AddToCompanyStore(companyStore);
                ncBase.CurrentEntities.SaveChanges();
            }
            user.Tel         = userModels.Tel;
            user.Name        = userModels.UserName;
            user.Password    = password;
            user.CityID      = cityId;
            user.DistrictId  = 0;
            user.CompanyId   = company.CompanyId;
            user.StoreId     = companyStore.IsNoNull() ? companyStore.StoreId : 0;
            user.RegionId    = 0;
            user.VipType     = 2; //会员类型
            user.Portrait    = userModels.Portrait;
            user.Remarks     = !string.IsNullOrEmpty(from) ? "From:" + from : "";
            user.IP          = Request.UserHostAddress;
            user.LastLoginIP = Request.UserHostAddress;
            user.NickName    = userName;
            user.EnrolnName  = userName;

            #region 表单验证
            if (string.IsNullOrEmpty(user.Tel))
            {
                return(Json(new { status = 1, msg = "手机号不能为空" }));
            }

            if (string.IsNullOrEmpty(user.Name))
            {
                return(Json(new { status = 1, msg = "用户名不能为空" }));
            }
            if (string.IsNullOrEmpty(user.Password) || (user.Password != null && user.Password.Length < 6))
            {
                return(Json(new { status = 1, msg = "密码至少6位数" }));
            }
            if (user.CityID <= 0)
            {
                return(Json(new { status = 1, msg = "所属城市必填" }));
            }
            if (user.CompanyId <= 0)
            {
                return(Json(new { status = 1, msg = "所属公司必填" }));
            }

            #endregion

            UserBll userBll = new UserBll();
            int     userid  = userBll.addPublicUser(user);
            if (userid == -1)
            {
                return(Json(new { status = 1, msg = "用户名已经存在" }));
            }
            else if (userid == -2)
            {
                return(Json(new { status = 1, msg = "手机号已被注册" }));
            }
            if (userid > 0)//自动登录
            {
                try
                {
                    if (userModels.InviteUid.IsNoNull() && userModels.InviteUid > 0)
                    {
                        PublicUser publicUserInvite =
                            ncBase.CurrentEntities.PublicUser.Where(
                                o => o.UserID == userModels.InviteUid && o.Status == 1).FirstOrDefault();
                        if (publicUserInvite.IsNoNull())
                        {
                            int points = publicUserInvite.Points;
                            publicUserInvite.Points = points + 200;
                            ncBase.CurrentEntities.SaveChanges();

                            PublicUserPointsLog publicUserPointsLog = new PublicUserPointsLog();
                            publicUserPointsLog.Points        = 200;
                            publicUserPointsLog.UserId        = publicUserInvite.UserID;
                            publicUserPointsLog.AddTime       = DateTime.Now;
                            publicUserPointsLog.CurrentPoints = points + 200;
                            publicUserPointsLog.Description   = "手机用户" + user.Tel + "接受邀请注册加分";
                            ncBase.CurrentEntities.AddToPublicUserPointsLog(publicUserPointsLog);
                            ncBase.CurrentEntities.SaveChanges();
                            smsApi.SendSms(publicUserInvite.Tel, "手机用户" + user.Tel + "成功通过您的邀请链接注册房产盒子,系统赠送您200积分!", (Purpose)8, "【房产盒子】");
                        }
                    }
                    SendResult sendResult = smsApi.SendSms(user.Tel, "恭喜您成功开通房产盒子,帐号:" + user.Tel + " 密码:" + user.Password, (Purpose)8, "【房产盒子】");
                }
                catch (Exception)
                {
                    throw;
                }
                if (Session[user.Tel] != null)
                {
                    Session[user.Tel] = null;
                    Session.Remove(user.Tel);
                }
                PublicUserModel newUser = userBll.PublicUserLogin(user.Name, user.Password);
                String          saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"];
                if (String.IsNullOrEmpty(saveKey))
                {
                    saveKey = "WXLoginedUser";
                }
                Session[saveKey] = newUser;
                HttpCookie loginUserCookie = new HttpCookie(saveKey, CryptoUtility.TripleDESEncrypt(newUser.UserID.ToString()));
                loginUserCookie.Expires = DateTime.Now.AddDays(10);
                HttpContext.Response.Cookies.Add(loginUserCookie);
            }
            return(Json(new { status = 0, msg = "注册成功" }));
        }
Esempio n. 3
0
        public ActionResult WXUrlLogin(string tourl = "", string openid = "", string wxresult = "")
        {
            //if (Session["Passport"] != null)
            //{
            //    var ucPassport = (UcPassport)Session["Passport"];
            //    if (ucPassport != null && ucPassport.IsLogin)
            //    {
            //        Register(ucPassport);
            //        return redirectToUrl(tourl);
            //    }
            //}
            //else
            //{
            JObject         wxinfo  = JObject.Parse(wxresult);
            UserBll         userBll = new UserBll();
            PublicUserModel user    = userBll.GetUserByOpenId(wxinfo.SelectToken("openid").ToString());

            if (user == null)
            {
                if (wxinfo == null)
                {
                    return(Register("/"));
                }
                user             = new PublicUserModel();
                user.Name        = wxinfo.SelectToken("openid").ToString();
                user.Password    = "******";
                user.CityID      = 592;
                user.DistrictId  = 0;
                user.CompanyId   = 0;
                user.StoreId     = 0;
                user.RegionId    = 0;
                user.Portrait    = wxinfo.SelectToken("headimgurl").ToString();
                user.VipType     = 2; //会员类型
                user.IP          = Request.UserHostAddress;
                user.LastLoginIP = Request.UserHostAddress;
                user.NickName    = wxinfo.SelectToken("nickname").ToString();
                user.EnrolnName  = wxinfo.SelectToken("nickname").ToString();


                if (!string.IsNullOrEmpty(user.Name))
                {
                    int userid = userBll.addPublicUser(user);
                    if (userid == -1)
                    {
                        //return Json(new { status = 1, msg = "用户名已经存在" });
                    }
                    else if (userid == -2)
                    {
                        //return Json(new { status = 1, msg = "手机号已被注册" });
                    }
                    //if (userid > 0)//自动登录

                    userBll.addPublicUserThirdInfo(userid, 1, wxinfo.SelectToken("openid").ToString(),
                                                   wxinfo.SelectToken("unionid").ToString());
                    user.UserID = userid;
                }
            }
            //PublicUserModel newUser = userBll.PublicUserLogin(ucPassport.UserName, ucPassport.PassWord);
            PublicUserModel newUser = user;
            String          saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"];

            if (String.IsNullOrEmpty(saveKey))
            {
                saveKey = "WXLoginedUser";
            }
            Session[saveKey] = newUser;
            HttpCookie loginUserCookie = new HttpCookie(saveKey, CryptoUtility.TripleDESEncrypt(newUser.UserID.ToString()));

            loginUserCookie.Expires = DateTime.Now.AddDays(10);
            Response.Cookies.Add(loginUserCookie);

            //}
            //else
            //    Register("/");
            if (string.IsNullOrEmpty(tourl))
            {
                tourl = "/";
            }
            if (!string.IsNullOrEmpty(tourl))
            {
                return(redirectToUrl(tourl));
            }
            return(View());
        }
Esempio n. 4
0
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="startPartitionKey">The start partition key, or <c>null</c>.</param>
        /// <param name="startRowKey">The start row key, or <c>null</c>.</param>
        /// <param name="endPartitionKey">The end partition key, or <c>null</c>.</param>
        /// <param name="endRowKey">The end row key, or <c>null</c>.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessTablePolicy policy,
            string accessPolicyIdentifier,
            string startPartitionKey,
            string startRowKey,
            string endPartitionKey,
            string endRowKey,
            string resourceName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string         permissions = null;
            DateTimeOffset?startTime   = null;
            DateTimeOffset?expiryTime  = null;

            if (policy != null)
            {
                permissions = SharedAccessTablePolicy.PermissionsToString(policy.Permissions);
                startTime   = policy.SharedAccessStartTime;
                expiryTime  = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedIP + "\n" +
            ////                     signedProtocol + "\n" +
            ////                     signedversion + "\n" +
            ////                     startpk + "\n" +
            ////                     startrk + "\n" +
            ////                     endpk + "\n" +
            ////                     endrk
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}",
                permissions,
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(startTime),
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                SharedAccessSignatureHelper.GetProtocolString(protocols),
                sasVersion,
                startPartitionKey,
                startRowKey,
                endPartitionKey,
                endRowKey);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
Esempio n. 5
0
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a file returned with this SAS.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessFilePolicy policy,
            SharedAccessFileHeaders headers,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string         permissions = null;
            DateTimeOffset?startTime   = null;
            DateTimeOffset?expiryTime  = null;

            if (policy != null)
            {
                permissions = SharedAccessFilePolicy.PermissionsToString(policy.Permissions);
                startTime   = policy.SharedAccessStartTime;
                expiryTime  = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedversion + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////

            string cacheControl       = null;
            string contentDisposition = null;
            string contentEncoding    = null;
            string contentLanguage    = null;
            string contentType        = null;

            if (headers != null)
            {
                cacheControl       = headers.CacheControl;
                contentDisposition = headers.ContentDisposition;
                contentEncoding    = headers.ContentEncoding;
                contentLanguage    = headers.ContentLanguage;
                contentType        = headers.ContentType;
            }

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}",
                permissions,
                GetDateTimeOrEmpty(startTime),
                GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                sasVersion,
                cacheControl,
                contentDisposition,
                contentEncoding,
                contentLanguage,
                contentType);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
 /// <summary>
 /// Compute HMAC.
 /// </summary>
 /// <param name="key">The key of HMAC.</param>
 /// <param name="buf">The data to be computed.</param>
 /// <returns>The computed result.</returns>
 internal static byte[] HMAC(byte[] key, byte[] buf)
 {
     return(CryptoUtility.ComputeMd5Hmac(key, buf));
 }
Esempio n. 7
0
 public void RoundDownDefaultRules()
 {
     CryptoUtility.RoundDown(0.000123456789m).Should().Be(0.0001234m);
     CryptoUtility.RoundDown(1.2345678m).Should().Be(1.234m);
     CryptoUtility.RoundDown(10.2345678m).Should().Be(10m);
 }
 /// <summary>
 /// Opens the machine-based certificate store.
 /// </summary>
 /// <returns>The configured store.</returns>
 public SystemX509Store OpenStore()
 {
     return(new SystemX509Store(CryptoUtility.OpenStoreRead(this.Name, this.Location), null));
 }
Esempio n. 9
0
 /// <summary>
 /// Get a string for this trade
 /// </summary>
 /// <returns>String</returns>
 public override string ToString()
 {
     return(CryptoUtility.UnixTimeStampToDateTimeMilliseconds(Ticks).ToLocalTime() + ": " + Amount + " at " + Price);
 }
Esempio n. 10
0
 /// <summary>
 /// Return a rounded amount if needed
 /// </summary>
 /// <returns>Rounded amount or amount if no rounding is needed</returns>
 public decimal RoundAmount()
 {
     return(ShouldRoundAmount ? CryptoUtility.RoundAmount(Amount) : Amount);
 }
        protected void InitializeDatabase(NTSDBContext context)
        {
            Role AdminRole = new Role();

            AdminRole.GUID    = Functions.GetRandomGUID();
            AdminRole.Name    = "Administrator";
            AdminRole.AddedBy = 1;
            AdminRole.AddedOn = DateTime.UtcNow;
            context.Role.Add(AdminRole);
            context.SaveChanges();

            User user = new User();

            user.GUID      = Functions.GetRandomGUID();
            user.FirstName = "Super";
            user.LastName  = "Admin";
            user.Email     = "*****@*****.**";
            user.SaltKey   = CryptoUtility.GetNewSalt();
            string DefaultPassword = "******";

            user.Password      = CryptoUtility.GetPasswordHash(DefaultPassword, user.SaltKey);
            user.ProfilePicURL = "/Areas/Admin/assets/images/avatars/noprofile.jpg";
            user.IsActive      = true;
            user.IsDefault     = true;
            user.AddedOn       = DateTime.UtcNow;
            user.AddedBy       = 1;
            user.RoleID        = AdminRole.ID;
            user.IsSuperAdmin  = true;
            context.User.Add(user);
            context.SaveChanges();
            int userID = user.ID;

            /*Config config = new Config();
             * config.FacebookPageName = "netcms";
             * config.FacebookUserName = "******";
             * config.GPlusPageName = "netcms";
             * config.GPlusUsername = "******";
             * config.LogoPath = "/content/logo.png";
             * config.PintrestUserName = "******";
             * config.ShowNoOfLastPost = 5;
             * config.SiteName = "NITASA CMS";
             * config.SiteTitle = "NITASA CMS";
             * config.TwitterUsername = "******";
             * context.Config.Add(config);
             * context.SaveChanges();*/

            //Add Default Content
            Content content = new Content();

            content.GUID               = Functions.GetRandomGUID();
            content.Type               = "post";
            content.Title              = "Welcome to Nixon DotNet CMS ";
            content.URL                = "Welcome-to-Nixon-DotNet-CMS";
            content.Description        = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.";
            content.AddedBy            = userID;
            content.AddedOn            = DateTime.UtcNow;
            content.isPublished        = true;
            content.PublishedOn        = DateTime.UtcNow;
            content.IsSlugEdited       = true;
            content.IsFeatured         = false;
            content.EnableComment      = true;
            content.CommentEnabledTill = 180;
            context.Content.Add(content);
            context.SaveChanges();

            Content page = new Content();

            page.GUID          = Functions.GetRandomGUID();
            page.Type          = "page";
            page.Title         = "Index";
            page.URL           = "";
            page.Description   = "Home page";
            page.AddedBy       = userID;
            page.AddedOn       = DateTime.UtcNow;
            page.isPublished   = true;
            page.PublishedOn   = DateTime.UtcNow;
            page.IsSlugEdited  = false;
            page.IsFeatured    = false;
            page.EnableComment = false;
            context.Content.Add(page);
            context.SaveChanges();

            // Add default category
            Category conCategory = new Category();

            conCategory.Name             = "DotNet";
            conCategory.GUID             = Functions.GetRandomGUID();
            conCategory.Slug             = "dotnet";
            conCategory.ParentCategoryID = 0;
            conCategory.AddedBy          = userID;
            conCategory.AddedOn          = DateTime.UtcNow;
            context.Category.Add(conCategory);
            context.SaveChanges();

            ContentCategory contentCategory = new ContentCategory();

            contentCategory.CategoryID = conCategory.ID;
            contentCategory.ContentID  = content.ID;
            contentCategory.AddedBy    = userID;
            contentCategory.AddedOn    = DateTime.UtcNow;
            context.ContentCategory.Add(contentCategory);
            context.SaveChanges();

            //Add Widget
            Widget gadget = new Widget();

            gadget.Name         = "Recent Content";
            gadget.Title        = "Recent Content";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Recent Content\",\"count\": 5,\"showthumb\": false }";
            gadget.DisplayOrder = 1;
            gadget.IsActive     = true;
            context.Widget.Add(gadget);

            gadget              = new Widget();
            gadget.Name         = "Most Viewed Content";
            gadget.Title        = "Most Viewed Content";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Most Viewed Content\",\"count\": 5,\"showthumb\": false }";
            gadget.DisplayOrder = 2;
            gadget.IsActive     = true;
            context.Widget.Add(gadget);

            gadget              = new Widget();
            gadget.Name         = " Related Content";
            gadget.Title        = " Related Content";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Related Content\",\"count\": 3,\"showthumb\": false }";
            gadget.DisplayOrder = 3;
            gadget.IsActive     = false;
            context.Widget.Add(gadget);

            gadget              = new Widget();
            gadget.Name         = "Total Page View";
            gadget.Title        = "Total Page View";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Total Page View\",\"count\": 0,\"showthumb\": false }";
            gadget.DisplayOrder = 4;
            gadget.IsActive     = false;
            context.Widget.Add(gadget);

            gadget              = new Widget();
            gadget.Name         = "Category List";
            gadget.Title        = "Category List";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Category List\",\"count\": 3,\"showthumb\": false }";
            gadget.DisplayOrder = 5;
            gadget.IsActive     = true;
            context.Widget.Add(gadget);

            gadget              = new Widget();
            gadget.Name         = "Label List";
            gadget.Title        = "Label List";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Label List\",\"count\": 3,\"showthumb\": false }";
            gadget.DisplayOrder = 6;
            gadget.IsActive     = true;
            context.Widget.Add(gadget);
            context.SaveChanges();

            gadget              = new Widget();
            gadget.Name         = "Recent Comments";
            gadget.Title        = "Recent Comments";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Recent Comments\",\"count\": 3,\"showthumb\": false }";
            gadget.DisplayOrder = 6;
            gadget.IsActive     = true;
            context.Widget.Add(gadget);
            context.SaveChanges();

            gadget              = new Widget();
            gadget.Name         = "Page List";
            gadget.Title        = "Page List";
            gadget.GUID         = Functions.GetRandomGUID();
            gadget.Option       = "{ \"title\": \"Page List\",\"count\": 3,\"showthumb\": false }";
            gadget.DisplayOrder = 6;
            gadget.IsActive     = true;
            context.Widget.Add(gadget);
            context.SaveChanges();
        }
Esempio n. 12
0
        public void RoundDownOutOfRange()
        {
            Action a = () => CryptoUtility.RoundDown(1.2345m, -1);

            a.Should().Throw <ArgumentOutOfRangeException>();
        }
        public async Task <Result> CheckForUpdatesAsync()
        {
            try
            {
                this.Show();

#if DEBUG
                const bool SkipUpdate = true;
#else
                const bool SkipUpdate = false;
#endif

                var curProcess         = Process.GetCurrentProcess();
                var processFilePath    = curProcess.MainModule?.FileName;
                var processFileOldPath = $"{processFilePath}.old";

                if (string.IsNullOrEmpty(processFilePath))
                {
                    MessageBox.Show(this,
                                    "Fatal error...could not locate the running program on the file system.",
                                    "Update Failed",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    return(Result.Failed);
                }

                var otherProcesses = Process.GetProcessesByName(curProcess.ProcessName)
                                     .Where(p => p.Id != curProcess.Id);

                foreach (var process in otherProcesses)
                {
                    process.WaitForExit(3000);
                    process.Kill();
                }

                if (File.Exists(processFileOldPath))
                {
                    File.Delete(processFileOldPath);
                }

                using var web = new WebClient();

                var localHash  = CryptoUtility.CalculateFileMd5(processFilePath);
                var remoteHash = await web.DownloadStringTaskAsync(this.remoteMd5Url);

                // ReSharper disable once RedundantLogicalConditionalExpressionOperand
                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                if (SkipUpdate || localHash == remoteHash)
                {
                    return(Result.NoUpdateNeeded);
                }

                this.lbStatus.Text    = "Updating program...";
                this.pbDownload.Style = ProgressBarStyle.Continuous;

                web.DownloadProgressChanged += (o, e) => this.Invoke(new Action(() => {
                    var dlSize    = e.BytesReceived.Bytes();
                    var totalSize = e.TotalBytesToReceive.Bytes();

                    this.lbProgress.Text  = $"Downloading updates... {dlSize.ToString("0.##")} / {totalSize.ToString("0.##")} ({e.ProgressPercentage}%)";
                    this.pbDownload.Value = e.ProgressPercentage;
                }));

                var updateFilePath = Path.Combine(Path.GetTempPath(), "MinecraftLauncher.exe");

                if (File.Exists(updateFilePath))
                {
                    File.Delete(updateFilePath);
                }

                await web.DownloadFileWrappedAsync(this.remoteFileUrl, updateFilePath);

                this.lbStatus.Text    = "Installing updates...";
                this.pbDownload.Style = ProgressBarStyle.Marquee;

                File.Move(processFilePath, processFileOldPath);
                File.Move(updateFilePath, processFilePath);

                var newLocalHash = CryptoUtility.CalculateFileMd5(processFilePath);

                if (newLocalHash != remoteHash)
                {
                    MessageBox.Show(this,
                                    "Checksum mismatch! The update file is invalid. Update failed.",
                                    "Update Failed",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    File.Delete(processFilePath);
                    File.Move(processFileOldPath, processFilePath);

                    return(Result.Failed);
                }

                MessageBox.Show(this,
                                "Update complete! Click OK to restart the program and apply the update.",
                                "Update Complete",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                Process.Start(new ProcessStartInfo {
                    FileName        = processFilePath,
                    UseShellExecute = true,
                });

                return(Result.NeedsRestart);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in updater:");
                Console.WriteLine(ex);
                throw;
            }
            finally
            {
                this.Close();
            }
        }
Esempio n. 14
0
 public ActionResult DESDec(string dec)
 {
     return(Content(CryptoUtility.TripleDESDecrypt(dec)));
 }
Esempio n. 15
0
 public static string MD5(this string s)
 {
     return(CryptoUtility.MD5(s));
 }
Esempio n. 16
0
 public static string EncodeCookie(byte[] bytes)
 {
     return(CryptoUtility.TripleDESEncrypt(bytes, _keyBytes, _ivBytes));
 }
Esempio n. 17
0
 public static string TripleDESDecrypt(this string s, string key, string iv)
 {
     return(CryptoUtility.TripleDESDecrypt(s, key, iv));
 }
Esempio n. 18
0
 public static byte[] DecodeCookie(string s)
 {
     return(CryptoUtility.TripleDESDecrypt(s, _keyBytes, _ivBytes));
 }
Esempio n. 19
0
 public void CalculatePrecision_NoDecimals_Returns1()
 {
     CryptoUtility.CalculatePrecision("24").Should().Be(1);
     CryptoUtility.CalculatePrecision("1000").Should().Be(1);
     CryptoUtility.CalculatePrecision("123456789123456789465132").Should().Be(1);
 }
Esempio n. 20
0
 public UserService(IGenericRepository <User> repository, CryptoUtility cryptoUtility, TokenUtility tokenUtility)
     : base(repository)
 {
     this.cryptoUtility = cryptoUtility;
     this.tokenUtility  = tokenUtility;
 }
Esempio n. 21
0
        public void RoundDownOutOfRange()
        {
            void a() => CryptoUtility.RoundDown(1.2345m, -1);

            Invoking(a).Should().Throw <ArgumentOutOfRangeException>();
        }
Esempio n. 22
0
        //does encryption and decryption and returns a filled testResult
        private TestResult process(String message)
        {
            TestResult testResult = new TestResult();

            //encryption//
            stopWatch.Start();
            CryptoUtility.setServiceProvider(localSet);                                                                     //give local key set to utility
            Byte[] signatureBytes = CryptoUtility.signMessage(message);                                                     //creates signature for message with "local" key set
            CryptoUtility.setServiceProvider(remoteSet);                                                                    //give remote key set to utility
            Byte[] messageBytes = Encoding.UTF8.GetBytes(CryptoUtility.encryptData(message, CryptoUtility.getPublicKey())); //encrypts with remote public key of "recipient"
            stopWatch.Stop();
            testResult.encryptionTime = (int)stopWatch.ElapsedMilliseconds;
            testResult.totalLength    = signatureBytes.Length + messageBytes.Length;

            //decryption//
            //stopWatch.Restart();
            stopWatch.Reset();
            stopWatch.Start();
            //decrypts message with "recipients" remote private key. CryptoUtility already has the remote keyset as it's service provider
            String decMessage = CryptoUtility.decryptData(Encoding.UTF8.GetString(messageBytes), CryptoUtility.getPrivateKey());

            CryptoUtility.setServiceProvider(localSet); //give it the "senders" public key
            bool validSig = CryptoUtility.validateSignature(Encoding.UTF8.GetBytes(message), signatureBytes, CryptoUtility.getPublicKey());

            stopWatch.Stop();
            testResult.decryptionTime = (int)stopWatch.ElapsedMilliseconds;

            if (!validSig || 0 != String.Compare(decMessage, message)) //if signature failed to validate or the messages are not the same
            {
                throw new Exception("something ain't right");
            }

            testResult.totalTime = testResult.encryptionTime + testResult.decryptionTime; //adds up total time
            return(testResult);
        }
Esempio n. 23
0
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a blob returned with this SAS. Not valid for the 2012-02-12 version.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string         permissions = null;
            DateTimeOffset?startTime   = null;
            DateTimeOffset?expiryTime  = null;

            if (policy != null)
            {
                permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                startTime   = policy.SharedAccessStartTime;
                expiryTime  = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedversion + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////
            //// Note that the final five headers are invalid for the 2012-02-12 version.

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
                permissions,
                GetDateTimeOrEmpty(startTime),
                GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                sasVersion);

            if (string.Equals(sasVersion, Constants.VersionConstants.February2012))
            {
                if (headers != null)
                {
                    string errorString = string.Format(CultureInfo.CurrentCulture, SR.InvalidHeaders);
                    throw new ArgumentException(errorString);
                }
            }
            else
            {
                string cacheControl       = null;
                string contentDisposition = null;
                string contentEncoding    = null;
                string contentLanguage    = null;
                string contentType        = null;
                if (headers != null)
                {
                    cacheControl       = headers.CacheControl;
                    contentDisposition = headers.ContentDisposition;
                    contentEncoding    = headers.ContentEncoding;
                    contentLanguage    = headers.ContentLanguage;
                    contentType        = headers.ContentType;
                }

                stringToSign = stringToSign + string.Format(
                    CultureInfo.InvariantCulture,
                    "\n{0}\n{1}\n{2}\n{3}\n{4}",
                    cacheControl,
                    contentDisposition,
                    contentEncoding,
                    contentLanguage,
                    contentType);
            }

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }
Esempio n. 24
0
        public virtual decimal ClampOrderAmount(string pair, decimal amount)
        {
            ExchangeMarket market = Api.GetExchangeMarketFromCache(pair);

            return(market == null ? amount : CryptoUtility.ClampDecimal(market.MinTradeSize, market.MaxTradeSize, market.QuantityStepSize, amount));
        }
Esempio n. 25
0
        public ActionResult Invite(string from, string info)
        {
            UserModels userModels = new UserModels();
            bool       existTel   = false;
            PublicUser publicUser = new PublicUser();

            if (String.IsNullOrEmpty(info))
            {
                ViewBag.Status = -1;
                return(View(userModels));
                // return Content("房产盒子提示:无效的参数!");
            }
            ViewBag.Info = info;
            ViewBag.From = from;
            info         = CryptoUtility.TripleDESDecrypt(info);
            userModels   = JsonConvert.DeserializeObject <UserModels>(info);
            if (userModels.IsNull())
            {
                ViewBag.Status = -1;
                return(View(userModels));
            }
            ViewBag.Uid = userModels.InviteUid > 0 ? CryptoUtility.TripleDESEncrypt(Convert.ToString(userModels.InviteUid)) : "";
            string tel = string.IsNullOrEmpty(userModels.Tel) ? "" : StringUtility.StripWhiteSpace(userModels.Tel.Replace("-", ""), false);

            if (tel.StartsWith("0"))
            {
                tel = tel.Substring(1);
            }
            userModels.Tel = tel;
            if (!StringUtility.ValidateMobile(userModels.Tel))
            {
                ViewBag.Status = -2;
                return(View(userModels));
                //  return Content("房产盒子提示:联合网用户手机号码格式不正确!");
            }
            if (string.IsNullOrEmpty(userModels.UserName))
            {
                ViewBag.Status = -3;
                return(View(userModels));
                //  return Content("房产盒子提示:用户名不能为空!");
            }
            if (string.IsNullOrEmpty(userModels.Company) && string.IsNullOrEmpty(userModels.Store))
            {
                ViewBag.Status = -4;
                return(View(userModels));
                // return Content("房产盒子提示:仅开放联合网房产经纪人注册!详情联系房产客服!");
            }
            publicUser =
                ncBase.CurrentEntities.PublicUser.Where(o => o.Tel == userModels.Tel).FirstOrDefault();
            if (publicUser.IsNoNull())
            {
                ViewBag.Status = -5;
                return(View(userModels));
            }
            publicUser =
                ncBase.CurrentEntities.PublicUser.Where(o => o.Name == userModels.UserName).FirstOrDefault();
            if (publicUser.IsNoNull())
            {
                userModels.UserName = userModels.UserName + "_" + userModels.UserId;
            }
            ViewBag.Status = 0;
            return(View(userModels));
        }
Esempio n. 26
0
        public virtual decimal ClampOrderPrice(string pair, decimal price)
        {
            ExchangeMarket market = Api.GetExchangeMarketFromCache(pair);

            return(market == null ? price : CryptoUtility.ClampDecimal(market.MinPrice, market.MaxPrice, market.PriceStepSize, price));
        }
Esempio n. 27
0
        public JsonResult DoRegister(PublicUserModel user, string code, string invitationCode)
        {
            bool isNeedCode = true;//是否需要手机短信验证码

            InvitationCode invitationEntity = new InvitationCode();

            #region 是否需要邀请码验证
            if (ConfigUtility.GetBoolValue("InvitationRegister") || !string.IsNullOrEmpty(invitationCode))
            {
                #region 判断 如果邀请码对应的手机号存在 则无需手机短信验证码 否则需要手机短信验证码

                invitationEntity = ncBase.CurrentEntities.InvitationCode.Where(i => i.Code == invitationCode && i.IsUsed == false).FirstOrDefault();
                if (invitationEntity.IsNull())
                {
                    return(Json(new { status = 1, msg = "邀请码不存在或已被使用" }));
                }
                user.VipType = (int)invitationEntity.VipType;
                if (!string.IsNullOrEmpty(invitationEntity.BindTel))
                {
                    user.Tel   = invitationEntity.BindTel; //邀请码有绑定手机号码,防止填入其他手机号码
                    isNeedCode = false;
                }
            }
            #endregion
            #endregion

            #region 表单验证
            if (string.IsNullOrEmpty(user.Tel))
            {
                return(Json(new { status = 1, msg = "手机号不能为空" }));
            }
            if (isNeedCode)
            {
                if (string.IsNullOrEmpty(code) || Session["Phone_Code" + user.Tel] == null || (code != "" && Session["Phone_Code" + user.Tel] != null && code != Session["Phone_Code" + user.Tel].ToString()))
                {
                    return(Json(new { status = 1, msg = "验证码错误" }));
                }
            }
            if (string.IsNullOrEmpty(user.Name))
            {
                return(Json(new { status = 1, msg = "用户名不能为空" }));
            }
            if (string.IsNullOrEmpty(user.Password) || (user.Password != null && user.Password.Length < 6))
            {
                return(Json(new { status = 1, msg = "密码至少6位数" }));
            }
            if (user.CityID <= 0)
            {
                return(Json(new { status = 1, msg = "所属城市必填" }));
            }
            if (user.CompanyId <= 0)
            {
                return(Json(new { status = 1, msg = "所属公司必填" }));
            }
            if (user.StoreId <= 0)
            {
                if (user.DistrictId <= 0 || user.RegionId <= 0)
                {
                    return(Json(new { status = 1, msg = "所属分店必填" }));
                }
            }
            #endregion
            user.IP          = Request.UserHostAddress;
            user.LastLoginIP = Request.UserHostAddress;
            user.VipType     = 0; //待审用户
            UserBll userBll = new UserBll();
            int     userid  = userBll.addPublicUser(user);
            if (userid == -1)
            {
                return(Json(new { status = 1, msg = "用户名已经存在" }));
            }
            else if (userid == -2)
            {
                return(Json(new { status = 1, msg = "手机号已被注册" }));
            }
            if (userid > 0)//自动登录
            {
                #region 邀请码状态更改
                if (ConfigUtility.GetBoolValue("InvitationRegister"))
                {
                    invitationEntity.IsUsed   = true;
                    invitationEntity.UsedTime = DateTime.Now;
                    invitationEntity.UsedUid  = userid;
                    ncBase.CurrentEntities.SaveChanges();
                }
                #endregion

                if (Session[user.Tel] != null)
                {
                    Session[user.Tel] = null;
                    Session.Remove(user.Tel);
                }
                PublicUserModel newUser = userBll.PublicUserLogin(user.Name, user.Password);
                String          saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"];
                if (String.IsNullOrEmpty(saveKey))
                {
                    saveKey = "WXLoginedUser";
                }
                Session[saveKey] = newUser;
                HttpCookie loginUserCookie = new HttpCookie(saveKey, CryptoUtility.TripleDESEncrypt(newUser.UserID.ToString()));
                loginUserCookie.Expires = DateTime.Now.AddDays(10);
                HttpContext.Response.Cookies.Add(loginUserCookie);
            }
            return(Json(new { status = 0, msg = "注册成功" }));
        }
Esempio n. 28
0
 public static string MD5(this byte[] bytes)
 {
     return(CryptoUtility.MD5(bytes));
 }
Esempio n. 29
0
 public override string PeriodSecondsToString(int seconds)
 {
     return(CryptoUtility.SecondsToPeriodStringLong(seconds));
 }
Esempio n. 30
0
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a blob returned with this SAS.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <param name="resource">Resource type identifier (e.g. "b", "c", "bs").</param>
        /// <param name="snapshotTimestamp">Timestamp of the snapshot for a snapshot-only SAS, null otherwise.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            SharedAccessProtocol?protocols,
            IPAddressOrRange ipAddressOrRange,
            byte[] keyValue,
            string resource,
            DateTimeOffset?snapshotTimestamp = null)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);
            CommonUtility.AssertNotNullOrEmpty("resource", resource);

            string         permissions = null;
            DateTimeOffset?startTime   = null;
            DateTimeOffset?expiryTime  = null;

            if (policy != null)
            {
                permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                startTime   = policy.SharedAccessStartTime;
                expiryTime  = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedIP + "\n" +
            ////                     signedProtocol + "\n" +
            ////                     signedversion + "\n" +
            ////                     signedresource + "\n" +
            ////                     signedTimeStamp + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////

            string cacheControl       = null;
            string contentDisposition = null;
            string contentEncoding    = null;
            string contentLanguage    = null;
            string contentType        = null;

            if (headers != null)
            {
                cacheControl       = headers.CacheControl;
                contentDisposition = headers.ContentDisposition;
                contentEncoding    = headers.ContentEncoding;
                contentLanguage    = headers.ContentLanguage;
                contentType        = headers.ContentType;
            }

            string snapTime = null;

            if (snapshotTimestamp.HasValue)
            {
                snapTime = Request.ConvertDateTimeToSnapshotString(snapshotTimestamp.Value);
            }

            string stringToSign = string.Format(
                CultureInfo.InvariantCulture,
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}\n{13}\n{14}",
                permissions,
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(startTime),
                SharedAccessSignatureHelper.GetDateTimeOrEmpty(expiryTime),
                resourceName,
                accessPolicyIdentifier,
                ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                SharedAccessSignatureHelper.GetProtocolString(protocols),
                sasVersion,
                resource,
                snapTime,
                cacheControl,
                contentDisposition,
                contentEncoding,
                contentLanguage,
                contentType);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return(CryptoUtility.ComputeHmac256(keyValue, stringToSign));
        }