Example #1
0
        /// <summary>
        /// Create list scrums
        /// </summary>
        /// <param name="url"></param>
        /// <param name="post"></param>
        /// <returns></returns>
        public static List <ScrumData> CreateScrums(System.Web.Mvc.UrlHelper url, PostDataModel post)
        {
            List <ScrumData> scrums = new List <ScrumData>();

            if (post == null || url == null)
            {
                return(scrums);
            }
            // Add Home page
            ScrumData homePage = new ScrumData()
            {
                Link = url.Action("Index", "Home"),
                Name = "Trang Chủ"
            };

            scrums.Add(homePage);
            // Add link catalogic
            ScrumData cataPage = new ScrumData()
            {
                Link = url.Action("Index", "Home"),
                Name = post.CatalogicName
            };

            scrums.Add(cataPage);
            // Add Post
            ScrumData postText = new ScrumData()
            {
                Link = string.Empty,
                Name = post.Title
            };

            scrums.Add(postText);
            return(scrums);
        }
        /// <summary>
        /// Gets widget render url
        /// </summary>
        /// <param name="httpContext">The http context.</param>
        /// <param name="website">The website name</param>
        /// <param name="locale">The locale name.</param>
        /// <returns></returns>
        public string GetContentUrl(HttpContextBase httpContext, string website = "home", string locale = "en-US")
        {
            var contentUrl = "";
            var Url        = new System.Web.Mvc.UrlHelper(httpContext.Request.RequestContext);

            if (!string.IsNullOrEmpty(Controller) && !string.IsNullOrEmpty(Action))
            {
                contentUrl = !string.IsNullOrEmpty(website) ? Url.Action(Action, ControllerShortName, new { Area = string.IsNullOrEmpty(this.Area) ? "" : this.Area, website = website, id = this.ID, preview = true }) : Url.Action(this.Action, this.ControllerShortName, new { Area = string.IsNullOrEmpty(this.Area) ? "" : this.Area, id = this.ID, preview = true });
            }
            else
            {
                contentUrl = !string.IsNullOrEmpty(website) ? Url.Action("Generic", "Widget", new { Area = "", website = website, id = this.ID, preview = true }) : Url.Action("Generic", "Widget", new { Area = "", id = this.ID, preview = true });
            }
            return(contentUrl);
        }
Example #3
0
        /// <summary>
        /// Generates a fully qualified URL to an action method
        /// </summary>
        public static string Action <TController>(this System.Web.Mvc.UrlHelper urlHelper, Expression <Action <TController> > action)
            where TController : System.Web.Mvc.Controller
        {
            RouteValueDictionary rvd = InternalExpressionHelper.GetRouteValues(action);

            return(urlHelper.Action(null, null, rvd));
        }
Example #4
0
        public async Task <IHttpActionResult> AddNewUser(int agentId, agentadmin item)
        {
            IdentityResult result    = null;
            var            userModel = new Models.ApplicationUser {
                Email = item.Email, UserName = item.Email
            };

            try
            {
                Random rand     = new Random();
                var    password = Helper.GetRandomAlphanumericString(6) + "3#";
                result = await UserManager.CreateAsync(userModel, password);

                if (result.Succeeded)
                {
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(userModel.Id);

                    System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
                    string callbackUrl = urlHelper.Action(
                        "ConfirmEmail",
                        "Account",
                        new { userId = userModel.Id, code = code },
                        HttpContext.Current.Request.Url.Scheme
                        );

                    await UserManager.SendEmailAsync(userModel.Id, "Confirm your account", "Your Password : "******" , and Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

                    if (!await RoleManager.RoleExistsAsync("agent"))
                    {
                        var roleCreate = RoleManager.Create(new IdentityRole("3", "Agent"));
                        if (!roleCreate.Succeeded)
                        {
                            throw new SystemException("User Tidak Berhasil Ditambah");
                        }
                    }
                    var addUserRole = await UserManager.AddToRoleAsync(userModel.Id, "Agent");

                    if (!addUserRole.Succeeded)
                    {
                        throw new SystemException("User Tidak Berhasil Ditambah");
                    }

                    item.UserId = userModel.Id;
                    var user = agentContext.AddNewUser(agentId, item);
                    if (user != null)
                    {
                        return(Ok(user));
                    }
                }
                throw new SystemException("User Tidak Berhasil Ditambah");
            }
            catch (Exception ex)
            {
                if (result != null && result.Succeeded)
                {
                    UserManager.Delete(userModel);
                }
                return(BadRequest(ex.Message));
            }
        }
Example #5
0
 public ItemData(string text, string Accion, string Controler, long IdModulo)
 {
     Text        = text;
     NavigateUrl = null;
     if (!string.IsNullOrEmpty(Accion))
     {
         NavigateUrl = urlHelper.Action(Accion, Controler, new { modId = IdModulo });
     }
 }
 /// <summary>
 /// 指定したController, Actionを行う単一フォームのボタンを生成する.
 /// </summary>
 /// <param name="helper"></param>
 /// <param name="label"></param>
 /// <param name="action"></param>
 /// <param name="controller"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static IHtmlString ActionButton(this HtmlHelper helper, string label, string action, string controller, object options)
 {
     var url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
     TagBuilder builder = new TagBuilder("form");
     builder.MergeAttribute("action", url.Action(action, controller, options));
     builder.MergeAttribute("method", "get");
     IHtmlString btn = SubmitButton(helper, label, null);
     return MvcHtmlString.Create(builder.ToString(TagRenderMode.StartTag) + btn + builder.ToString(TagRenderMode.EndTag));
 }
        // <a> タグ作成(IHtmlString)
        public static IHtmlString ActionImage(this HtmlHelper html, string actionName, string controllerName, string imagePath, string alternateText)
        {
            var url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            var builder = new TagBuilder("a");
            builder.MergeAttribute("href", url.Action(actionName, controllerName));
            builder.InnerHtml = ImageString(html, imagePath, alternateText);

            return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
        }
        /// <summary>
        /// 指定したController, Actionを行う単一フォームのボタンを生成する.
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="label"></param>
        /// <param name="action"></param>
        /// <param name="controller"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IHtmlString ActionButton(this HtmlHelper helper, string label, string action, string controller, object options)
        {
            var        url     = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
            TagBuilder builder = new TagBuilder("form");

            builder.MergeAttribute("action", url.Action(action, controller, options));
            builder.MergeAttribute("method", "get");
            IHtmlString btn = SubmitButton(helper, label, null);

            return(MvcHtmlString.Create(builder.ToString(TagRenderMode.StartTag) + btn + builder.ToString(TagRenderMode.EndTag)));
        }
Example #9
0
        public static string AbsoluteAction(this System.Web.Mvc.UrlHelper url, string action, string controller, object routeValues)
        {
            Uri requestUrl = url.RequestContext.HttpContext.Request.Url;

            string absoluteAction = string.Format("{0}://{1}{2}",
                                                  requestUrl.Scheme,
                                                  requestUrl.Authority,
                                                  url.Action(action, controller, routeValues));

            return(absoluteAction);
        }
        // <a> タグ作成(IHtmlString)
        public static IHtmlString ActionImage(this HtmlHelper html, string actionName, string controllerName, string imagePath, string alternateText)
        {
            var url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            var builder = new TagBuilder("a");

            builder.MergeAttribute("href", url.Action(actionName, controllerName));
            builder.InnerHtml = ImageString(html, imagePath, alternateText);

            return(MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal)));
        }
Example #11
0
        public void Issue218_Url_generation_with_optional_query_params()
        {
            // re: issue #218

            var routes = RouteTable.Routes;

            routes.Clear();
            routes.MapAttributeRoutes(config => config.AddRoutesFromController <Issue218TestController>());
            RouteTable.Routes.Cast <Route>().LogTo(Console.Out);

            var urlHelper = new UrlHelper(MockBuilder.BuildRequestContext());

            Assert.That(urlHelper.Action("NoQuery", "Issue218Test", new { categoryId = 12 }),
                        Is.EqualTo("/Issue-218/No-Query?categoryId=12"));

            Assert.That(urlHelper.Action("OptionalQuery", "Issue218Test", new { categoryId = 12 }),
                        Is.EqualTo("/Issue-218/Optional-Query?categoryId=12"));

            Assert.That(urlHelper.Action("DefaultQuery", "Issue218Test"),
                        Is.EqualTo("/Issue-218/Default-Query?categoryId=123"));
        }
Example #12
0
        public void Issue161_Querystring_param_constraints_mucks_up_url_generation()
        {
            // re: issue #161

            var routes = RouteTable.Routes;
            routes.Clear();
            routes.MapAttributeRoutes(config => config.AddRoutesFromController<Issue161TestController>());

            var urlHelper = new UrlHelper(MockBuilder.BuildRequestContext());
            var routeValues = new { area = "Cms", culture = "en", p = 1 };
            var expectedUrl = urlHelper.Action("Index", "Issue161Test", routeValues);

            Assert.That(expectedUrl, Is.EqualTo("/en/Cms/Content/Items?p=1"));
        }
Example #13
0
        public void Issue161_Querystring_param_constraints_mucks_up_url_generation()
        {
            // re: issue #161

            var routes = RouteTable.Routes;

            routes.Clear();
            routes.MapAttributeRoutes(config => config.AddRoutesFromController <Issue161TestController>());

            var urlHelper   = new UrlHelper(MockBuilder.BuildRequestContext());
            var routeValues = new { area = "Cms", culture = "en", p = 1 };
            var expectedUrl = urlHelper.Action("Index", "Issue161Test", routeValues);

            Assert.That(expectedUrl, Is.EqualTo("/en/Cms/Content/Items?p=1"));
        }
Example #14
0
        public void Init()
        {
            if (!_init)
            {
                lock (_lock)
                {
                    if (!_init)
                    {
                        _cachedBinaryResources = new Dictionary<string, byte[]>();
                        _cachedTextResources = new Dictionary<string, string>();


                        string script = GetTextResource("MVCGrid.js");
                        var handlerPath = HttpContext.Current.Request.CurrentExecutionFilePath;
                        script = script.Replace("%%HANDLERPATH%%", handlerPath);

                        bool showErrorDetails = ConfigUtility.GetShowErrorDetailsSetting();
                        script = script.Replace("%%ERRORDETAILS%%", showErrorDetails.ToString().ToLower());
                        

                        var controllerPath = HttpContext.Current.Request.ApplicationPath;
                        controllerPath += "mvcgrid/grid";

                        try
                        {
                            var urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                            controllerPath = urlHelper.Action("Grid", "MVCGrid");
                        }
                        catch { }

                        script = script.Replace("%%CONTROLLERPATH%%", controllerPath);

                        _cachedTextResources.Add("MVCGrid.js", script);
                        _cachedTextResources.Add("spin.min.js", GetTextResource("spin.min.js"));

                        _cachedBinaryResources.Add("sort.png", GetBinaryResource("sort.png"));
                        _cachedBinaryResources.Add("sortdown.png", GetBinaryResource("sortdown.png"));
                        _cachedBinaryResources.Add("sortup.png", GetBinaryResource("sortup.png"));

                        _init = true;
                    }
                }
            }
        }
Example #15
0
        public void Init()
        {
            if (!_init)
            {
                lock (_lock)
                {
                    if (!_init)
                    {
                        _cachedBinaryResources = new Dictionary <string, byte[]>();
                        _cachedTextResources   = new Dictionary <string, string>();


                        string script      = GetTextResource("MVCGrid.js");
                        var    handlerPath = HttpContext.Current.Request.CurrentExecutionFilePath;
                        script = script.Replace("%%HANDLERPATH%%", handlerPath);

                        bool showErrorDetails = ConfigUtility.GetShowErrorDetailsSetting();
                        script = script.Replace("%%ERRORDETAILS%%", showErrorDetails.ToString().ToLower());


                        var controllerPath = HttpContext.Current.Request.ApplicationPath;
                        controllerPath += "mvcgrid/grid";

                        try
                        {
                            var urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                            controllerPath = urlHelper.Action("Grid", "MVCGrid");
                        }
                        catch { }

                        script = script.Replace("%%CONTROLLERPATH%%", controllerPath);

                        _cachedTextResources.Add("MVCGrid.js", script);
                        _cachedTextResources.Add("spin.min.js", GetTextResource("spin.min.js"));

                        _cachedBinaryResources.Add("sort.png", GetBinaryResource("sort.png"));
                        _cachedBinaryResources.Add("sortdown.png", GetBinaryResource("sortdown.png"));
                        _cachedBinaryResources.Add("sortup.png", GetBinaryResource("sortup.png"));

                        _init = true;
                    }
                }
            }
        }
Example #16
0
        /// <summary>
        /// 生成Url.
        /// </summary>
        /// <returns>The action.</returns>
        /// <param name="urlHelper">URL helper.</param>
        /// <param name="actionName">Action name.</param>
        /// <param name="controllerName">Controller name.</param>
        /// <param name="routeValues">Route values.</param>
        public static string RetechAction(this System.Web.Mvc.UrlHelper urlHelper, string actionName,
                                          string controllerName, object routeValues)
        {
            var    rv = new RouteValueDictionary(routeValues);
            object areaName;
            var    hasArea = rv.TryGetValue("area", out areaName);

            if (!hasArea)
            {
                return(urlHelper.Action(actionName, controllerName, rv));
            }
            var mainHostName = ConfigurationManager.AppSettings["mainSite"];
            var areaNameStr  = areaName == null ? "" : areaName.ToString();
            var hostName     = areaServers.ContainsKey(areaNameStr) ? areaServers[areaNameStr] : mainHostName;

            var url = System.Web.Mvc.UrlHelper.GenerateUrl(null, actionName, controllerName, null, hostName, null, rv,
                                                           urlHelper.RouteCollection, urlHelper.RequestContext, true);

            return(url);
        }
Example #17
0
        private async Task <string> SendEmailConfirmationTokenAsync(string userID, string subject)
        {
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);

            var user = await UserManager.FindByIdAsync(userID);

            System.Web.Mvc.UrlHelper Url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
            var callbackUrl = Url.Action("ConfirmEmail", "Account",
                                         new { userId = userID, code = code }, protocol: HttpContext.Current.Request.Url.Scheme);
            var message = await PensionSetup.EmailTemplate("_Email");

            var Username = PensionSetup.GetMemberNamesAsync(user.Email, user);

            message = message.Replace("@ViewBag.Name", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Username));
            //message = message.Replace("@ViewBag.Link", "intent:#Intent;action=ke.co.synobrain.alexanderforbes;category=android.intent.category.DEFAULT;category=android.intent.category.BROWSABLE;S.msg_from_browser=Launched%20from%20Browser;end");
            message = message.Replace("@ViewBag.Link", callbackUrl);
            message = message.Replace("@ViewBag.Subject", subject);
            await UserManager.SendEmailAsync(userID, subject, message);

            return(callbackUrl);
        }
Example #18
0
        // Returns the activation code
        public string SendActivationEmail()
        {
            // Get an instance of request to create the Url
            var httpContext    = HttpContext.Current;
            var requestContext = httpContext.Request.RequestContext;
            var urlHelper      = new System.Web.Mvc.UrlHelper(requestContext);

            string code        = UserManager.GenerateEmailConfirmationToken(User.Id);
            string callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { userId = User.Id, code = code, returnUrl = urlHelper.Action("Create", "Applications") }, protocol: httpContext.Request.Url.Scheme);
            string abbr        = Settings.COMPANY_ABBR;

            System.Text.StringBuilder body = new System.Text.StringBuilder()
                                             .AppendFormat("<p>Dear <strong>{0} {1}</strong></p>", User.FirstName, User.LastName)
                                             .AppendFormat("<p>An account as been created for you on {0}. ", Settings.COMPANY_NAME)
                                             .AppendFormat(@"In order to proceed and login into the system you must verify your email address by clicking this <a href=""{0}"">activation link</a></p>", callbackUrl);

            string subject = abbr + " - Confirm your email";

            UserManager.SendEmail(User.Id, subject, body.ToString());

            return(callbackUrl);
        }
Example #19
0
        /// <summary>
        /// 生成Url.
        /// </summary>
        /// <returns>The action.</returns>
        /// <param name="urlHelper">URL helper.</param>
        /// <param name="actionName">Action name.</param>
        /// <param name="controllerName">Controller name.</param>
        /// <param name="routeValues">Route values.</param>
        public static string RetechAction(this System.Web.Mvc.UrlHelper urlHelper, string actionName,
                                          string controllerName, object routeValues)
        {
            var    rv = new RouteValueDictionary(routeValues);
            object areaName;
            var    hasArea = rv.TryGetValue("area", out areaName);

            if (!hasArea)
            {
                return(urlHelper.Action(actionName, controllerName, rv));
            }

            var    mainHostName = ConfigurationManager.AppSettings["mainSite"];
            var    areaNameStr  = areaName == null ? "" : areaName.ToString();
            var    hostName     = UrlGenerateConfig.AreaServers.ContainsKey(areaNameStr) ? UrlGenerateConfig.AreaServers[areaNameStr] : mainHostName;
            string sitePort     = ConfigurationManager.AppSettings["sitePort"];

            if (sitePort != "80")
            {
                hostName += ":" + sitePort;
            }


            var url =
                System.Web.Mvc.UrlHelper.GenerateUrl(null, actionName, controllerName, rv,
                                                     urlHelper.RouteCollection, urlHelper.RequestContext, true);

            if (url != null)
            {
                Uri    requestUrl      = urlHelper.RequestContext.HttpContext.Request.Url;
                string requestProtocol = requestUrl.Scheme;
                url = requestProtocol + Uri.SchemeDelimiter + hostName + url;
            }

            // System.Web.Mvc.UrlHelper.GenerateUrl(null, actionName, controllerName, null, hostName, null, rv,
            // urlHelper.RouteCollection, urlHelper.RequestContext, true);
            return(url);
        }
Example #20
0
        public BreadcrumbViewModel GetBreadcrumbNodes(int categoryId)
        {
            Category category  = Find(categoryId);
            var      nodes     = new List <Tuple <string, string> >();
            int      count     = 0;
            var      urlHelper = new UrlHelper(httpRequest.RequestContext);

            while (++count < 10)
            {
                nodes.Insert(0,
                             new Tuple <string, string>(
                                 urlHelper.Action("Details", "Category", new { id = category.Id, slug = @category.Name.ToSlug() }),
                                 category.Name));

                if (category.ParentId == null)
                {
                    break;
                }
                category = category.Parent;
            }
            return(new BreadcrumbViewModel {
                Nodes = nodes
            });
        }
Example #21
0
        private async Task <string> SendEmailConfirmationTokenAsync(string userID, string subject)
        {
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);

            // var newRouteValues = new RouteValueDictionary(new { userId = userID, code = code });
            //newRouteValues.Add("httproute", true);
            System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
            string callbackUrl = urlHelper.Action(
                "ConfirmEmail",
                "Account",
                new { userId = userID, code = code },
                HttpContext.Current.Request.Url.Scheme
                );
            string           emailBody = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>";
            DailyMailService dailyMail = new DailyMailService();
            string           username  = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(userID).UserName;

            dailyMail.SendMailWithoutAttachment(username, "*****@*****.**", "confirm Email", emailBody);

            //await UserManager.SendEmailAsync(userID, subject,
            //"Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            return(callbackUrl);
        }
Example #22
0
        /// <summary>
        /// 创建搜索框
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="type"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static string Search(this System.Web.Mvc.HtmlHelper helper, Type type, object parms)
        {
            List <string> plist     = new List <string>();//可查询属性 列表
            UrlHelper     UrlHelper = new System.Web.Mvc.UrlHelper(helper.ViewContext.RequestContext);

            var propertys = type.GetProperties();

            foreach (var p in propertys)
            {
                object[] alist = p.GetCustomAttributes(typeof(SearchAttribute), false);
                if (alist.Length > 0)
                {
                    SearchAttribute sa = alist[0] as SearchAttribute;
                    if (sa == null)
                    {
                        continue;
                    }

                    var           ls = sa.getInputFiles(p);
                    StringBuilder sb = new StringBuilder();
                    foreach (var l in ls)
                    {
                        var value       = sa.getValue(p.Name, helper.ViewContext.HttpContext.Request);
                        var displayname = ((DisplayAttribute[])p.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
                        sb.Append(string.Format("<label for='{0}' >{2}</label><input type='text' name='{0}' id='{0}' value='{1}' >", p.Name, value, displayname.Name));
                    }
                    plist.Add(string.Format("<span>{0}</span>", sb.ToString()));//获取类型绑定的search对象
                }
            }

            if (plist.Count == 0)
            {
                return("");
            }
            string actionName = helper.ViewContext.RouteData.Values["action"].ToString();
            string result     = string.Format("<div class='query-content'><form action='{0}' name='form-{1}' id='form-{1}'> {2} <span><input type='submit' value='查询'></span><form></div>", UrlHelper.Action(actionName, parms), type.Name, string.Join("", plist.ToArray()));

            return(result);
        }
Example #23
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var dbTransaction = db.Database.BeginTransaction())
            {
                ApplicationUser applicationUser = db.Users.Where(b => (b.Email.Equals(model.Email))).SingleOrDefault();
                if (applicationUser != null)
                {
                    return(Ok(new CreateUserResponse(CreateUserResult.THE_USER_WITH_REQUESTED_USERNAME_ALREADY_EXISTS, DateTime.UtcNow)));
                }
                else
                {
                    var user = new ApplicationUser()
                    {
                        UserName = model.Email, Email = model.Email
                    };

                    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }

                    try
                    {
                        //UserManager.EmailService = new EmailService();
                        // var provider = new DpapiDataProtectionProvider();
                        // UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("ASP.NET Identity"));
                        var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        var newRouteValues = new RouteValueDictionary(new { userId = user.Id, code = code });
                        newRouteValues.Add("httproute", true);
                        System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
                        string callbackUrl = urlHelper.Action(
                            "ConfirmEmail",
                            "Account",
                            newRouteValues,
                            HttpContext.Current.Request.Url.Scheme
                            );
                        var x = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/Account/ConfirmEmail?";
                        var t = HttpContext.Current.Request.Url.Port;
                        callbackUrl = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + ((HttpContext.Current.Request.Url.Port == 80 || HttpContext.Current.Request.Url.Port == 443) ? "" : (":" + HttpContext.Current.Request.Url.Port)) + "/Account/ConfirmEmail?" + "userId=" + HttpUtility.UrlEncode(user.Id) + "&" + "code=" + HttpUtility.UrlEncode(code);
                        string emailBody = "<a href='" + callbackUrl + "'Please click Here to confirm your email</a>";
                        await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.ToString());
                    }

                    //  var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    //await UserManager.SendEmailAsync(user.Id, "Confirm your account", callbackUrl);

                    db.SaveChanges();

                    dbTransaction.Commit();

                    return(Ok(new CreateUserResponse(CreateUserResult.SUCCESS, DateTime.UtcNow)));
                }
            }
        }
Example #24
0
        public static string FullActionUrl(this System.Web.Mvc.UrlHelper url, string actionName, string controllerName, object routeValues = null)
        {
            string webUrl = System.Configuration.ConfigurationManager.AppSettings["WebUrl"].TrimEnd('/');

            return(webUrl + url.Action(actionName, controllerName, routeValues));
        }
Example #25
0
        public IHttpActionResult adviserCreateNewClient_Person(PersonClientCreationBindingModel model)
        {
            //if (!ModelState.IsValid) {
            //    var errors = ModelState.Select(x => x.Value.Errors)
            //               .Where(y => y.Count > 0)
            //               .ToList();
            //}
            if (model != null)                                          //  deleted   && ModelState.IsValid         must put it back afterward
            {
                #region create asp user and send email
                var user = new ApplicationUser
                {
                    Email       = model.email,
                    UserName    = model.email,
                    PhoneNumber = model.contactPhone
                };
                var password    = "******";//Membership.GeneratePassword(10, 0);
                var userManager = Request.GetOwinContext().GetUserManager <ApplicationUserManager>();
                userManager.Create(user, password);
                userManager.AddToRole(user.Id, AuthorizationRoles.Role_Preclient);
                //EmailUtilities.SendEmailToUser(user.Id, "", "", "");//send password
                #endregion



                #region create client profile
                ClientRegistration client = new ClientRegistration
                {
                    CreateOn     = DateTime.Now,
                    ClientNumber = user.Id,
                    FirstName    = model.firstName,
                    MiddleName   = model.middleName,
                    Email        = model.email,
                    LastName     = model.lastName,
                    Phone        = model.contactPhone,
                    ClientType   = BusinessLayerParameters.clientType_person,
                };
                #endregion

                #region create client group or add to existing group
                if (model.isGroupLeader.HasValue && model.isGroupLeader.Value)
                {
                    var adviserNumber             = User.Identity.GetUserId();
                    ClientGroupRegistration group = new ClientGroupRegistration
                    {
//#warning adviser number needs replacement
                        AdviserNumber = adviserNumber,
                        GroupAmount   = model.newGroupAmount,
                        GroupName     = model.newGroupAccountName,
                        CreateOn      = DateTime.Now,
                        client        = client,
                    };
                    edisRepo.CreateNewClientGroupSync(group);
                }
                else
                {
                    client.GroupNumber = model.existingGroupId;
                    edisRepo.CreateNewClientSync(client);
                }

                using (DocX document = DocX.Create("C:\\Test\\" + client.FirstName + "_" + client.LastName + ".docx"))
                {
                    Paragraph paragraph = document.InsertParagraph();
                    paragraph.AppendLine(ClientDocInfo.FirstName + model.firstName);
                    paragraph.AppendLine(ClientDocInfo.MiddleName + model.middleName);
                    paragraph.AppendLine(ClientDocInfo.LastName + model.lastName);
                    paragraph.AppendLine(ClientDocInfo.Email + model.email);
                    paragraph.AppendLine(ClientDocInfo.ContactPhone + model.contactPhone);
                    document.Save();
                }

                string code        = userManager.GenerateEmailConfirmationTokenAsync(user.Id).Result;
                string path        = HttpContext.Current.Server.MapPath("~/EmailTemplate/ConfirmEmail.html");
                var    Url         = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Current.Request.Url.Scheme);
                string content     = System.IO.File.ReadAllText(path).Replace("###Name###", user.UserName).Replace("###Confirm###", callbackUrl);
                userManager.SendEmailAsync(user.Id, "Confirm your account", content);

                #endregion


                #region create risk profile if present
                if (model.riskProfile != null)
                {
                    var         riskProfile = model.riskProfile;
                    RiskProfile profile     = new RiskProfile {
                        CapitalLossAttitude    = riskProfile.capitalLossAttitude,
                        ClientID               = edisRepo.GetClientSync(user.Id, DateTime.Now).Id,
                        Comments               = riskProfile.comments,
                        DateCreated            = DateTime.Now,
                        DateModified           = DateTime.Now,
                        IncomeSource           = riskProfile.incomeSource,
                        InvestmentKnowledge    = riskProfile.investmentKnowledge,
                        InvestmentObjective1   = riskProfile.investmentObjective1,
                        InvestmentObjective2   = riskProfile.investmentObjective2,
                        InvestmentObjective3   = riskProfile.investmentObjective3,
                        InvestmentProfile      = riskProfile.investmentProfile,
                        InvestmentTimeHorizon  = riskProfile.investmentTimeHorizon,
                        LongTermGoal1          = riskProfile.longTermGoal1,
                        LongTermGoal2          = riskProfile.longTermGoal2,
                        LongTermGoal3          = riskProfile.longTermGoal3,
                        MedTermGoal1           = riskProfile.medTermGoal1,
                        MedTermGoal2           = riskProfile.medTermGoal2,
                        MedTermGoal3           = riskProfile.medTermGoal3,
                        RetirementAge          = string.IsNullOrEmpty(riskProfile.retirementAge) ? (int?)null : Convert.ToInt32(riskProfile.retirementAge),
                        RetirementIncome       = riskProfile.retirementIncome,
                        RiskAttitude           = riskProfile.riskAttitude,
                        ShortTermAssetPercent  = riskProfile.shortTermAssetPercent,
                        ShortTermEquityPercent = riskProfile.shortTermEquityPercent,
                        ShortTermGoal1         = riskProfile.shortTermGoal1,
                        ShortTermGoal2         = riskProfile.shortTermGoal2,
                        ShortTermGoal3         = riskProfile.shortTermGoal3,
                        ShortTermTrading       = riskProfile.shortTermTrading,
                        riskLevel              = Int32.Parse(riskProfile.riskLevel)
                    };
                    edisRepo.CreateRiskProfileForClient(profile);
                }
                #endregion

                //#region save all changes and return ok
                //db.SaveChanges();
                return(Ok());
                //#endregion
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
        public IHttpActionResult adviserCreateNewClient_Person(PersonClientCreationBindingModel model)
        {
            //if (!ModelState.IsValid) {
            //    var errors = ModelState.Select(x => x.Value.Errors)
            //               .Where(y => y.Count > 0)
            //               .ToList();
            //}
            if (model != null)                                          //  deleted   && ModelState.IsValid         must put it back afterward
            {
                
                #region create asp user and send email
                var user = new ApplicationUser
                {
                    Email = model.email,
                    UserName = model.email,
                    PhoneNumber = model.contactPhone
                };
                var password = "******";//Membership.GeneratePassword(10, 0);
                var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
                userManager.Create(user, password);
                userManager.AddToRole(user.Id, AuthorizationRoles.Role_Preclient);
                //EmailUtilities.SendEmailToUser(user.Id, "", "", "");//send password
                #endregion



                #region create client profile
                ClientRegistration client = new ClientRegistration
                {
                    CreateOn = DateTime.Now,
                    ClientNumber = user.Id,
                    FirstName = model.firstName,
                    MiddleName = model.middleName,
                    Email = model.email,
                    LastName = model.lastName,
                    Phone = model.contactPhone,                        
                    ClientType = BusinessLayerParameters.clientType_person,                      
                };
                #endregion

                #region create client group or add to existing group
                if (model.isGroupLeader.HasValue && model.isGroupLeader.Value)
                {
                    var adviserNumber = User.Identity.GetUserId();
                    ClientGroupRegistration group = new ClientGroupRegistration
                    {
//#warning adviser number needs replacement
                        AdviserNumber = adviserNumber,
                        GroupAmount = model.newGroupAmount,
                        GroupName = model.newGroupAccountName,
                        CreateOn = DateTime.Now,
                        client = client,
                    };
                    edisRepo.CreateNewClientGroupSync(group);

                }
                else
                {
                    client.GroupNumber = model.existingGroupId;
                    edisRepo.CreateNewClientSync(client);
                }

                using (DocX document = DocX.Create("C:\\Test\\"+ client.FirstName + "_" + client.LastName +".docx"))
                {
                    Paragraph paragraph = document.InsertParagraph();
                    paragraph.AppendLine(ClientDocInfo.FirstName + model.firstName);
                    paragraph.AppendLine(ClientDocInfo.MiddleName + model.middleName);
                    paragraph.AppendLine(ClientDocInfo.LastName + model.lastName);
                    paragraph.AppendLine(ClientDocInfo.Email + model.email);
                    paragraph.AppendLine(ClientDocInfo.ContactPhone + model.contactPhone);
                    document.Save();
                }

                string code = userManager.GenerateEmailConfirmationTokenAsync(user.Id).Result;
                string path = HttpContext.Current.Server.MapPath("~/EmailTemplate/ConfirmEmail.html");
                var Url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Current.Request.Url.Scheme);
                string content = System.IO.File.ReadAllText(path).Replace("###Name###", user.UserName).Replace("###Confirm###", callbackUrl);
                userManager.SendEmailAsync(user.Id, "Confirm your account", content);

                #endregion


                #region create risk profile if present
                if (model.riskProfile != null) {
                    var riskProfile = model.riskProfile;
                    RiskProfile profile = new RiskProfile {
                        CapitalLossAttitude = riskProfile.capitalLossAttitude,
                        ClientID = edisRepo.GetClientSync(user.Id, DateTime.Now).Id,
                        Comments = riskProfile.comments,
                        DateCreated = DateTime.Now,
                        DateModified = DateTime.Now,
                        IncomeSource = riskProfile.incomeSource,
                        InvestmentKnowledge = riskProfile.investmentKnowledge,
                        InvestmentObjective1 = riskProfile.investmentObjective1,
                        InvestmentObjective2 = riskProfile.investmentObjective2,
                        InvestmentObjective3 = riskProfile.investmentObjective3,
                        InvestmentProfile = riskProfile.investmentProfile,
                        InvestmentTimeHorizon = riskProfile.investmentTimeHorizon,
                        LongTermGoal1 = riskProfile.longTermGoal1,
                        LongTermGoal2 = riskProfile.longTermGoal2,
                        LongTermGoal3 = riskProfile.longTermGoal3,
                        MedTermGoal1 = riskProfile.medTermGoal1,
                        MedTermGoal2 = riskProfile.medTermGoal2,
                        MedTermGoal3 = riskProfile.medTermGoal3,
                        RetirementAge = string.IsNullOrEmpty(riskProfile.retirementAge) ? (int?)null : Convert.ToInt32(riskProfile.retirementAge),
                        RetirementIncome = riskProfile.retirementIncome,
                        RiskAttitude = riskProfile.riskAttitude,
                        ShortTermAssetPercent = riskProfile.shortTermAssetPercent,
                        ShortTermEquityPercent = riskProfile.shortTermEquityPercent,
                        ShortTermGoal1 = riskProfile.shortTermGoal1,
                        ShortTermGoal2 = riskProfile.shortTermGoal2,
                        ShortTermGoal3 = riskProfile.shortTermGoal3,
                        ShortTermTrading = riskProfile.shortTermTrading,
                        riskLevel = Int32.Parse(riskProfile.riskLevel)
                    };
                    edisRepo.CreateRiskProfileForClient(profile);
                }
                #endregion

                //#region save all changes and return ok
                //db.SaveChanges();
                return Ok();
                //#endregion

            }
            else
            { 
                return BadRequest(ModelState);
            }
        }
Example #27
0
 public static string Image(this System.Web.Mvc.UrlHelper url,
                            string actionName, string controllerName, Image image)
 {
     return(url.Action(actionName, controllerName, new { imageId = image.ImageId }));
 }
        public IHttpActionResult adviserCreateNewClient_Entity(EntityClientCreationBindingModel model)
        {
            if (model != null)          //ModelState.IsValid &&
            {
                using (EdisRepository edisRepo = new EdisRepository())
                {
                    #region create asp user and send email
                    var user = new ApplicationUser
                    {
                        Email       = model.email,
                        UserName    = model.email,
                        PhoneNumber = model.contactPhone
                    };
                    var password    = "******";//Membership.GeneratePassword(10, 0);
                    var userManager = Request.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    userManager.Create(user, password);
                    userManager.AddToRole(user.Id, AuthorizationRoles.Role_Preclient);
                    //EmailUtilities.SendEmailToUser(user.Id, "", "", "");//send password
                    #endregion

                    #region create client profile
                    ClientRegistration client = new ClientRegistration
                    {
                        CreateOn     = DateTime.Now,
                        ClientNumber = user.Id,
                        EntityName   = model.nameOfEntity,
                        EntityType   = model.typeOfEntity,
                        ABN          = model.abn,
                        ACN          = model.acn,
                        Email        = model.email,
                        Phone        = model.contactPhone,
                        ClientType   = BusinessLayerParameters.clientType_entity,
                        GroupNumber  = model.existingGroupId
                    };

                    string code        = userManager.GenerateEmailConfirmationTokenAsync(user.Id).Result;
                    string path        = HttpContext.Current.Server.MapPath("~/EmailTemplate/ConfirmEmail.html");
                    var    Url         = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                    var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Current.Request.Url.Scheme);
                    string content     = System.IO.File.ReadAllText(path).Replace("###Name###", user.UserName).Replace("###Confirm###", callbackUrl);
                    userManager.SendEmailAsync(user.Id, "Confirm your account", content);


                    #endregion

                    #region insert both records to db

                    edisRepo.CreateNewClientSync(client);
                    #endregion

                    #region create risk profile if present
                    if (model.riskProfile != null)
                    {
                        var         riskProfile = model.riskProfile;
                        RiskProfile profile     = new RiskProfile {
                            CapitalLossAttitude    = riskProfile.capitalLossAttitude,
                            ClientID               = edisRepo.GetClientSync(user.Id, DateTime.Now).Id,
                            Comments               = riskProfile.comments,
                            DateCreated            = DateTime.Now,
                            DateModified           = DateTime.Now,
                            IncomeSource           = riskProfile.incomeSource,
                            InvestmentKnowledge    = riskProfile.investmentKnowledge,
                            InvestmentObjective1   = riskProfile.investmentObjective1,
                            InvestmentObjective2   = riskProfile.investmentObjective2,
                            InvestmentObjective3   = riskProfile.investmentObjective3,
                            InvestmentProfile      = riskProfile.investmentProfile,
                            InvestmentTimeHorizon  = riskProfile.investmentTimeHorizon,
                            LongTermGoal1          = riskProfile.longTermGoal1,
                            LongTermGoal2          = riskProfile.longTermGoal2,
                            LongTermGoal3          = riskProfile.longTermGoal3,
                            MedTermGoal1           = riskProfile.medTermGoal1,
                            MedTermGoal2           = riskProfile.medTermGoal2,
                            MedTermGoal3           = riskProfile.medTermGoal3,
                            RetirementAge          = string.IsNullOrEmpty(riskProfile.retirementAge) ? (int?)null : Convert.ToInt32(riskProfile.retirementAge),
                            RetirementIncome       = riskProfile.retirementIncome,
                            RiskAttitude           = riskProfile.riskAttitude,
                            ShortTermAssetPercent  = riskProfile.shortTermAssetPercent,
                            ShortTermEquityPercent = riskProfile.shortTermEquityPercent,
                            ShortTermGoal1         = riskProfile.shortTermGoal1,
                            ShortTermGoal2         = riskProfile.shortTermGoal2,
                            ShortTermGoal3         = riskProfile.shortTermGoal3,
                            ShortTermTrading       = riskProfile.shortTermTrading,
                            riskLevel              = Int32.Parse(riskProfile.riskLevel)
                        };
                        edisRepo.CreateRiskProfileForClient(profile);
                    }
                    #endregion

                    //#region save all changes and return ok

                    //db.SaveChanges();
                    return(Ok());
                    //#endregion
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
 public string Url(System.Web.Mvc.UrlHelper helper)
 {
     return(helper.Action("ClinicalRecord", "History", new { Id = OpdRecordId, area = "Clinical" }));
 }
 /// <summary>
 /// Gets widget render url 
 /// </summary>
 /// <param name="httpContext">The http context.</param>
 /// <param name="website">The website name</param>
 /// <param name="locale">The locale name.</param>
 /// <returns></returns>
 public string GetContentUrl(HttpContextBase httpContext, string website = "home", string locale = "en-US")
 {
     var contentUrl = "";
     var Url = new System.Web.Mvc.UrlHelper(httpContext.Request.RequestContext);
     if (!string.IsNullOrEmpty(Controller) && !string.IsNullOrEmpty(Action))
         contentUrl = !string.IsNullOrEmpty(website) ? Url.Action(Action, ControllerShortName, new { Area = string.IsNullOrEmpty(this.Area) ? "" : this.Area, website = website, id = this.ID, preview = true }) : Url.Action(this.Action, this.ControllerShortName, new { Area = string.IsNullOrEmpty(this.Area) ? "" : this.Area, id = this.ID, preview = true });
     else
         contentUrl = !string.IsNullOrEmpty(website) ? Url.Action("Generic", "Widget", new { Area = "", website = website, id = this.ID, preview = true }) : Url.Action("Generic", "Widget", new { Area = "", id = this.ID, preview = true });
     return contentUrl;
 }
Example #31
0
        public BreadcrumbViewModel GetBreadcrumbNodes(int categoryId)
        {
            Category category = Find(categoryId);
            var nodes = new List<Tuple<string, string>>();
            int count = 0;
            var urlHelper = new UrlHelper(httpRequest.RequestContext);
            while (++count < 10)
            {
                nodes.Insert(0,
                    new Tuple<string, string>(
                        urlHelper.Action("Details", "Category", new { id = category.Id, slug = @category.Name.ToSlug() }),
                        category.Name));

                if (category.ParentId == null) break;
                category = category.Parent;
            }
            return new BreadcrumbViewModel {Nodes = nodes};
        }
Example #32
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            var dbContext = context.OwinContext.Get <ApplicationDbContext>();

            if (dbContext.GetUserCount() <= 0)
            {
                UOWUserProfile dbcontext = new UOWUserProfile();
                IdentityResult result    = null;
                var            userModel = new Models.ApplicationUser {
                    Email = "*****@*****.**", UserName = "******"
                };
                try
                {
                    Random rand     = new Random();
                    var    password = Helper.GetRandomAlphanumericString(6) + "3#";
                    result = await userManager.CreateAsync(userModel, password);

                    if (result.Succeeded)
                    {
                        string code = await userManager.GenerateEmailConfirmationTokenAsync(userModel.Id);

                        System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
                        string callbackUrl = urlHelper.Action(
                            "ConfirmEmail",
                            "Account",
                            new { userId = userModel.Id, code = code },
                            HttpContext.Current.Request.Url.Scheme
                            );

                        await userManager.SendEmailAsync(userModel.Id, "Confirm your account", "Your Password : "******" , and Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

                        var RoleManager = context.OwinContext.GetUserManager <ApplicationRoleManager>();
                        var role        = "Admin";
                        if (!await RoleManager.RoleExistsAsync(role))
                        {
                            var roleCreate = RoleManager.Create(new IdentityRole(Guid.NewGuid().ToString(), role));
                            if (!roleCreate.Succeeded)
                            {
                                throw new SystemException("User Tidak Berhasil Ditambah");
                            }
                        }
                        var addUserRole = await userManager.AddToRoleAsync(userModel.Id, role);

                        if (!addUserRole.Succeeded)
                        {
                            throw new SystemException("User Tidak Berhasil Ditambah");
                        }

                        var usesr = dbcontext.AddNewUser(new DataAccesLayer.Models.petugas {
                            Email = "*****@*****.**", Name = "Administrator", Role = role, UserId = userModel.Id
                        });
                    }
                    throw new SystemException("User Tidak Berhasil Ditambah");
                }
                catch (Exception ex)
                {
                    context.SetError("App Not Yet Ready", "if you administrator please verify your account." + ex.Message);
                    return;
                }
            }

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.EmailConfirmed)
            {
                context.SetError("Email Confirm", "Your Account Not Yet Varification, Please Check Your Email");
                return;
            }

            if (user.LockoutEnabled)
            {
                context.SetError("Lock", "Sory Your Account Is Lock, Please Contact Trireksa Administrator");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager);

            AuthenticationProperties properties = CreateProperties(user.UserName, user.Roles);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public IHttpActionResult adviserCreateNewClient_Entity(EntityClientCreationBindingModel model)
        {
            if (model != null)          //ModelState.IsValid &&
            {
                using (EdisRepository edisRepo = new EdisRepository())
                {
                    #region create asp user and send email
                    var user = new ApplicationUser
                    {
                        Email = model.email,
                        UserName = model.email,
                        PhoneNumber = model.contactPhone
                    };
                    var password = "******";//Membership.GeneratePassword(10, 0);
                    var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
                    userManager.Create(user, password);
                    userManager.AddToRole(user.Id, AuthorizationRoles.Role_Preclient);
                    //EmailUtilities.SendEmailToUser(user.Id, "", "", "");//send password
                    #endregion

                    #region create client profile
                    ClientRegistration client = new ClientRegistration
                    {
                        CreateOn = DateTime.Now,
                        ClientNumber = user.Id,
                        EntityName = model.nameOfEntity,
                        EntityType = model.typeOfEntity,
                        ABN = model.abn,
                        ACN = model.acn,
                        Email = model.email,
                        Phone = model.contactPhone,
                        ClientType = BusinessLayerParameters.clientType_entity,
                        GroupNumber = model.existingGroupId
                    };

                    string code = userManager.GenerateEmailConfirmationTokenAsync(user.Id).Result;
                    string path = HttpContext.Current.Server.MapPath("~/EmailTemplate/ConfirmEmail.html");
                    var Url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Current.Request.Url.Scheme);
                    string content = System.IO.File.ReadAllText(path).Replace("###Name###", user.UserName).Replace("###Confirm###", callbackUrl);
                    userManager.SendEmailAsync(user.Id, "Confirm your account", content);

                    #endregion

                    #region insert both records to db

                    edisRepo.CreateNewClientSync(client);
                    #endregion

                    //#region create risk profile if present
                    //if (model.riskProfile != null)
                    //{
                    //    var riskProfile = model.riskProfile;
                    //    RiskProfile profile = new RiskProfile
                    //    {
                    //        CapitalLossAttitude = riskProfile.capitalLossAttitude,
                    //        ClientID = client.ClientUserID,
                    //        Comments = riskProfile.comments,
                    //        DateCreated = DateTime.Now,
                    //        DateModified = DateTime.Now,
                    //        IncomeSource = riskProfile.incomeSource,
                    //        InvestmentKnowledge = riskProfile.investmentKnowledge,
                    //        InvestmentObjective1 = riskProfile.investmentObjective1,
                    //        InvestmentObjective2 = riskProfile.investmentObjective2,
                    //        InvestmentObjective3 = riskProfile.investmentObjective3,
                    //        InvestmentProfile = riskProfile.investmentProfile,
                    //        InvestmentTimeHorizon = riskProfile.investmentTimeHorizon,
                    //        LongTermGoal1 = riskProfile.longTermGoal1,
                    //        LongTermGoal2 = riskProfile.longTermGoal2,
                    //        LongTermGoal3 = riskProfile.longTermGoal3,
                    //        MedTermGoal1 = riskProfile.medTermGoal1,
                    //        MedTermGoal2 = riskProfile.medTermGoal2,
                    //        MedTermGoal3 = riskProfile.medTermGoal3,
                    //        RetirementAge = string.IsNullOrEmpty(riskProfile.retirementAge)? (int?)null: Convert.ToInt32(riskProfile.retirementAge),
                    //        RetirementIncome = riskProfile.retirementIncome,
                    //        RiskProfileID = Guid.NewGuid().ToString(),
                    //        RiskAttitude = riskProfile.riskAttitude,
                    //        ShortTermAssetPercent = riskProfile.shortTermAssetPercent,
                    //        ShortTermEquityPercent = riskProfile.shortTermEquityPercent,
                    //        ShortTermGoal1 = riskProfile.shortTermGoal1,
                    //        ShortTermGoal2 = riskProfile.shortTermGoal2,
                    //        ShortTermGoal3 = riskProfile.shortTermGoal3,
                    //        ShortTermTrading = riskProfile.shortTermTrading
                    //    };
                    //    db.RiskProfiles.Add(profile);
                    //}
                    //#endregion

                    //#region save all changes and return ok

                    //db.SaveChanges();
                    return Ok();
                    //#endregion
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
Example #34
0
        public void Issue218_Url_generation_with_optional_query_params()
        {
            // re: issue #218

            var routes = RouteTable.Routes;
            routes.Clear();
            routes.MapAttributeRoutes(config => config.AddRoutesFromController<Issue218TestController>());
            RouteTable.Routes.Cast<Route>().LogTo(Console.Out);

            var urlHelper = new UrlHelper(MockBuilder.BuildRequestContext());

            Assert.That(urlHelper.Action("NoQuery", "Issue218Test", new { categoryId = 12 }),
                        Is.EqualTo("/Issue-218/No-Query?categoryId=12"));

            Assert.That(urlHelper.Action("OptionalQuery", "Issue218Test", new { categoryId = 12 }),
                        Is.EqualTo("/Issue-218/Optional-Query?categoryId=12"));

            Assert.That(urlHelper.Action("DefaultQuery", "Issue218Test"),
                        Is.EqualTo("/Issue-218/Default-Query?categoryId=123"));
        }
Example #35
0
 public static string Product(this System.Web.Mvc.UrlHelper urlHelper, string sku)
 {
     return(urlHelper.Action("Product", "Products", new { id = sku }));
 }
        public async Task<IHttpActionResult> ResetUsersPassword(string userId)
        {
            var processingResult = new ServiceProcessingResult();

            var appUserService = new ApplicationUserDataService();

            var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

            var baseUrl = Request.RequestUri.Authority;
            var code = await userManager.GeneratePasswordResetTokenAsync(userId);
            var helper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
            var callbackPath = helper.Action("ResetPassword", "Authentication", new { userId = userId, code = code });
            var callbackUrl = baseUrl + callbackPath;

            try
            {
                await
                    userManager.SendEmailAsync(userId, "Reset Password",
                        "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                processingResult.IsSuccessful = true;
            }
            catch (Exception ex)
            {
                processingResult.IsSuccessful = false;
                processingResult.Error = new ProcessingError("Email failed to send.", ex.Message, false);
            }

            return Ok(processingResult);
        }
        public string GenerateUlink(string link, string section, string element, string type)
        {
            System.Web.Mvc.UrlHelper u = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
            string strand = link.Contains("/") ? link.Substring(0, link.IndexOf("/")) : link;

            return u.Action("Index", "Home", new { Strand = strand, Section = ((section != "") ? section : "1"), Element = element + "$$" + type });
        }
Example #38
0
        public static void SetupOwin(this IAppBuilder app, Container container)
        {
            app.CreatePerOwinContext(() => container.GetInstance <OdissUserManager>());
            app.CreatePerOwinContext(() => container.GetInstance <OdissRoleManager>());
            app.CreatePerOwinContext(() => new OdissOwinLogger(container.GetInstance <IOdissLogger>()));
            app.CreatePerOwinContext(() =>
            {
                var manager = new UserSessionManager <Guid, Guid>(
                    container.GetInstance <IUserSessionStore <Guid, Guid> >(),
                    container.GetInstance <IAuthenticationManager>(),
                    container.GetInstance <IOdissLogger>()
                    );

                var initializer = container.GetInstance <Action <UserSessionManager <Guid, Guid> > >();
                initializer(manager);

                return(manager);
            });

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <OdissUserManager, OdissUser, Guid>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie),
                        getUserIdCallback: (identity) =>
                    {
                        var value = identity.FindFirstValue(OdissClaims.Id);

                        if (value == null)
                        {
                            return(Guid.Empty);
                        }

                        return(Guid.Parse(value));
                    })
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            var httpContext    = new HttpContextWrapper(HttpContext.Current);
            var requestContext = new RequestContext(httpContext, new RouteData());
            var urlHelper      = new System.Web.Mvc.UrlHelper(requestContext);

            var redirectUrl = urlHelper.Action("Index", "Home");

            app.Use(typeof(SessionMiddleware), redirectUrl, container.GetInstance <IOdissLogger>());
        }
Example #39
0
        public HttpResponseMessage Register(Register Register)
        {
            // ensure users can register
            var registrationSettings = _orchardServices.WorkContext.CurrentSite.As <RegistrationSettingsPart>();

            if (!registrationSettings.UsersCanRegister)
            {
                return(Request.CreateResponse(HttpStatusCode.MethodNotAllowed, new uError("Method Not Allowed", 405)));
            }

            if (Register.Password.Length < MinPasswordLength)
            {
                return(Request.CreateResponse(HttpStatusCode.MethodNotAllowed, new uError("Method Not Allowed", 405)));
            }

            if (!_profileService.VerifyUserUnicity(Register.Email, Register.Email))
            {
                return(Request.CreateResponse(HttpStatusCode.Conflict, new uError("Conflict on the Server", 409)));
            }
            ApplicationRecord apprecord = _applicationsService.GetApplicationByKey(Register.ApiKey);

            if (apprecord == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, new uError("Not Found", 404)));
            }

            if (ValidateRegistration(Register))
            {
                // Attempt to register the user
                // No need to report this to IUserEventHandler because _membershipService does that for us
                var user = _membershipService.CreateUser(new CreateUserParams(Register.Email, Register.Password, Register.Email, null, null, false));

                if (user != null)
                {
                    UserProfilePart profile = user.As <UserProfilePart>();
                    if (profile != null)
                    {
                        profile.FirstName = Register.FirstName;
                        profile.LastName  = Register.LastName;
                    }
                    if (user.As <UserPart>().EmailStatus == UserStatus.Pending)
                    {
                        var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl;
                        //if (String.IsNullOrWhiteSpace(siteUrl))
                        //{
                        //    siteUrl = Request.ToRootUrlString();
                        //}
                        //var url = Url.Route("challengeemail", new { controller = "login", action = "ChallengeEmail", returnUrl = "hello" });

                        var _Url = new System.Web.Mvc.UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);

                        _profileService.SendChallengeMail(
                            apprecord,
                            user.As <UserPart>(),
                            nonce =>

                            _Url.MakeAbsolute(
                                _Url.Action("ChallengeEmail", "Account", new
                        {
                            Area  = "Contrib.Foundation.UserProfile",
                            nonce = nonce
                        }
                                            )
                                )

                            //_Url.MakeAbsolute(
                            //    _Url.Action("ChallengeEmail", "login", new
                            //        {
                            //            httproute = true,
                            //            area = "Contrib.Foundation.UserProfile",
                            //            nonce = nonce
                            //        }
                            //    )
                            //)

                            //protocolChallengeEmail(nonce)
                            );
                        _userEventHandler.SentChallengeEmail(user);
                        return(Request.CreateResponse(HttpStatusCode.Created, new uError("Create", 201, false)));
                    }

                    if (user.As <UserPart>().RegistrationStatus == UserStatus.Pending)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotModified, new uError("Not Modified", 304)));
                    }

                    _authenticationService.SignIn(user, false);
                    return(Request.CreateResponse(HttpStatusCode.OK, new uError("OK", 200)));
                }

                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new uError("Internal Server Error", 500)));
            }

            return(Request.CreateResponse(HttpStatusCode.InternalServerError, new uError("Internal Server Error", 500)));;
        }
Example #40
0
 public static string ActionRedirectToReferrer(this System.Web.Mvc.UrlHelper helper, HttpRequestBase request)
 {
     return(request.UrlReferrer?.ToString() ?? helper.Action("Index", "Movies"));
 }
Example #41
0
        /// <summary>
        /// 创建搜索框
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="type"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static string Search(this System.Web.Mvc.HtmlHelper helper, Type type,object parms)
        {
            List<string> plist = new List<string>();//可查询属性 列表
            UrlHelper UrlHelper = new System.Web.Mvc.UrlHelper(helper.ViewContext.RequestContext);

            var propertys = type.GetProperties();
            foreach (var p in propertys)
            {
                object[] alist = p.GetCustomAttributes(typeof(SearchAttribute), false);
                if (alist.Length > 0)
                {
                    SearchAttribute sa = alist[0] as SearchAttribute;
                    if (sa == null) continue;

                    var ls = sa.getInputFiles(p);
                    StringBuilder sb = new StringBuilder();
                    foreach (var l in ls)
                    {
                        var value = sa.getValue(p.Name, helper.ViewContext.HttpContext.Request);
                        var displayname = ((DisplayAttribute[])p.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
                        sb.Append(string.Format("<label for='{0}' >{2}</label><input type='text' name='{0}' id='{0}' value='{1}' >", p.Name, value, displayname.Name));
                    }
                    plist.Add(string.Format("<span>{0}</span>", sb.ToString()));//获取类型绑定的search对象
                }
            }

            if (plist.Count == 0) return "";
            string actionName = helper.ViewContext.RouteData.Values["action"].ToString();
            string result = string.Format("<div class='query-content'><form action='{0}' name='form-{1}' id='form-{1}'> {2} <span><input type='submit' value='查询'></span><form></div>", UrlHelper.Action(actionName, parms), type.Name, string.Join("", plist.ToArray()));
            return result;
        }
Example #42
0
 public static string GetFullUrlToAction(string action, string controller)
 {
     var url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
     return url.Action(action, controller, new {language = LanguageHelper.HttpContextLanguage},
         HttpContext.Current.Request.Url.Scheme);
 }