Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

Going in Cricles on Distinct Record Returns

$
0
0

I am sure this is simple and I am just missing something...

I have a view component:

 public IViewComponentResult Invoke(int id)
        {
            var supplierContacts = _context.SupplierContact
                                   .Where(s => s.SupplierID== id )
                                   .Distinct();

            return View(supplierContacts);
        }

The invoke statement is returning correctly the records for the supplier contacts.  For example Peter and Raj work for Techsource returns fine.

Where I am having issues is where the supplier contact has two forms of contact, say mobile phone and email, this is returning the contact persons name twice.

So instead of:

Peter

Email

Phone

Raj

Email

The result is

Peter

Email

Phone

Peter

Email

Phone

Raj

Email

I can kind of see why this is.  After all the only restriction I am passing to the expression is the SupplierID and I can also see that the records are not distinct in SupplierContact as there is a listing with an email and then separately a listing with the phone etc.

I just cant see how to write something like:

  var supplierContacts = _context.SupplierContact
                                   .Where(s => s.SupplierID== id )
                                   .Distinct(SupplierConact.Name);  

How do I force the statement to return just the distinct names in supplierContact without breaking the IEnumerable in the view?


SqlException -OFFSET, NEXT & FETCH

$
0
0

Hello, 
I have this SqlException error in my ASP Core project , and I have no clue from where the error come from.
Line : http://prnt.sc/f291qb
Exception message : http://prntscr.com/f29418    sorry some lines are in french 

Some help would be appreciated , thanks !

Being a newbee I want to learn basic syntax of csharp7 & ef core 1.0

$
0
0

Sir,

I have a java background and want to learn csharp 7 & ef core.

As for as csharp is concerned I can understand it very similar to java. But still there are some new things like "using" instead of 'import" etc.

But I have no idea about ef core. Please refer any tutorial or books for a newbee.

Regards

Image Upload Tutorials and Advice

$
0
0

I am still very much a begineer in ASP.Net.  I stumble about and occasionally something clicks and I can get a lot of what I need done.

But this is frustrating me chronically.  What I want to do is add to an existing model the ability to upload an image to the web and retrieve as part of the final 'report' I will generate.  I have been having a pass at this now and again using tutorials I find online but none seems to actually work without little red squiggles, so I am either stupid, or the tutorials are for different virgins or ...probably stupid.

The code I am trying to make work this time are:

Extract from Equipment Model:

 [Display(Name = "Equipment Type")]
        public int EqTypeID { get; set; }

        [Display(Name ="Equipment Photo")]
        [DataType(DataType.ImageUrl)]
        public string ImageUrl { get; set; }

        public int Quantity { get; set; }

        [Display(Name = "Manufacturer")]
        public int MakeID { get; set; }

I then have a view model ImageViewModel, which I copied form the tutorial:

namespace Eva804.Models
{
    public class ImageViewModel
    {
        [Required]
        public string Title { get; set; }

        public string AltText { get; set; }

        [DataType(DataType.Html)]
        public string Caption { get; set; }

        [DataType(DataType.Upload)]
        IFormFile ImageUpload { get; set; }

    }
}

Following the tutorial broadly I have the following controller:

 public async Task<IActionResult> Create(
            [Bind("ConditionID,EqTypeID,EstimateRemainingLife,InstallDate,EquipmentImage, LastServiceDate,MakeID,Model,Notes,Recommended,ReplacementCost,SerialNumber,WaterBodyID")] Equipment equipment, ImageViewModel model)
        {
            try
            {
                var validImageTypes = new string[]
                    {"image/gif","image/jpeg","image/pjpeg","image/png"
                    };


                if (!validImageTypes.Contains(model.ImageUpload.ContentType))
                {
                    ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
                }

                if (ModelState.IsValid)
                {
                    if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
                    {
                        var uploadDir = "~/uploads"
                        var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
                        var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName);
                        model.ImageUpload.SaveAs(imagePath);
                        image.ImageUrl = imageUrl;
                    }


                    _context.Add(equipment);
                    await _context.SaveChangesAsync();
                    return RedirectToAction("Index");
                }

            }

Which is hating ImageUpload, Server.Mappath and image.Imageurl.

Clearly this is wrong.

Where can I go for good tutorial?  I really have struggled with this?

Custome SignInManager with Version=3.0.0.0 Microsoft.AspNet.Identity

$
0
0

I just started to learning ASP.net 5 or you can say ASP.NET Core 1.0. Whenever I create project from existing Visual Studio 2015 template, its come with existing User Authentication code which is implemented with the help of Entity Framework. But I am not used to Entity Framework more so, I try to implement it with custom SignInManager.But I found that If I want to implement it, I will have to implement allInterfaces exists in UserManager class and need to register as service into startup.cs.

public class AspUserManager : UserManager<ApplicationUser>
{
public AspUserManager(IUserStore<ApplicationUser> store,
IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<ApplicationUser> passwordHasher,
IEnumerable<IUserValidator<ApplicationUser>> userValidators,
IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators,
ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors,
IServiceProvider services,
ILogger<UserManager<ApplicationUser>> logger,
IHttpContextAccessor contextAccessor):
base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor)
{ }
}

Is this only way to implement custom SignInManager without Entity Framework or we can implement it with another way.

Help on 404 custom

$
0
0

"Create a web page (Err404.aspx) with custom error message which will be displayed when a user try to access a non-existing web page"

I created the ERR404.aspx page, now this is code when i add to be web.config file

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" />

<!-- Turn on Custom Errors -->
<customErrors mode="On"
defaultRedirect="/nonexistingpage.aspx">
<error statusCode="404" redirect="/Err404.aspx"/>
</customErrors>

</system.web>
</configuration>

Now my end state is to basically test the configuration when the non existing webpage by typing https://localhost/nonexistingpage.aspx

I would appreciate any help on this issues please.

Rickyjj

NonFactors Grid MVC 6 and Checkbox / Multiselect

$
0
0

I am working with a problem.  I can currently display data on a page with the NonFactors Grid MVC6, though it is incomplete data.  Currently for Boolean values it is displaying a True or False on the page.  I am having trouble trying to get it to display a checkbox.  I have tried Html.CheckboxFor and <input type="checkbox" /> with no luck.  So here is what I am working with.  I have four viewmodels for the page, and a partial view that works in conjunction with the view.  The page is only for editing, but the only editing that needs to take place is with the Boolean values and a selectlist for each row of the grid.  What I am looking for is advice with the partial view so that I can get the checkbox and selectlist to display.

Here is my viewmodels in question:

public class CharRepViewModel
    {
        public CharRepViewModel()
        {
            this.Name = new CharFullNameViewModel();
            this.Reputation = new List<CharRepListViewModel>();
        }
        public CharFullNameViewModel Name { get; set; }
        public List<CharRepListViewModel> Reputation { get; set; }
    }

public class CharFullNameViewModel
    {
        public int Char_ID { get; set; }
        public string CharFullName { get; set; }
    }

public class CharRepListViewModel
    {
        public CharRepListViewModel()
        {
            this.CharID = CharID;
            this.FactionID = FactionID;
            this.FactionName = FactionName;
            this.FactionSet = FactionSet;
            this.RepLevelID = RepLevelID;
            this.RepLevels = new List<RepLevelListViewModel>();
        }
        public int CharID { get; set; }
        public int FactionID { get; set; }
        public string FactionName { get; set; }
        public bool FactionSet { get; set; }
        public int RepLevelID { get; set; }
        public List<RepLevelListViewModel> RepLevels { get; set; }

    }

public class RepLevelListViewModel
    {
        public int FactionID { get; set; }
        public int RepLevelID { get; set; }
        public string RepLevelName { get; set; }
        public bool RepIsChecked { get; set; }
    }

The RepLevelListViewModel is what I want for the SelectList in the grid.  The FactionSet in the CharRepListViewModel is what I want for a checkbox.  This will hopefully allow the multiselect dropdown to be accessible if checked, and not accessible if uncheck.  Of which I have not figured out how to do yet either.  The CharRepViewModel brings everything together for the main view.  And yes my RepLevelID in the CharRepListViewModel is currently unused, I added it there, but have not been able to make the data use it correctly yet, but I have left it there currently while building the view in case I need it.

Here is my controller:

public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return BadRequest();
            }

            var factIdList = await _db.Database.SqlQuery<CharRepListViewModel>(sql: "GetCharacterReputations @p0", parameters: new object[] { id }).ToListAsync();
            var eReps = await _db.Database.SqlQuery<RepLevelListViewModel>(sql: "GetCharacterReputationsChecks @p0", parameters: new object[] { id }).ToListAsync();
            foreach (CharRepListViewModel cr in factIdList)
            {
                cr.RepLevels.AddRange(eReps.Where(a => a.FactionID == cr.FactionID));
            }

            var characterReputation = new CharRepViewModel()
            {
                Name = await _db.Database.SqlQuery<CharFullNameViewModel>(sql: "GetCharacterFullName @p0", parameters: new object[] { id }).FirstOrDefaultAsync(),
                Reputation = factIdList
            };


            if (characterReputation == null)
            {
                return NotFound();
            }

            return View(characterReputation);
        }

        public async Task<IActionResult> _RepEditPartial(int? id)
        {
            return PartialView();
        }

Here are my views:

Edit.cshtml:
@model WebAppMVC.Models.CharRepViewModels.CharRepViewModel

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_CharEdLayout.cshtml";
}<h2 style="text-align: center; font-family: 'Times New Roman', Times, serif">Character Database Character Reputation Edit Form</h2><form asp-controller="CharReps" asp-action="Edit" method="post"><div class="form-horizontal"><h4>Character Reputation</h4><hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })<b style="text-align: center; font-family: 'Times New Roman', Times, serif; font-size: x-large">@Html.DisplayFor(model => model.Name.CharFullName)</b><div class="form-group"><label asp-for="@Model.Reputation" class="control-label col-md-2"></label>
            @Html.Partial("_RepEditPartial", @Model.Reputation)</div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-default" /></div></div></div></form><div>
    @Html.ActionLink("Back to Edit Character", "EdChar", "Menu")</div>


_RepEditPartial.cshtml:
@model IEnumerable<WebAppMVC.Models.CharRepViewModels.CharRepListViewModel>
    @{

    }

    <div class="form-group"><div class="col-md-12">
            @(Html
            .Grid(Model)
            .Build(columns =>
            {
                columns.Add(model => model.CharID).Css("hidden");
                columns.Add(model => model.FactionID).Css("hidden");
                columns.Add(model => model.FactionName).Titled("Faction");
                columns.Add(model => model.FactionSet).Titled("Available");  //This needs to be a editable checkbox that will enable the select list to open up if checked
                columns.Add(model => model.RepLevels.Select(a => a.RepLevelID).LastOrDefault()).Css("hidden");  //This needs to be part of a multi select list
                columns.Add(model => model.RepLevels.Select(a => a.RepIsChecked).LastOrDefault());  //This needs to be part of a multi select list, this will be what checks the item
                columns.Add(model => model.RepLevels.Select(a => a.RepLevelName).LastOrDefault()).Titled("Reputation");  //This needs to be part of a multi select list

            })
            .Pageable()
            .Empty("No Data Found")
            )</div></div>

You will notice that currently I have .LastOrDefault in there for the last three entries as not having them in there would either give an error on the add, or display Linq on the view.  This was so I could test if the data was making it to the view.  Using the Html.CheckboxFor(model.FactionSet) gave an error on the checkbox for about unable to convert a bool to system.func<IEnumerable<ViewModel>,bool>', adding a new {@checked ="checked" } gave an error at the Add.  Using @<input type="checkbox" asp-for="model.FactionSet" /> gave an error at the add.  I used these both within the parenthesis after the lambda for model.

Any thoughts?

How to put mvc controller and web api controller together with the same name

$
0
0

The current folder structure is 

Controllers

       Apis

             MoviesController

       MoviesController
      

but it caused a problem every time  I call the delete action in moviescontroller(inside controllers), it calls to moviescontroller inside Apis,

How to solve this problem or should I put the api controllers other place else


update dotnet 1.03 to 1.1.1 on Ubuntu

$
0
0

hello all, How can i upgrade dotnet SDK to 1.1.1 for linux (ubuntu)

Entity Framework Core

$
0
0

Hi,
    how do I create an Edit for the below.
The code pasted works, there is no error.
My question is about CRUD. I would like functionality for (CRUD - Update) / "EDIT" on the Blog.

I think it would be
1. Get row by Id
2. Edit
3. Refresh view

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ExploreCalifornia.Models;
using Microsoft.AspNetCore.Authorization;
namespace ExploreCalifornia.Controllers
{
    [Route("blog")]
    public class BlogController : Controller
    {
        private readonly BlogDataContext _db;
        public BlogController(BlogDataContext db)
        {
            _db = db;
        }
        [Route("")]
        public IActionResult Index(int page = 0)
        {
            var pageSize = 2;
            var totalPosts = _db.Posts.Count();
            var totalPages = totalPosts / pageSize;
            var previousPage = page - 1;
            var nextPage = page + 1;
            ViewBag.PreviousPage = previousPage;
            ViewBag.HasPreviousPage = previousPage >= 0;
            ViewBag.NextPage = nextPage;
            ViewBag.HasNextPage = nextPage < totalPages;
            var posts =
                _db.Posts
                    .OrderByDescending(x => x.Posted)
                    .Skip(pageSize * page)
                    .Take(pageSize)
                    .ToArray();
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                return PartialView(posts);
            return View(posts);
        }
        [Route("{year:min(2000)}/{month:range(1,12)}/{key}")]
        public IActionResult Post(int year, int month, string key)
        {
            var post = _db.Posts.FirstOrDefault(x => x.Key == key);
            return View(post);
        }
        [Authorize]
        [HttpGet, Route("create")]
        public IActionResult Create()
        {
            return View();
        }
        [Authorize]
        [HttpPost, Route("create")]
        public IActionResult Create(Post post)
        {
            if (!ModelState.IsValid)
                return View();
            post.Author = User.Identity.Name;
            post.Posted = DateTime.Now;
            _db.Posts.Add(post);
            _db.SaveChanges();
            return RedirectToAction("Post", "Blog", new
            {
                year = post.Posted.Year,
                month = post.Posted.Month,
                key = post.Key
            });
        }
    }
}
Thanks,

Can Auth0 and asp.net identity be used at the same time

$
0
0

eg: I have a core MVC project, and it uses identity ,then I built WebApis inside the project, can I use auth0 and asp.net identity at the same time

If yes, how should I integrate these two authentication

Entity Framework Core 1.1

$
0
0

Hello guys,

I want to start use Visual Studio 2017, but i afraid from Entity Framework Core 1.1,

I know that Entity Framework Core not support Stored Procedures, 

But i want to make big project and i need to use all features, 

can i depend on Entity Framework Core 1.1,  or it is not suits for all project

thanks

Can't run the setup from dotnet new reactredux

$
0
0

After doing:

dotnet new reactredux

dotnet restore

dotnet run

I get this error:

ERROR in [at-loader] ./ClientApp/components/Layout.tsx:13:21
    TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<NavMenu> & { children?: ReactNode; } & void'.
  Type '{}' is not assignable to type 'void'.

Switching to VS Code and running from VS Code's debug launcher gives error message:

Could not find the "preLaunchTask": "build",

So being a newbie at learning .NET Core, I need some help just to get started.

Async method hanging the second time it is called

$
0
0

I have converted my code as much as possible line for line from old asp.net to .net core.

One piece of code is not working and I think it is because a deadlock is happening on an async method call.

Translating the code directly from its previous equivalent, the code is like this:

//loop at this level - many health checks to carry out

try

{

    bool result = await healthCheckable.GetHealthAsync(); 

}

catch(Exception ex)

{

   

}

 note that an exception is raised each time the healthcheck code is executed in this scenario as a service is down.

The first time around the loop the exception is caught correctly, the second time around, the code simply hangs on the healthservice check.

 I have tried .Wait() and I have tried .Result;  and I have tried ConfigureAwait(false) - all the way up the call tree

At this point I have no clue what to try next.. help?

View Component Grief - Not Handling Paginated List

$
0
0

Not even sure this is possible, thought it would be very nice to have though.

I have created a sales page, with a view component of outstanding quote requests.

@{
    ViewData["Title"] = "Sales Page";
}<h2>Shenton Application - Sales Team</h2>

To start a sale first select Quote Request

<h2><a asp-area="" asp-controller="QuoteRequests" asp-action="SalesCreate">Quote Request</a></h2><h4> Quote Requests Not Quoted</h4><div>@await Component.InvokeAsync("QuoteRequests")</div><h4>Quotes To Follow Up</h4>

All fine and dandy.

Then I thought hold on wouldn't it be nice if I can sort the quote requests and maybe there will be more than a few outstanding, I hope not, but should build it in, just in case, and then whilst I am at it lets add search as well.  Cant think why, but I guess a contact may call up and we may want to search his request out to update it or something.

The code I added to view component is:

public IViewComponentResult Invoke(
            string sortOrder,
            string currentFilter,
            string searchString,
            int? page)
        {
            ViewData["QRSortParm"] = sortOrder;

            ViewData["CloseDateSortParm"] = String.IsNullOrEmpty(sortOrder) ? "close_desc" : "";
            ViewData["RequestSortParm"] = sortOrder == "Request" ? "request_desc" : "Request";
            ViewData["QDSortParm"] = sortOrder == "QD" ? "qd_desc" : "QD";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {

                searchString = currentFilter;

            }

            ViewData["CurrentFilter"] = searchString;

            var quoteRequests = from q in _context.QuoteRequest
                        .Where(q=>q.Quoted==false)
                        select q;

            if (!String.IsNullOrEmpty(searchString))
            {
                quoteRequests = quoteRequests.Where(q => q.Requested.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "close_desc":
                    quoteRequests = quoteRequests.OrderByDescending(q => q.CloseDate);
                    break;

                case "request_desc":
                    quoteRequests = quoteRequests.OrderByDescending(q => q.Requested);
                    break;

                case "Request":
                    quoteRequests = quoteRequests.OrderBy(q => q.Requested);
                    break;

                case "qd_desc":
                    quoteRequests = quoteRequests.OrderByDescending(q => q.QDescription);
                    break;

                case "QD":
                    quoteRequests = quoteRequests.OrderBy(q => q.QDescription);
                    break;

                default:
                    quoteRequests = quoteRequests.OrderBy(q => q.CloseDate);
                    break;
            }

            //return View(quoteRequests);
            int pageSize = 7;

            return View(PaginatedList<QuoteRequest>.CreateAsync(page ?? 1, quoteRequests.AsNoTracking(), pageSize));
        }

normally I have async PaginatedList, but this didn't like it, so I took the async out.

Then in default view I have:

@model PaginatedList<Eva804.Models.QuoteRequest><form asp-action="Index" method="get"><div class="form-actions no-color"><p>
            Find by Requested: <input type="text" name="SearchString" value="@ViewData["currentFilter"]" /><input type="submit" value="Search" class="btn btn-default" /><a asp-action="Index">Back to list</a></p></div></form><table class="table"><tr><th><a asp-action="Index" asp-route-sortOrder="@ViewBag.CloseDateSortParm" asp-route-currentFilter="@ViewData["CurrentFilter"]">Closing Date</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewBag.RequestSortParm" asp-route-currentFilter="@ViewData["CurrentFilter"]">Requested By</a></th><th>
            Contact Detail</th><th><a asp-action="Index" asp-route-sortOrder="@ViewBag.QDSortParm" asp-route-currentFilter="@ViewData["CurrentFilter"]"> Quote Description</a></th><th></th></tr>


    @foreach (var q in Model)
    {


        <tr><td>
                @q.CloseDate</td><td>

                @q.Requested
            </td><td>
                @q.ConDetail</td><td>
                @q.QDescription.Substring(0, Math.Min(q.QDescription.Length, 28))</td><td><a asp-controller="QuoteRequests"
                   asp-action="Details"
                   asp-route-id="@q.QuoteRequestID">Details</a> |<a asp-controller="Quotes"
                   asp-action="Create"
                   asp-route-id="@q.QuoteRequestID">Quote</a></td></tr>

    }

</table>
@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}<a asp-action="Index"
   asp-route-page="@(Model.PageIndex-1)"
   class="btn btn-default @prevDisabled btn">
    Previous</a><a asp-action="Index"
   asp-route-page="@(Model.PageIndex+1)"
   class="btn btn-default @nextDisabled btn">
    Next</a>

Nothing wrong in here I can see.  Same code I use elsewhere for searching, sorting and paging.  All good I thought.

However when I click on the sales index in IE it is creating an error message:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Threading.Tasks.Task`1[Eva804.PaginatedList`1[Eva804.Models.QuoteRequest]]', but this ViewDataDictionary instance requires a model item of type 'Eva804.PaginatedList`1[Eva804.Models.QuoteRequest]'.

Which to me makes no sense.

Why is it telling me about Systems Threading Tasks when neither the ViewComponent or the Default list it as a using item?

Why is it throwing this error at all?

Is this fixable or am I asking too much from the view component?


PTO Calender

$
0
0

Here is my code for my PTO calendar:

<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="2" BackColor="#F7F6F3" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" Height="161px" Width="1028px">
<HeaderStyle BackColor="#5D7B9D" BorderStyle="Solid" Font-Bold="True" Font-Size="0.9em" ForeColor="White" HorizontalAlign="Left" />
<NavigationButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />
<SideBarButtonStyle BorderWidth="0px" Font-Names="Verdana" ForeColor="White" />
<SideBarStyle BackColor="#7C6F57" BorderWidth="0px" Font-Size="0.9em" VerticalAlign="Top" />
<StepStyle BorderWidth="0px" ForeColor="#5D7B9D" />
<WizardSteps>
<asp:WizardStep runat="server" title="Personal Info">
<br />
Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="TextBox4" runat="server" Width="231px"></asp:TextBox>
<br />
Employee ID:
<asp:TextBox ID="TextBox2" runat="server" Width="232px"></asp:TextBox>
<br />
Supervisor:&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="TextBox3" runat="server" Width="231px"></asp:TextBox>
</asp:WizardStep>
<asp:WizardStep runat="server" title="Days Requesting">
Start Date:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Calendar ID="Calendar2" runat="server" BackColor="White" BorderColor="#999999" CellPadding="4" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" Height="180px" Width="200px">
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt" />
<NextPrevStyle VerticalAlign="Bottom" />
<OtherMonthDayStyle ForeColor="Gray" />
<SelectedDayStyle BackColor="#666666" Font-Bold="True" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" />
<TitleStyle BackColor="#999999" BorderColor="Black" Font-Bold="True" />
<TodayDayStyle BackColor="#CCCCCC" ForeColor="Black" />
<WeekendDayStyle BackColor="#FFFFCC" />
</asp:Calendar>
<br />
End Date:<br />&nbsp;
<asp:Calendar ID="Calendar3" runat="server" BackColor="White" BorderColor="#999999" CellPadding="4" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" Height="180px" Width="200px">
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt" />
<NextPrevStyle VerticalAlign="Bottom" />
<OtherMonthDayStyle ForeColor="Gray" />
<SelectedDayStyle BackColor="#666666" Font-Bold="True" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" />
<TitleStyle BackColor="#999999" BorderColor="Black" Font-Bold="True" />
<TodayDayStyle BackColor="#CCCCCC" ForeColor="Black" />
<WeekendDayStyle BackColor="#FFFFCC" />
</asp:Calendar>
<br />
<br />
Type of PTO:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>Vacation</asp:ListItem>
<asp:ListItem>Personal</asp:ListItem>
<asp:ListItem>Sick</asp:ListItem>
</asp:DropDownList>
<br />
</asp:WizardStep>
<asp:WizardStep runat="server" Title="Summary">
</asp:WizardStep>
</WizardSteps>
</asp:Wizard>

For the last step In the summary I tried to add a field to show  a summary of the info added.

The last step Im pretty much getting a confirmation saying the info was submitted : The confirmation message will be: "Name, your request for numberOfDays type days has been received and has been forwarded to supervisorName for approval". Where the name is the name of the user, numberOfDays is the end date - start date + 1, and supervisorName is the name of the supervisor. Also it must include validation for example where end date cant be before start date.

I would appreciate any help

Custom Validation Attribute not working client side

$
0
0

Its  been a while since I have done this and I read about the changes in the docs but this isn't working on the client. Any help would be appreciated.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class NonAlphaUppercaseAttribute : ValidationAttribute, IClientModelValidator
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string password = value.ToString();
            bool nonAlpha = false;
            bool uppercase = false;

            foreach(var character in password)
            {
                if(!char.IsLetterOrDigit(character))
                {
                    nonAlpha = true;
                    break;
                }
            }

            foreach (var character in password)
            {
                if (char.IsUpper(character))
                {
                    uppercase = true;
                    break;
                }
            }

            if(!nonAlpha || !uppercase)
            {
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            }

            return null;

        }// IsValid()

        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-nonalphauppercase", errorMessage);

        }// AddValidation()

        private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }


    }// NonAlphaUppercaseAttribute class
(function (win, doc, undefined) {

    var nonalpha = false;
    var uppercase = false;


    var isValid = function (value) {

        var pattern = /\W|_/;
        nonalpha = pattern.test(value);
        var pattern2 = /[A-Z]/;
        uppercase = pattern2.test(value);

        var result = (nonalpha === true && uppercase === true);

        return result;

    };

    jQuery.validator.addMethod('NonAlphaUppercase', isValid);
    jQuery.validator.unobtrusive.adapters.add('nonalphauppercase', {}, function (options) {
        options.rules['nonalphauppercase'] = true;
        options.messages['nonalphauppercase'] = options.message;
    });

})(window, document);
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[NonAlphaUppercase(ErrorMessage = "{0} must have an uppercase and non-alpha numeric character")]
[DataType(DataType.Password)]
[Display(Name = "password")]
public string Password { get; set; }

Thanks in advance!


Deployed WebAPI project fails to perform dependency injection for middleware

$
0
0

I'm deploying a site to Windows Server 2012 R2, and I get this error from the deployed site:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Cors.Infrastructure.ICorsService' while attempting to activate 'Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware'.

Microsoft.Extensions.Internal.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider)

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Cors.Infrastructure.ICorsService' while attempting to activate 'Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware'.
Microsoft.Extensions.Internal.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider)
Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass3_0.<UseMiddleware>b__0(RequestDelegate next)
Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

I took out app.UseCors() to see what would happen and redeployed, and I realized that for every middleware I'm using that uses dependency injection, I'm getting the same type of error (it will be a different service and different middleware, but essentially the same error).  If I take all the middleware out of the configuration, the webapi finally does run.  

This isn't an issue when I run the webapi application locally.  Why is it behaving this way when deployed?

textbox' height

$
0
0

Hi,

I just deployed an application to QA and the deployed web application's text boxes' height are twice the size as that of development's running in VS.  Also, the spaces with between are much larger than the one which showed in my development environment.  I checked the CSS for both and they were identical.

Can anyone tell me what's wrong?

Thanks,

tinac99

How to return Unauthorized result in OnActionExecuting method

$
0
0
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   var authenticateKey = filterContext.HttpContext.Request.Headers["AuthenticateKey"];
   if (String.IsNullOrEmpty(authenticateKey))
   {
       base.OnActionExecuting(filterContext);
   }
   else
   {
       filterContext.Result = new JsonResult(new { HttpStatusCode.Unauthorized });
//Instead of jsonresult, here I want to return response Unauthorized to browser } }

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>