示例#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);
        }
示例#2
0
        public void Process(List<ITemplateAction> actions, MerchantTribe.Commerce.MerchantTribeApplication app, ITagProvider tagProvider, ParsedTag tag, string innerContents)
        {
            this.App = app;
            this.Url = new System.Web.Mvc.UrlHelper(app.CurrentRequestContext.RoutingContext);
            CurrentCategory = app.CurrentRequestContext.CurrentCategory;
            if (CurrentCategory == null)
            {
                CurrentCategory = new Category();
                CurrentCategory.Bvin = "0";
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("<div class=\"categorymenu\">");
            sb.Append("<div class=\"decoratedblock\">");

            string title = tag.GetSafeAttribute("title");
            if (title.Trim().Length > 0)
            {
                sb.Append("<h4>" + title + "</h4>");
            }

            sb.Append("<ul>");

            int maxDepth = 5;

            string mode = tag.GetSafeAttribute("mode");
            switch (mode.Trim().ToUpperInvariant())
            {
                case "ROOT":
                case "ROOTS":
                    // Root Categories Only
                    LoadRoots(sb);
                    break;
                case "ALL":
                    // All Categories
                    LoadAllCategories(sb, maxDepth);
                    break;
                case "":
                case "PEERS":
                    // Peers, Children and Parents
                    LoadPeersAndChildren(sb);
                    break;
                case "ROOTPLUS":
                    // Show root and expanded children
                    LoadRootPlusExpandedChildren(sb);
                    break;
                default:
                    // All Categories
                    LoadPeersAndChildren(sb);
                    break;
            }

            sb.Append("</ul>");

            sb.Append("</div>");
            sb.Append("</div>");

            actions.Add(new Actions.LiteralText(sb.ToString()));
        }
示例#3
0
        /// <summary>
        /// Build pager view model from a non-paged list of items.
        /// </summary>
        /// <param name="posts"></param>
        /// <returns></returns>
        public static EntityListViewModel <T> ConvertToListViewModel <T>(System.Web.Mvc.UrlHelper urlhelper, IList <T> items, string controllerName, IDictionary conf) where T : IEntity
        {
            if (string.IsNullOrEmpty(controllerName))
            {
                controllerName = typeof(T).Name;
            }

            // Url for pager.
            // This List page uses a paged result by default.
            // Since we are getting ALL the posts with matching tags, just wrap them in a paged result.
            string url = string.Format("/{0}/index/{1}", controllerName, 1);

            // Check for empty.
            if (items == null)
            {
                var result = new EntityListViewModel <T>(PagedList <T> .Empty, url, false);
                result.ControlPath = "ModelList";
            }

            PagedList <T> pagedList = new PagedList <T>(1, items.Count + 1, items.Count, items);
            var           viewModel = new EntityListViewModel <T>(pagedList, url, false);

            ViewHelper.BuildViewModel <T>(urlhelper, viewModel, default(T), controllerName, "ModelList", false, conf);
            viewModel.Items          = pagedList;
            viewModel.PageIndex      = pagedList.PageIndex;
            viewModel.TotalPages     = pagedList.TotalPages;
            viewModel.ShowEditDelete = false;
            return(viewModel);
        }
示例#4
0
        public ImageModel(string ImagePath, System.Web.Mvc.UrlHelper url)
        {
            dir      = new DirectoryInfo(ImagePath);
            thumbDir = dir.GetDirectories("t").FirstOrDefault();

            if (!dir.Exists)
            {
                dir.Create();
            }
            if (thumbDir == null || !thumbDir.Exists)
            {
                thumbDir = dir.CreateSubdirectory("t");
            }

            Images = from f in dir.GetFiles()
                     let exists = File.Exists(Path.Combine(thumbDir.FullName, f.Name))
                                  select new Img {
                Filename     = f.Name,
                ImageUrl     = url.Content("~/Images/" + f.Name),
                Uploaded     = f.CreationTime,
                Size         = f.Length,
                HasThumbnail = exists,
                ThumbnailUrl = exists ? url.Content("~/Images/t/" + f.Name) : null
            };
        }
示例#5
0
        public static string Content(this System.Web.Mvc.UrlHelper urlHelper, string contentPath, bool toAbsolute = false)
        {
            var path = urlHelper.Content(contentPath);
            var url  = new Uri(System.Web.HttpContext.Current.Request.Url, path);

            return(toAbsolute ? url.AbsoluteUri : path);
        }
        /// <summary>
        /// Builds the link for a media folder that's associated with an entity.
        /// </summary>
        /// <param name="urlhelper">UrlHelper</param>
        /// <param name="action">Action on the controller.</param>
        /// <param name="controller">Controller</param>
        /// <param name="id">Entity Id</param>
        /// <param name="refgroup">Entity Group ( e.g. post or event )</param>
        /// <returns></returns>
        public static string LinkForMediaForEntity(this System.Web.Mvc.UrlHelper urlhelper, string action, string controller, int id, int refgroup)
        {
            string baseurl = _adminAreas.ContainsKey(controller.ToLower()) ? "/admin" : string.Empty;
            string url     = baseurl + "/" + controller + "/" + action + "?id=" + id + "&refgroup=" + refgroup;

            return(url);
        }
        /// <summary>
        /// Generates the link for the url action/controller combination.
        /// </summary>
        /// <param name="urlhelper"></param>
        /// <param name="action"></param>
        /// <param name="controller"></param>
        /// <param name="routeValues"></param>
        /// <returns></returns>
        public static string Link(this System.Web.Mvc.UrlHelper urlhelper, string action, string controller, object routeValues)
        {
            string baseurl = _adminAreas.ContainsKey(controller.ToLower()) ? "/admin" : string.Empty;
            string url     = baseurl + "/" + controller + "/" + action + "/";

            return(url);
        }
示例#8
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));
            }
        }
        public void SendOrderReceived(Order order, HttpRequestBase Request, System.Web.Mvc.UrlHelper Url)
        {
            var fileContents = System.IO.File.ReadAllText(HostingEnvironment.MapPath(@"~/Content/Emails/OrderReceived.html"));

            fileContents = fileContents.Replace("[#ORDERNO#]", StringHelper.GetOrderNo(order.OrderId, order.OrderDate));
            fileContents = fileContents.Replace("[#ORDERDATE#]", order.OrderDate.ToShortDateString());
            fileContents = fileContents.Replace("[#PAYMENT#]", order.Paid ? "PAID" : "NOT PAID");
            fileContents = fileContents.Replace("[#TOTALPRICE#]", order.TotalPrice.ToString());

            var    orderDetails = order.GetOrderDetail(order.OrderId);
            string productsHtml = "";

            foreach (var product in orderDetails.OrderProducts)
            {
                productsHtml += "<tr>";
                productsHtml += "<td><img src =\"" + Request.Url.Scheme + "://" + Request.Url.Authority + Url.Content("~/ProductImage/" + product.FileName + "-1.jpg")
                                + "\" /></td>";
                productsHtml += "<td>" + product.VariantName + " " + product.ProductName + "</td>";
                productsHtml += "<td>" + product.Quantity + "</td>";
                productsHtml += "<td>" + product.UnitPrice + "</td>";
                productsHtml += "<td>" + product.TotalPrice + "</td>";
                productsHtml += "</tr>";
            }
            fileContents = fileContents.Replace("[#PRODUCTS#]", productsHtml);
            var model = new EmailModel();

            model.Body   = fileContents;
            model.MailTo = order.BillingEmail;
            model.Title  = "Order Received!";
            string error = "";

            SendEmail(model, ref error);
        }
        /// <summary>
        /// Retrieves a particular routeurl from the global route table. Because the app is running inside OWIN host, we need to query route from the global routetable
        /// instead of route from OWIN configuration
        /// </summary>
        /// <returns>The url of route</returns>
        public static string RouteAppUrl(this UrlHelper urlHelper, string routeName, dynamic routeValues)
        {
            if (routeValues == null)
            {
                routeValues = new { }
            }
            ;

            try
            {
                return(urlHelper.RouteUrl(routeName, routeValues));
                // RouteTable.Routes.GetVirtualPath(null, new RouteValueDictionary(routeValues));
            }
            catch (Exception ex)
            {
                // ignored
            }
            //search in webapi routes
            IHttpRoute apiRoute;
            var        vPath = WebApiConfig.Configuration.Routes.TryGetValue(routeName, out apiRoute);


            if (!vPath)
            {
                throw new mobSocialException(string.Format("Can't find a route named {0} in the RouteTable", routeName));
            }
            return(apiRoute.RouteTemplate);
        }
示例#11
0
        public static string HttpRouteUrl2 <TController>(this System.Web.Mvc.UrlHelper urlHelper, Expression <Action <TController> > expression)
            where TController : System.Web.Http.Controllers.IHttpController
        {
            var routeValues  = expression.GetRouteValues();
            var httpRouteKey = System.Web.Http.Routing.HttpRoute.HttpRouteKey;

            if (!routeValues.ContainsKey(httpRouteKey))
            {
                routeValues.Add(httpRouteKey, true);
            }
            var url = string.Empty;

            if (routeValues.ContainsKey(HttpAttributeRouteWebApiKey))
            {
                var routeName = routeValues[HttpAttributeRouteWebApiKey] as string;
                routeValues.Remove(HttpAttributeRouteWebApiKey);
                routeValues.Remove("controller");
                routeValues.Remove("action");
                url = urlHelper.HttpRouteUrl(routeName, routeValues);
            }
            else
            {
                var path = resolvePath <TController>(routeValues, expression);
                var root = getRootPath(urlHelper);
                url = root + path;
            }
            return(url);
        }
示例#12
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));
        }
示例#13
0
        //
        /// <summary>
        /// Needs to run from both MVC and Web api context.
        /// </summary>
        /// <param name="user">ApplicationUser to be e-mailed</param>
        /// <returns>0 = OK, 1 = problem</returns>
        public async Task <int> SendEmailConfirmation(ApplicationUser user)
        {
            //
            try
            {
                var _code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var _hpr         = new System.Web.Mvc.UrlHelper();
                var _url         = Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = _code });
                var _callbackUrl = new Uri(_url);
                //
                await UserManager.SendEmailAsync(user.Id, "Confirm your account",
                                                 "Thank-you for registering, but your new account requires the e-mail address to be confirmed.  " +
                                                 "Please confirm your account by clicking this link: <a href=\""
                                                 + _callbackUrl + "\">link</a>");
            }
            catch (Exception _ex)
            {
                Console.WriteLine(_ex.Message);
                Console.WriteLine(_ex.StackTrace.ToString());

                return(1);
            }
            return(0);
        }
示例#14
0
        //public static string Zip(string filename)
        //{
        //    return Zip(filename, null);
        //}

        //public static string Zip(string filename, string zipFilename)
        //{
        //    if (string.IsNullOrEmpty(zipFilename))
        //    {
        //        FileInfo file = new FileInfo(filename);

        //        zipFilename = filename.TrimEnd(file.Extension.ToCharArray()) + ".zip";
        //    }

        //    if (File.Exists(zipFilename))
        //    {
        //        File.Delete(zipFilename);
        //    }

        //    if (!File.Exists(filename))
        //    {
        //        throw new FileNotFoundException("Configuration file was not found");
        //    }
        //    FileStream sourceFile = File.OpenRead(filename);
        //    FileStream destFile = File.Create(zipFilename);

        //    GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

        //    try
        //    {
        //        int theByte = sourceFile.ReadByte();
        //        while (theByte != -1)
        //        {
        //            compStream.WriteByte((byte)theByte);
        //            theByte = sourceFile.ReadByte();
        //        }
        //        return zipFilename;
        //    }
        //    finally
        //    {
        //        compStream.Dispose();
        //    }
        //}

        public static string GetActionName()
        {
            //string url = HttpContext.Current.Request.RawUrl;
            HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);

            System.Web.Routing.RouteData route = System.Web.Routing.RouteTable.Routes.GetRouteData(httpContextBase);
            if (route == null)
            {
                return(string.Empty);
            }
            System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(new System.Web.Routing.RequestContext(httpContextBase, route));
            //System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            var routeValueDictionary = urlHelper.RequestContext.RouteData.Values;

            if (!routeValueDictionary.ContainsKey("action"))
            {
                return(string.Empty);
            }

            string actionName = routeValueDictionary["action"].ToString();

            httpContextBase = null;
            return(actionName);
        }
示例#15
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;
        }
 public static string GetUrl()
 {
     var requestContext = HttpContext.Current.Request.RequestContext;
     var baseurl = new System.Web.Mvc.UrlHelper(requestContext).Action("Index", "Home");
     baseurl = baseurl.Replace("/Home/Index/", "");
     baseurl = baseurl.TrimEnd('/');
     return baseurl;
 }
示例#17
0
        public static string AbsoluteRouteUrl(this System.Web.Mvc.UrlHelper url, string routeName, object values)
        {
            Uri requestUrl = url.RequestContext.HttpContext.Request.Url;

            string absoluteRouteUrl = String.Format("{0}://{1}{2}", requestUrl.Scheme, requestUrl.Authority, url.RouteUrl(routeName, values));

            return(absoluteRouteUrl);
        }
示例#18
0
 /// <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));
 }
示例#19
0
        public void Parts_Common_Metadata__api__Flat(dynamic Display, dynamic Shape)
        {
            System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(Display.ViewContext.RequestContext);

            Display.ViewDataContainer.Model.Id           = Shape.ContentPart.Id;
            Display.ViewDataContainer.Model.ResourceUrl  = urlHelper.ItemApiGet((IContent)Shape.ContentPart);
            Display.ViewDataContainer.Model.CreatedUtc   = Shape.ContentPart.CreatedUtc;
            Display.ViewDataContainer.Model.PublishedUtc = Shape.ContentPart.PublishedUtc;
        }
示例#20
0
        /// <summary>
        /// Returns script tags based on the webpack asset manifest
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="urlHelper">Optional IUrlHelper instance. Enables the use of tilde/relative (~/) paths inside the expose-components.js file.</param>
        /// <returns></returns>
        public static IHtmlString ReactGetScriptPaths(this IHtmlHelper htmlHelper, IUrlHelper urlHelper = null)
        {
            string nonce = Environment.Configuration.ScriptNonceProvider != null
                                ? $" nonce=\"{Environment.Configuration.ScriptNonceProvider()}\""
                                : "";

            return(new HtmlString(string.Join("", Environment.GetScriptPaths()
                                              .Select(scriptPath => $"<script{nonce} src=\"{(urlHelper == null ? scriptPath : urlHelper.Content(scriptPath))}\"></script>"))));
        }
示例#21
0
        /// <summary>
        /// Add preflight-specific values to the servervariables dictionary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="dictionary"></param>
        private static void ServerVariablesParser_Parsing(object sender, Dictionary <string, object> dictionary)
        {
            var urlHelper = new System.Web.Mvc.UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));

            dictionary.Add("Stately", new Dictionary <string, object>
            {
                { "ApiPath", urlHelper.GetUmbracoApiServiceBaseUrl <SettingsApiController>(controller => controller.Get()) }
            });
        }
示例#22
0
        private static string getRootPath(System.Web.Mvc.UrlHelper urlHelper)
        {
            var request = urlHelper.RequestContext.HttpContext.Request;
            var scheme  = request.Url.Scheme;
            var server  = request.Headers["Host"] ?? string.Format("{0}:{1}", request.Url.Host, request.Url.Port);
            var host    = string.Format("{0}://{1}", scheme, server);
            var root    = host + ToAbsolute("~");

            return(root);
        }
 public static string SaveBase64Image(string base64Img, string imgExtension)
 {
     string fileUri = null;
     byte[] bytes = Convert.FromBase64String(base64Img);
     string imgName = string.Format("{0}.{1}", Guid.NewGuid().ToString(), imgExtension);
     string fullFileName = Path.Combine(HostingEnvironment.MapPath(ConfigHelper.ImageFolder), imgName);
     File.WriteAllBytes(fullFileName, bytes);
     fileUri = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext).Content(ConfigHelper.ImageFolder + imgName);
     return fileUri;
 }
        //
        // [TestMethod]
        public void Identity_AccountController_UrlHelper_Test()
        {
            var    obj       = new { userId = "111-11111", code = "A12B==", httproute = true };
            var    _config   = _sut.Request.GetConfiguration();
            var    _url      = new System.Web.Mvc.UrlHelper();
            var    _out      = _url.RouteUrl("ConfirmEmailRoute", obj);
            string _rUrlPart = "api/Account/ConfirmEmail" + _out;

            Assert.AreNotEqual("", _rUrlPart);
        }
示例#25
0
        public static string Absolute(this System.Web.Mvc.UrlHelper url, string relativeUrl)
        {
            //System.Web.Mvc.UrlHelper url = new System.Web.Mvc.UrlHelper();
            var request = url.RequestContext.HttpContext.Request;

            return(string.Format("{0}://{1}{2}",
                                 (request.IsSecureConnection) ? "https" : "http",
                                 request.Headers["Host"],
                                 VirtualPathUtility.ToAbsolute(relativeUrl)));
        }
示例#26
0
        public static string Internal(this System.Web.Mvc.UrlHelper helper, object url)
        {
            string urlString = url as string;

            if (urlString == null)
            {
                return(string.Empty);
            }
            return(UrlHelper.AppendSessionID(helper.RequestContext, urlString));
        }
示例#27
0
        public UrlHelper Method1(this System.Web.Mvc.UrlHelper h)
        {
            Foo.UrlHelper x = h;

            h.ExtenstionMethod(new TestProject.MyNamespace.UrlHelper(), new UrlHelper());

            System.Web.Mvc.UrlHelper.GenerateUrl(null, null, null, null, null, null, false);

            return(h);
        }
示例#28
0
        public static bool AuthorizeAPI(string userName, string password, out string errMsg)
        {
            System.Web.Mvc.UrlHelper Url = new System.Web.Mvc.UrlHelper();
            string backendServiceUrl     = System.Configuration.ConfigurationManager.AppSettings["ServiceUrl"].ToString();
            string providedLoginInfo     = "grant_type=password&username="******"&password="******"token", providedLoginInfo, "application/json", "application-x-www-form-urlencode", string.Empty, out errMsg);

            return(!string.IsNullOrEmpty(token));
        }
示例#29
0
        // <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));
        }
示例#30
0
        // <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)));
        }
示例#31
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);
        }
示例#32
0
        public dynamic MoveArticle([FromUri] ArticleSlug slug, [FromUri] ArticleSlug targetArticleSlug)
        {
            this.CurrentRepository.MoveArticle(slug, targetArticleSlug);

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

            var articleUrl = urlHelper.WikiArticle(targetArticleSlug.Slug);
            var editUrl = urlHelper.WikiArticleEdit(targetArticleSlug.Slug);

            return new { targetArticleSlug.Slug, articleUrl, editUrl };
        }
示例#33
0
        /// <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)));
        }
示例#34
0
        public void Parts_Common_Metadata__api__Native(dynamic Display, dynamic Shape)
        {
            System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(Display.ViewContext.RequestContext);

            using (Display.ViewDataContainer.Model.Node("a-list-item")) {
                Display.ViewDataContainer.Model.Type         = Shape.ContentPart.PartDefinition.Name;
                Display.ViewDataContainer.Model.Id           = Shape.ContentPart.Id;
                Display.ViewDataContainer.Model.ResourceUrl  = urlHelper.ItemApiGet((IContent)Shape.ContentPart);
                Display.ViewDataContainer.Model.CreatedUtc   = Shape.ContentPart.CreatedUtc;
                Display.ViewDataContainer.Model.PublishedUtc = Shape.ContentPart.PublishedUtc;
            }
        }
示例#35
0
 /// <summary>
 /// Address the specified urlHelper, contentPath and defaultValue.
 /// </summary>
 /// <param name="urlHelper">URL helper.</param>
 /// <param name="contentPath">Content path.</param>
 /// <param name="defaultValue">Default value.</param>
 public static string Addr(this System.Web.Mvc.UrlHelper urlHelper, string contentPath, string defaultValue = "")
 {
     if (string.IsNullOrEmpty(contentPath))
     {
         return(defaultValue);
     }
     if (contentPath.StartsWith("~"))
     {
         return(urlHelper.Content(contentPath));
     }
     return(contentPath);
 }
        public string GetUserPic()
        {
            var     jwtObject = GetjwtToken();
            UserPic userPic   = _userPicService.GetPicByAcc(jwtObject["Account"].ToString());

            if (userPic != null)
            {
                System.Web.Mvc.UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                return(urlHelper.Content("~/UserPic/" + userPic.Name));
            }
            return(null);
        }
示例#37
0
        /// <summary>
        /// Add preflight-specific values to the servervariables dictionary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="dictionary"></param>
        private static void ServerVariablesParser_Parsing(object sender, Dictionary <string, object> dictionary)
        {
            var urlHelper = new System.Web.Mvc.UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
            IDictionary <string, object> settings = dictionary["umbracoSettings"].ToDictionary();

            dictionary.Add("Preflight", new Dictionary <string, object>
            {
                { "ContentFailedChecks", KnownStrings.ContentFailedChecks },
                { "PluginPath", $"{settings["appPluginsPath"]}/preflight/backoffice" },
                { "PropertyTypesToCheck", KnownPropertyAlias.All },
                { "ApiPath", urlHelper.GetUmbracoApiServiceBaseUrl <Api.ApiController>(controller => controller.GetSettings()) }
            });
        }
示例#38
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"));
        }
        internal static GridContext Create(HttpContext context, string gridName, IMVCGridDefinition grid, QueryOptions options)
        {
            var httpContext = new HttpContextWrapper(context);
            var urlHelper = new System.Web.Mvc.UrlHelper(new RequestContext(httpContext, new RouteData()));

            var gridContext = new GridContext()
            {
                GridName = gridName,
                CurrentHttpContext = context,
                GridDefinition = grid,
                QueryOptions = options,
                UrlHelper = urlHelper
            };

            return gridContext;
        }
示例#40
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;
                    }
                }
            }
        }
示例#41
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);
 }
示例#42
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"));
        }
示例#43
0
        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 });
        }
 /// <summary>
 /// Convert widget descriptor to dynamic object.
 /// </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 dynamic ToObject(HttpContextBase httpContext, string website = "home", string locale = "en-US")
 {
     var Url = new System.Web.Mvc.UrlHelper(httpContext.Request.RequestContext);
     return new
     {
         id = this.ID,
         title = this.Title,
         description = this.Description,
         icon = string.IsNullOrEmpty(this.IconUrl) ? null : Url.Content(this.IconUrl),
         contentUrl = GetContentUrl(httpContext, website, locale),
         contentType = this.ContentType,
         version = this.Version,
         defaults = this.Defaults
     };
 }
 /// <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;
 }
        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);
            }
        }
示例#47
0
        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 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);
            }
        }
示例#49
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};
        }