I have an mvc5 application that I want to allow for two different authentication options to take place.

For users within the company, I want to authenticate against Azure AD using OpenId. I have this piece working correctly.

            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });

For external users, I want to have a separate login page for them, where they can input a userId/password, and use basic CookieAuthentication to authenticate.

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = System.TimeSpan.FromMinutes(60),
            SlidingExpiration = true,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User, int>(
                       validateInterval: TimeSpan.FromMinutes(30),
                       regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                       getUserIdCallback: id => id.GetUserId<int>()),

            }
        });

Ideally, on my controllers, I could tag them with an implementation of the AuthorizeFilter that would handle either user case -- my thought is on the database, I would have a central user database that includes AD and External users, so that I can create a role/permissions structure that is common to both. Ideally the only piece that would be different is the path to initial authentication, and after that, I could authorize very similarly.

I have implemented both of these auth flows before separately, but not sure how to offer them simultaneously, while minimizing code duplication on the authentication piece.

We are uploading Excel content to SQL Sever DB using bulkupload and Oledb. We are getting error System.Data.OleDb.OleDbException: Unspecified error again and again.

We understand that this error occurs when ASP.NET try to access some temp folder. Based on another SO Post we have set impersonate to false in web.config file. But it did not help. Also we have a scheduled job running once in a week to restart IIS. That is also not helping. But when we restart IIS manually it works for few days again we receive the same error.

We are using .NET Framework 3.5 and Server is Windows 2003 ( I KNow it's old, but that decision is not mine to take :( )

Can anybody explain what is the problem and how can we resolve it permanently.

Thanks in advance.

I want to split string using textchanged event. example i have 10000853,154SSDAAS but i just want to retrieve only 10000583. I try to use split but it doesn't work. Can someone help me. Here is my code:

 Private Sub AssetTxt_TextChanged(sender As Object, e As EventArgs) Handles AssetTxt.TextChanged
    Try
        Dim split() As String = AssetTxt.Text.Split(",")
        If split.Count > 2 Then
            AssetTxt.Text = split(0)
        End If
    Catch ex As Exception

    End Try

This question already has an answer here:

I am working on a database project and I needed a checkbox list for the create method. Model:

public class LabAppointmentCreationModel
{
    public string PatientName{get;set;}

    public string PatientsPhoneNumber {get;set;}

    public DateTime AppointMentDateTime{get;set;}

    public List<TestNeeded_CheckBoxListItem> TestsNeeded {get;set;}
}

public class TestNeeded_CheckBoxListItem
{
    public int Id{get;set;}

    public string TestName {get;set;}

    public bool IsChecked {get;set;}

}

In controller I returned the model with available tests.

public async Task<IActionResult> Index()
{
    var tests=await _context.Tests.ToListAsync();
    var testItems=new List<TestNeeded_CheckBoxListItem>();
    foreach (var test in tests)
    {
        testItems.Add(new TestNeeded_CheckBoxListItem{Id=test.Id,TestName=test.Name,IsChecked=false});
    }
    var model=new LabAppointmentCreationModel(){TestsNeeded=testItems};
    return View(model);
}

Now in index page I displayed the appointments using jquery datatables. And for adding appointment I created a form within a bootstrap modal. In form I added the foreach loop for displaying the tests in the form of checkbox list.

<form asp-controller="Appointment" asp-action="Create"
                  data-ajax="true" data-ajax-method="POST"
                  data-ajax-mode="replace" data-ajax-success="onAddSuccess"
                  data-ajax-failure="onFailed">

                <div class="modal-body">

                    @Html.AntiForgeryToken()

                    <div id="formBody">

                        <div class="category-title">Patient Details</div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label" asp-for="PatientName">Name:</label>
                                    <input class="form-control" asp-for="PatientName" />
                                </div>
                                <span asp-validation-for="PatientName" class="text-danger"></span>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label" asp-for="PatientsPhoneNumber">Phone Number:</label>
                                    <input class="form-control" type="tel" min="9" asp-for="PatientsPhoneNumber" />
                                </div>
                                <span asp-validation-for="PatientsPhoneNumber" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="category-title">Available Tests</div>
                        <div class="row">
                            <div class="col-md-12">
                                @foreach(var test in Model.TestsNeeded)
                                {
                                    <div>
                                        <input type="hidden" asp-for="@test.Id"/>
                                        <label>
                                            <input type="checkbox" asp-for="@test.IsChecked"/>
                                            @unit.TestName
                                        </label>
                                    </div>
                                }
                            </div>
                        </div>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success btn-fixed-width">Save</button>
                    <button type="button" class="btn btn-default btn-fixed-width" data-dismiss="modal">
                        Close
                    </button>
                </div>

            </form>

Ok now when I run the code it will work. It loads the index and displays checkbox and text needed everything.

But when I look at the source the input hidden fields doesn't have any values at all.

enter image description here

I tried with for loop and even tried adding value directly still it wont render the id to value. However when I displayed the id value in label (@test.Id) then it displays the correct id value for that test.

enter image description here

It seems I am getting values from the controller but in view its not rendering it.

I also followed this https://exceptionnotfound.net/simple-checkboxlist-in-asp-net-mvc/ yet nothing works.

I don't understand what I am missing here?

Recently we have migrated web application from 32bit to 64bit. But now there is weird behavior in session values, as session picking old values on invoking response.redirect method.

For example:

On drop-down event change we set the below value of session in page1.aspx Session ("type")= "IN". When we redirected to page2.aspx and Now the value of session ("type") is nothing.

Then on next time again if we tried to set value of session ("type") ="OUT" in page1.aspx on drop-down change event & redirect to page2.aspx second the value of session ("type") is "IN"

This only happening after web application migrated from 32bit to 64bit , as before in 32bit it was working fine. And also this issue is only on production server but not in Test server nor on Quality server.

Need help.

I have 3 asp.net solutions which makes one application. These solution hosted on 3 IIS web site site and redirection happens among them as required. after login(1st website) , an update to DB(from second website) does not reflect on a web page on 3rd web site.

I understand it is because application hosted on 3 different web sites and the dlls from other web sites does not get refreshed. To solve this problem,presently i am logging out and loggin in..so all the websites get refreshed during login.

But i dont want re-login. how to update other 2 website dlls after the update to DB?

We are working on one project and we have used our Smart Wizard Which Is for edit. We are having partial views so page is not loading multiple times. The problem we are facing is multiple calls to controller(Server Side). i.e. We have edited id 1 one call will go. We are editing id 2 2 calls will go. We are editing id 3 3 calls will go and continues. We have invested 2 days but we are unable to catch the issue can you please help us in catching the issue.

Getting an error while running migrations command. I explored through the csproj file and itemgroup are in place but still getting the error.

csproj file attached for reference

csproj file

We are trying to save the current date and time in our database in the Datetime format . But the value entered always shows up as 1900-01-01 00:00:00.000.

we tried this code :

  SqlCommand cmd = new SqlCommand("update " + 
                                   con.Database + 
                                 " set Teacher_code=@Teacher_code ,Checkdate=" + 
                                   DateTime.Now.ToShortDateString() + 
                                 " where copycode=@copycode", con);

How to fix this issue?

i have installed 'Microsoft.ACE.OLEDB.12.0' in my local machine. its working properly. but , when i host website i got this error. what i do??

i have registered in webconfig

<add name ="Excel03ConString"

    connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};

                     Extended Properties='Excel 8.0;HDR={1}'" providerName="Microsoft.Office.Interop"/>

<add name ="Excel07ConString"

     connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};

                     Extended Properties='Excel 8.0;HDR={1}'" providerName="Microsoft.Office.Interop"/>

I need help where I can show the arrow up and down in the bootstrap timepicker, because the output that is being shown in my current program is, it's hidden or perhaps blank.

Example Image

so here is how I put it the header the source and javascript function with asp control textbox

<script src="js/jquery-3.3.1.js" type="text/javascript"></script>
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap-timepicker.min.css" rel="stylesheet" type="text/css" /> 
<script src="js/jquery-ui.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/bootstrap-timepicker.min.js" type="text/javascript"></script>

<script>
            $(".timepicker").timepicker
</script>

TextBox

 <asp:TextBox ID="StartTime" data-provide="timepicker" CssClass="timepicker" runat="server" />

I have a url like below:

https://myprod.blabla.com/myapp/?us=9141&co=5590&cl=https%3a%2f%2fmyprod.blabla.com%2fEngine%2fcustom%2flaunch.aspx%3factfk%3dITC%26reg%3d123342%26force%3dfalse

I wanted to rewrite the above url to the below url:

https://externalsite.com/myapp/?token=1234qe_56f-wf.f&us=9141&co=5590&cl=https%3a%2f%2fmyprod.blabla.com%2fEngine%2fcustom%2flaunch.aspx%3factfk%3dITC%26reg%3d123342%26force%3dfalse

https://externalsite.com: External Site address

1234qe_56f-wf.f: Token for external site for handshaking.

Below is my rules I set in urlrewrite:

<rule name="test" stopProcessing="true">
                <match url="^myapp/(.*)" />
                    <conditions>
                        <add input="{CACHE_URL}" pattern="^(https?)://" />
                    </conditions>
                    <serverVariables>
                        <set name="HTTP_ACCEPT_ENCODING" value="" />
                    </serverVariables>
                    <action type="Rewrite" appendQueryString="true"
                    url="https://externalsite.com/myapp/{R:1}?token=1234qe_56f-wf.f" />

            </rule>

Note: I also checked Enable proxy checkbox in application request routing.

Please help me to get rid from this. I spent whole day to find solution but no luck till now.

Thanks in advance.

I have 3 multiselect dropdown lists. When I make multiple selections from each dropdown lists and submit I can see that the results are being posted but doesn't get passed to the controller.

my view

    @model Facility.AdgarWeb.ViewModels.MailingConfigVM

    @using (Html.BeginForm("New", "MailingConfig"))
    {
@*Company List Dropdown*@
<div class="mailingConfiguration__modal__dropDown mailingConfiguration__modal__dropDown--companyList">
    <h3 class="mailingConfiguration__modal__dropDown__title">Wybierz Budynki</h3>
    <div class="dropdown companiesDropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="companiesButton" aria-haspopup="true" aria-expanded="false">
            Select Building
        </button>
        @Html.LabelFor(m => m.allBuildings)
        @Html.DropDownListFor(m => m.allBuildings, new MultiSelectList(Model.allBuildings, "Id", "Name"), new { @class="dropdown-menu", @multiple="true" })
    </div>
</div>

@*Classification List Dropdown*@
<div class="mailingConfiguration__modal__dropDown mailingConfiguration__modal__dropDown--classificationList">
    <h3 class="mailingConfiguration__modal__dropDown__title">Wybierz Klasyfikacje</h3>
    <div class="dropdown classificationDropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="classificationButton" aria-haspopup="true" aria-expanded="false">
            Select Classification
        </button>
        @Html.LabelFor(m => m.allServices)
        @Html.DropDownListFor(m => m.allServices, new MultiSelectList(Model.allServices, "Id", "Name"), new { @class = "dropdown-menu", @multiple = "true" })
    </div>
</div>
@*Users List Dropdown*@
<div class="mailingConfiguration__modal__dropDown mailingConfiguration__modal__dropDown--usersList">
    <h3 class="mailingConfiguration__modal__dropDown__title">Wybierz Użytkowników</h3>
    <div class="dropdown usersDropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="usersButton" aria-haspopup="true" aria-expanded="false">
            Select Users
        </button>
        @Html.LabelFor(m => m.allUsers)
        @Html.DropDownListFor(m => m.allUsers, new MultiSelectList(Model.allUsers, "Id", "UserName"), new { @class = "dropdown-menu", @multiple = "true" })
    </div>
</div>

<input type="submit" class="btn btn-primary" name="New" value="Submit">
}

viewmodel

    public class MailingConfigVM
{
    [Display(Name = "Buildings")]
    public IEnumerable<Building> allBuildings { get; set; }

    [Display(Name = "Services")]
    public IEnumerable<Facility.Model.Service> allServices { get; set; }

    [Display(Name = "Users")]
    public IEnumerable<User> allUsers { get; set; }

}

controller

        public ActionResult Create()
    {
        if (!SessionControlService.CheckIsLoginStillTrue(_loginsService, HttpContext))
            return RedirectToAction("Login", "Account");

        MailingConfigVM vm = new MailingConfigVM();
        vm.allBuildings = _buildingService.GetBuildings();
        vm.allServices = _serviceService.GetServices();
        vm.allUsers = _userService.GetUsers().Where(user => user.Roles.Any(r => r.Id <= 4));
        var buildings = _buildingService.GetBuildings().ToList();
        return View(vm);
    }
    [Authorize(Roles = "Admin")]
    [HttpPost]
    public ActionResult New(MailingConfigVM mailingConfigVM)
    {
        if (!SessionControlService.CheckIsLoginStillTrue(_loginsService, HttpContext))
            return RedirectToAction("Login", "Account");
        if (!User.IsInAnyRoles("Admin"))
            return RedirectToAction("Index");

        return RedirectToAction("Create", "MailingConfig");
    }

The create controller populates the forms with datas for selection and New controller is httppost. I want the selected items to be passed to this controller, but after POST the result is "COUNT=0" on each of the list.

I would appreciate any help.

This question already has an answer here:

I am working on a database project and I needed a checkbox list for the create method. Model:

public class LabAppointmentCreationModel
{
    public string PatientName{get;set;}

    public string PatientsPhoneNumber {get;set;}

    public DateTime AppointMentDateTime{get;set;}

    public List<TestNeeded_CheckBoxListItem> TestsNeeded {get;set;}
}

public class TestNeeded_CheckBoxListItem
{
    public int Id{get;set;}

    public string TestName {get;set;}

    public bool IsChecked {get;set;}

}

In controller I returned the model with available tests.

public async Task<IActionResult> Index()
{
    var tests=await _context.Tests.ToListAsync();
    var testItems=new List<TestNeeded_CheckBoxListItem>();
    foreach (var test in tests)
    {
        testItems.Add(new TestNeeded_CheckBoxListItem{Id=test.Id,TestName=test.Name,IsChecked=false});
    }
    var model=new LabAppointmentCreationModel(){TestsNeeded=testItems};
    return View(model);
}

Now in index page I displayed the appointments using jquery datatables. And for adding appointment I created a form within a bootstrap modal. In form I added the foreach loop for displaying the tests in the form of checkbox list.

<form asp-controller="Appointment" asp-action="Create"
                  data-ajax="true" data-ajax-method="POST"
                  data-ajax-mode="replace" data-ajax-success="onAddSuccess"
                  data-ajax-failure="onFailed">

                <div class="modal-body">

                    @Html.AntiForgeryToken()

                    <div id="formBody">

                        <div class="category-title">Patient Details</div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label" asp-for="PatientName">Name:</label>
                                    <input class="form-control" asp-for="PatientName" />
                                </div>
                                <span asp-validation-for="PatientName" class="text-danger"></span>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label" asp-for="PatientsPhoneNumber">Phone Number:</label>
                                    <input class="form-control" type="tel" min="9" asp-for="PatientsPhoneNumber" />
                                </div>
                                <span asp-validation-for="PatientsPhoneNumber" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="category-title">Available Tests</div>
                        <div class="row">
                            <div class="col-md-12">
                                @foreach(var test in Model.TestsNeeded)
                                {
                                    <div>
                                        <input type="hidden" asp-for="@test.Id"/>
                                        <label>
                                            <input type="checkbox" asp-for="@test.IsChecked"/>
                                            @unit.TestName
                                        </label>
                                    </div>
                                }
                            </div>
                        </div>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success btn-fixed-width">Save</button>
                    <button type="button" class="btn btn-default btn-fixed-width" data-dismiss="modal">
                        Close
                    </button>
                </div>

            </form>

Ok now when I run the code it will work. It loads the index and displays checkbox and text needed everything.

But when I look at the source the input hidden fields doesn't have any values at all.

enter image description here

I tried with for loop and even tried adding value directly still it wont render the id to value. However when I displayed the id value in label (@test.Id) then it displays the correct id value for that test.

enter image description here

It seems I am getting values from the controller but in view its not rendering it.

I also followed this https://exceptionnotfound.net/simple-checkboxlist-in-asp-net-mvc/ yet nothing works.

I don't understand what I am missing here?

Hi I am using View bag in mvc to fetch the Name from controller my code is

 var Name= '@Html.Raw(ViewBag.Name)';

But when the Name is Unicode character then @html.raw is not working properly for IE browser it is working properly for Chrome I have already set

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

Please suggest

Also if i don't give my credentials it gives some configuration file error.

I want AD authentication to take place. But it always picks my username when logged from different systems. How do I resolve it?

Is there any way I can make a user group and assign that to the Identity in DefaultAppPool or do I need to change the code for authentication as it is only taking the user from the Identity mentioned in DefaultAppPool?

The code that I am using to validate the user who logs in is as follows:

string groupName = ConfigurationManager.AppSettings["groupName"].ToString();
string domainName = ConfigurationManager.AppSettings["domain"].ToString();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx,IdentityType.SamAccountName,System.Security.Principal.WindowsIdentity.GetCurrent().Name);
if (user != null)
{ //code as required }

code in web.config file:

<appSettings>
  <add key="domain" value="EYDEV" />
  <add key="groupName" value="Domain Users" />
</appSettings> 

When I use Web Deploy it pushes all the files to the server regardless of whether they are changed or not.

It wasn't doing this before but I installed some Visual Studio extensions and now I can't figure out what changed.

What configuration should I change in order to make Web Deploy publish only changed files?

How can i place a limit of the number of concurrent session objects in IIS?

  • if sessions are being created faster than they expire (expire e.g. 30 minutes)
  • session objects will pile up in memory
  • crashing the worker process when it runs out of memory

I want IIS/ASP.net to discard oldest session objects, before it gets to the point that it crashes.

  • A cap of 10,000 of these 10 KB session objects in memory would be fine.
  • Because when we start to hit 90,000 sessions during a heavy usage by "users", memory consumption becomes a problem.

How can I read C# dictionary to Javascript in MVC3 without Razor? I can do this fine with newer MVC with

var texts = @Html.Raw(JsonConvert.SerializeObject(Model.TextDict));

But my older project does not recognize Jsoncovert. I tried with:

var texts = <% Html.Raw(Json.Encode(Model.TextDict)); %>

But here the texts is undefined.

Is there a simple way to get the public static string result to the controller.

So im trying to make so when you upload you're image it gets resized. i made a following code in my Toolbox

public static string ImageUpload(HttpPostedFileBase file, string SubFolder)
{
    Guid gi = Guid.NewGuid();
    string extension = Path.GetExtension(file.FileName);

    using (var image = Image.FromStream(file.InputStream, true, true))
    {
        var thumbWidth = 700;
        var thumbHeight = 700;
        if (image.Width < image.Height)
        {
            //portrait image  
            thumbHeight = 640;
            var imgRatio = (float)thumbHeight / (float)image.Height;
            thumbWidth = Convert.ToInt32(image.Width * imgRatio);
        }
        else
        if (image.Height < image.Width)
        {
            //landscape image  
            thumbWidth = 960;
            var imgRatio = (float)thumbWidth / (float)image.Width;
            thumbHeight = Convert.ToInt32(image.Height * imgRatio);
        }

        using (var thumb = image.GetThumbnailImage(
            thumbWidth,
            thumbHeight,
            () => false,
            IntPtr.Zero))
        {
            var jpgInfo = ImageCodecInfo.GetImageEncoders()
                .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();

            using (var encParams = new EncoderParameters(1))
            {
                string thumbPath = "~/Content/admin/images/" + SubFolder;
                bool isExists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(thumbPath));

                if (!isExists)
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(thumbPath));
                }

                var thumbPathFull = Path.Combine(HttpContext.Current.Server.MapPath(thumbPath), gi + extension);
                string newfileurl = "/Content/admin/images/" + SubFolder + gi + extension;
                long quality = 1500;
                encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                thumb.Save(thumbPathFull, jpgInfo, encParams);
                return newfileurl;
            }
        }
    }

so i want the value "return newfileurl;" to my controller so how do i call it. so i can save the the string to my db to get the image frontend

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult NewsCreate(NewsItem ni, HttpPostedFileBase file)
    {
        Guid gi = Guid.NewGuid();
        if (file != null && file.ContentLength > 0)
        {
            CRUDHelper.ImageUpload(file, "newsimage");
        ni.Image = **??????insert solution here??????**;
        db.NewsItems.Add(ni);
        db.SaveChanges();
}

I have used some data annotation and regular expression in my model same as below

[StringLength(10, MinimumLength = 10, ErrorMessageResourceType = 
typeof(ResourcesPrj.Resource), ErrorMessageResourceName = 
"NationalIdError")]
[RegularExpression("(^[0-9]{10})", ErrorMessageResourceType = 
typeof(ResourcesPrj.Resource), ErrorMessageResourceName = 
"NationalIdError")]
[Required(ErrorMessageResourceType = typeof(ResourcesPrj.Resource), ErrorMessageResourceName = "NationalIdError")]
    public string NationalCode { get; set; }

Now my problem is that, when I focousout from NationalCode and the input value is not correct and error shown but the focus is not on NationalCode editor. Is there any way to focus on this field again when the input value is not correct?