Undesired logout in MVC 4 - asp.net-mvc-4

I have this issue after publish project in host, in development environment everything is OK!
In my published MVC 4.0 website when an authenticated user try to upload a picture, the user has been logged off and redirected to the Login Page.
I've used the following code to upload pictures and successfully work in local:
private void TryUploadImages(Product product)
{
const string emptyImage = "empty.jpg";
try
{
for (int idx = 0; idx < 3; idx++)
{
if ((Request.Files.Count < 3) ||
(Request.Files[idx] == null) ||
(Request.Files[idx].ContentLength > 1024 * 1024 * 5) ||
(Request.Files[idx].ContentLength <= 0))
{
if ((idx == 0 && string.IsNullOrEmpty(product.ImageFilename)) ||
(idx == 1 && string.IsNullOrEmpty(product.ThumbnailImage)) ||
(idx == 2 && string.IsNullOrEmpty(product.AttributesImage)))
throw new Exception(GlobalResources.Global_Image_Restrictions_Error);
continue;
}
HttpPostedFileBase uploadedFile = Request.Files[idx];
string fileName = Path.GetFileName(uploadedFile.FileName);
using (var img = Image.FromStream(uploadedFile.InputStream))
{ bool temp = img.Width > 0; }
if (!string.IsNullOrEmpty(fileName))
{
string[] filenames = {"product", "product-thumb", "attribute"};
fileName = string.Format("{0}-{1}{2}",
filenames[idx],
Guid.NewGuid().ToString().Replace("-", string.Empty),
Path.GetExtension(fileName));
var physicalPath = Path.Combine(Server.MapPath("~/Images/sitepx/products/"), fileName);
uploadedFile.SaveAs(physicalPath);
switch (idx)
{
case 0:
product.ImageFilename = fileName;
break;
case 1:
product.ThumbnailImage = fileName;
break;
case 2:
product.AttributesImage = fileName;
break;
}
}
else
{
switch (idx)
{
case 0:
product.ImageFilename = emptyImage;
break;
case 1:
product.ThumbnailImage = emptyImage;
break;
case 2:
product.AttributesImage = emptyImage;
break;
}
}
}
}
catch (Exception ex)
{
ViewBag.UploadError = ex.Message;
product.ImageFilename = emptyImage;
}
}
and call it in this action method:
[AllowUploadSafeFiles]
[AllowUploadSpecialFilesOnly(".jpg,.jpeg,.gif,.png,.bmp")]
[HttpPost]
public virtual ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
TryUploadImages(product);
product.ModifiedOn = DateTime.Now;
_db.Entry(product).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction(MVC.Product.ActionNames.Index);
}
ViewBag.CategoryId = new SelectList(_db.Categories, "CategoryId", "Name", product.CategoryId);
ViewBag.ProductTypeId = new SelectList(_db.ProductTypes, "ProductTypeId", "Name", product.ProductTypeId);
return View(product);
}
Moreover I authorize controller for particular Roles and also disable Sessions in Web.config for security reasons :
<httpModules>
<-- blah blah blah ... -->
<!-- Disable Session -->
<remove name="Session" />
</httpModules>
<sessionState mode="Off" />
If you still need additional information, feel free to tell.
Thanks
===== EDITED (Add authentication detail) =====
Maybe I looking for trouble in the wrong place, my login method is something like this:
[AllowAnonymous]
public virtual ActionResult Login(string returnUrl)
{
if (User.Identity.IsAuthenticated)
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
return RedirectToLocal(returnUrl);
else
return Redirect(ReturnRedirectUrl(returnUrl));
ViewBag.ReturnUrl = returnUrl;
ViewBag.Roles = GetAllAccountRoles();
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, model.RememberMe))
{
var location = ReturnRedirectUrl(returnUrl);
return string.IsNullOrEmpty(location)
? RedirectToAction(MVC.Account.Login())
: RedirectToLocal(location);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", GlobalResources.Account_Login_ModelError);
return View(model);
}
and this is Role base ReturnRedirectUrl used in login function:
private string ReturnRedirectUrl(string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
{
foreach (var role in Roles.GetAllRoles().Where(Roles.IsUserInRole))
{
switch (role)
{
case "info":
returnUrl = Url.Action(MVC.SiteManage.Index(1));
break;
case "support":
returnUrl = Url.Action(MVC.SiteManage.Index(2));
break;
case "sales":
returnUrl = Url.Action(MVC.SiteManage.Index(3));
break;
case "admin":
returnUrl = Url.Action(MVC.SiteManage.Index(6));
break;
case "club-member":
returnUrl = Url.Action(MVC.SiteManage.Index());
break;
case "vendor-reseller":
returnUrl = Url.Action(MVC.SiteManage.Index());
break;
case "sales-reseller":
returnUrl = Url.Action(MVC.SiteManage.Index());
break;
}
}
}
return returnUrl;
}

Related

getExternalStoragePublicDirectory is deprecated and getExternalFilesDir is not working

i'm trying to take a photo and upload it. weird thing is, it's working on my android 9 device, but not working on the android 11 device... input field remains as "no file chosen" even after taking the photo.
here are the codes related to photo upload system
private String mCM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
ActivityResultLauncher<Intent> startActivityIntent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
Uri[] results = null;
if (result.getResultCode() == Activity.RESULT_OK) {
if(null == mUMA){
return;
}
if(result.getData() == null || result.getData().getData() == null){
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = result.getData().getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
});
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, perms, FCR);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FCR);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, FCR);
}
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (MainActivity.this.getPackageManager().resolveActivity(takePictureIntent, 0) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e("TAG", "ioexception log", ex);
}
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityIntent.launch(chooserIntent);
return true;
}
private File createImageFile() throws IOException{
String imageFileName = java.util.UUID.randomUUID().toString();
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
this is the last deprecation warning i have left in my app. it's working fine on all 3 of my test devices(android 7-9-11) with "getExternalStoragePublicDirectory"
I tried again with "getExternalFilesDir" and checked "Internal shared storage\Android\data-myapp-\files\Pictures"
there are files but 0bytes...
i can hardcode like this and it works on all 3 devices without any deprecation warnings...
File storageDir = new File("/storage/emulated/0/Pictures/");
but its probably even worse than using deprecated api?

Multiple parameter in Get Method

[Route("api/LoginValues/itemcode/{username}/{password}")]
[HttpGet]
public IEnumerable<AC_Attendance> Get(string username, string password )
{
**var list = from g in db.AC_Attendances where g.username == username select g;**
return list;
}
How i want to make " g.username == username AND g.password== password "
For example I have taken employee(userID and password) as parameter.
public IEnumerable<Employee> Get(int Id, string password)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Employees.Where(tem => tem.ID == Id && tem.password
== password).ToList();
}
}
public IEnumerable<AC_Attendance> Get(string username, string password)
{
var a = db.AC_Attendances
.Where(s => s.username == username && s.password == password)
.ToArray();
if (a != null)
{
return a;
}
else
{
return null;
}
}

AspNet.Identity.Core : how to create a user manually - HashPassword

I have a .NET core app, it works perfectly.
But I need to create a batch of new users, by inserting directly into the database.
The problem now is that when I try to login, it failed...
I suspect a problem with the hashed password.
I use the following code to generate my hash and security stamp:
_user.SecurityStamp = Guid.NewGuid().ToString("D");
_user.UserName = _userName;
_user.Email = _email;
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher<IdentityUser>();
IdentityUser identityUser = new IdentityUser(Guid.Parse(_user.Id), _userName, _email);
_user.PasswordHash = hasher.HashPassword(identityUser, _password);
From my understanding, it should work, but do you have any idea to debug / fix this issue ?
Don't use custom VerifyHashedPassword method.
From the source code of PasswordHasher below, we can see VerifyHashedPassword() can verify automatically with hashedPassword from DB and original input password.
using System;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
namespace Microsoft.AspNet.Identity
{
internal static class Crypto
{
private const int PBKDF2IterCount = 1000;
private const int PBKDF2SubkeyLength = 32;
private const int SaltSize = 16;
public static string HashPassword(string password)
{
if (password == null)
throw new ArgumentNullException("password");
byte[] salt;
byte[] bytes;
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, 16, 1000))
{
salt = rfc2898DeriveBytes.Salt;
bytes = rfc2898DeriveBytes.GetBytes(32);
}
byte[] inArray = new byte[49];
Buffer.BlockCopy((Array) salt, 0, (Array) inArray, 1, 16);
Buffer.BlockCopy((Array) bytes, 0, (Array) inArray, 17, 32);
return Convert.ToBase64String(inArray);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
if (hashedPassword == null)
return false;
if (password == null)
throw new ArgumentNullException("password");
byte[] numArray = Convert.FromBase64String(hashedPassword);
if (numArray.Length != 49 || (int) numArray[0] != 0)
return false;
byte[] salt = new byte[16];
Buffer.BlockCopy((Array) numArray, 1, (Array) salt, 0, 16);
byte[] a = new byte[32];
Buffer.BlockCopy((Array) numArray, 17, (Array) a, 0, 32);
byte[] bytes;
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, 1000))
bytes = rfc2898DeriveBytes.GetBytes(32);
return Crypto.ByteArraysEqual(a, bytes);
}
[MethodImpl(MethodImplOptions.NoOptimization)]
private static bool ByteArraysEqual(byte[] a, byte[] b)
{
if (object.ReferenceEquals((object) a, (object) b))
return true;
if (a == null || b == null || a.Length != b.Length)
return false;
bool flag = true;
for (int index = 0; index < a.Length; ++index)
flag &= (int) a[index] == (int) b[index];
return flag;
}
}
}
Test Codes
public static User user = new User();
[Route("/")]
public IActionResult Index()
{
//register a user
if(user != null) {
//test data
user.Id = Guid.NewGuid();
user.UserName = "test";
user.Email = "test#x.com";
user.Password = "password";
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher<IdentityUser>();
IdentityUser identityUser = new IdentityUser(user.Id.ToString());
user.PasswordHash = hasher.HashPassword(identityUser, user.Password);
}
//... save user to DB
return View();
}
Login controller
[HttpPost]
public IActionResult Login(LoginViewModel login)
{
if (ModelState.IsValid)
{
//... Here are codes get Id by email from DB
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher<IdentityUser>();
IdentityUser identityUser = new IdentityUser(user.Id.ToString());
if (PasswordVerificationResult.Failed == hasher.VerifyHashedPassword(identityUser,user.PasswordHash, login.Password))
ModelState.AddModelError("Password", "password is wrong");
}
else
ModelState.AddModelError("Email", "email or password invalid");
return PartialView("_LoginModalPartial", login);
}
Test of result
use
private readonly RandomNumberGenerator _rng;
public virtual string HashPassword(TUser user, string password)
{
if (_compatibilityMode == PasswordHasherCompatibilityMode.IdentityV2)
{
return Convert.ToBase64String(HashPasswordV2(password, _rng));
}
else
{
return Convert.ToBase64String(HashPasswordV3(password, _rng));
}
}
Reference: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.passwordhasher-1.hashpassword?view=aspnetcore-3.1
https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Extensions.Core/src/PasswordHasher.cs#L96
Read more: https://andrewlock.net/exploring-the-asp-net-core-identity-passwordhasher/#hashing-new-passwords

Swashbuckle Swagger - Pulling information from Attributes and putting it into the Schema definition

I am trying to have pull the DisplayAttribute and the DescriptionAttribute from parts of the Swagger Model. For example I may have a Body Parameter which has properties with attributes, which I would also want to be generated in the swagger.json and visible in SwaggerUI.
So far I think the approach that should work would be using a custom filter with swashbuckle. I got a proof of concept using the IParameterFilter which displays the description attribute, not sure if another filter would be better.
Issues:
Finding the key for the schemaRegistry fails for some types, like list.
Need to get the key for the parameter to be generated the same as swagger.
Might need recursion to loop through child properties that contain complex objects.
public class SwaggerParameterFilter : IParameterFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
public SwaggerParameterFilter(SchemaRegistrySettings settings = null)
{
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
try
{
if (context.ApiParameterDescription?.ModelMetadata?.Properties == null) return;
if (parameter is BodyParameter bodyParameter)
{
string idFor = _schemaIdManager.IdFor(context.ApiParameterDescription.Type);
var schemaRegistry = (SchemaRegistry)context.SchemaRegistry;
//not perfect, crashes with some cases
var schema = schemaRegistry.Definitions[idFor];
//bodyParameter.Schema, this doesn't seem right, no properties
foreach (var modelMetadata in context.ApiParameterDescription.ModelMetadata.Properties)
{
if (modelMetadata is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name))
{
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute)x);
var descriptionAttribute = (DescriptionAttribute)attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
}
}
}
}
}
catch (Exception e)
{
//eat because above is broken
}
}
}
Edit add looping.
public class SwaggerParameterFilter : IParameterFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
public SwaggerParameterFilter(SchemaRegistrySettings settings = null)
{
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
try
{
if (context.ApiParameterDescription?.ModelMetadata?.Properties == null) return;
//Only BodyParameters are complex and stored in the schema
if (parameter is BodyParameter bodyParameter)
{
var idFor = _schemaIdManager.IdFor(context.ApiParameterDescription.Type);
//not perfect, crashes with some cases
var schema = context.SchemaRegistry.Definitions[idFor];
UpdateSchema(schema, (SchemaRegistry) context.SchemaRegistry, context.ApiParameterDescription.ModelMetadata);
}
}
catch (Exception e)
{
//eat because above is broken
}
}
private void UpdateSchema(Schema schema, SchemaRegistry schemaRegistry, ModelMetadata modelMetadata)
{
if (schema.Ref != null)
{
var schemaReference = schema.Ref.Replace("#/definitions/", "");
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
return;
}
if (schema.Properties == null) return;
foreach (var properties in modelMetadata.Properties)
{
if (properties is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name) == false) return;
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute) x).ToList();
var descriptionAttribute =
(DescriptionAttribute) attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
var displayAttribute = (DisplayAttribute) attributes.FirstOrDefault(x => x is DisplayAttribute);
if (displayAttribute != null)
subSchema.Title = displayAttribute.Name;
if (modelMetadata.ModelType.IsPrimitive) return;
UpdateSchema(subSchema, schemaRegistry, defaultModelMetadata);
}
}
}
}
Operation Filter
public class SwaggerOperationFilter : IOperationFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
private IModelMetadataProvider _metadataProvider;
public SwaggerOperationFilter(IModelMetadataProvider metadataProvider, SchemaRegistrySettings settings = null)
{
this._metadataProvider = metadataProvider;
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(Operation operation, OperationFilterContext context)
{
try
{
foreach (var paramDescription in context.ApiDescription.ParameterDescriptions)
{
if (paramDescription?.ModelMetadata?.Properties == null)
{
continue;
}
if (paramDescription.ModelMetadata.ModelType.IsPrimitive)
{
continue;
}
if (paramDescription.ModelMetadata.ModelType == typeof(string))
{
continue;
}
var idFor = _schemaIdManager.IdFor(paramDescription.Type);
var schema = context.SchemaRegistry.Definitions[idFor];
UpdateSchema(schema, (SchemaRegistry)context.SchemaRegistry, paramDescription.ModelMetadata);
}
}
catch (Exception e)
{
//eat because above is broken
}
}
private void UpdateSchema(Schema schema, SchemaRegistry schemaRegistry, ModelMetadata modelMetadata)
{
if (schema.Ref != null)
{
var schemaReference = schema.Ref.Replace("#/definitions/", "");
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
return;
}
if (schema.Type == "array")
{
if (schema.Items.Ref != null)
{
var schemaReference = schema.Items.Ref.Replace("#/definitions/", "");
var modelTypeGenericTypeArgument = modelMetadata.ModelType.GenericTypeArguments[0];
modelMetadata = _metadataProvider.GetMetadataForType(modelTypeGenericTypeArgument);
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
}
return;
}
if (schema.Properties == null) return;
foreach (var properties in modelMetadata.Properties)
{
if (properties is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name) == false) return;
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute)x).ToList();
var descriptionAttribute =
(DescriptionAttribute)attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
var displayAttribute = (DisplayAttribute)attributes.FirstOrDefault(x => x is DisplayAttribute);
if (displayAttribute != null)
subSchema.Title = displayAttribute.Name;
if (defaultModelMetadata.ModelType.IsPrimitive) return;
UpdateSchema(subSchema, schemaRegistry, defaultModelMetadata);
}
}
}
}
So after some troubleshooting this seems to work for me but may need modification for other cases.
public class SwashbuckleAttributeReaderDocumentFilter : IDocumentFilter
{
private readonly SchemaIdManager _schemaIdManager;
private readonly IModelMetadataProvider _metadataProvider;
private List<string> _updatedSchemeList;
public SwashbuckleAttributeReaderDocumentFilter(IModelMetadataProvider metadataProvider, SchemaRegistrySettings settings = null)
{
_metadataProvider = metadataProvider;
var registrySettings = settings ?? new SchemaRegistrySettings();
_schemaIdManager = new SchemaIdManager(registrySettings.SchemaIdSelector);
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
_updatedSchemeList = new List<string>();
foreach (var apiDescription in context.ApiDescriptions)
{
foreach (var responseTypes in apiDescription.SupportedResponseTypes)
{
ProcessModelMetadata(context, responseTypes.ModelMetadata);
}
foreach (var paramDescription in apiDescription.ParameterDescriptions)
{
ProcessModelMetadata(context, paramDescription.ModelMetadata);
}
}
}
private void ProcessModelMetadata(DocumentFilterContext context, ModelMetadata currentModelMetadata)
{
if (currentModelMetadata?.Properties == null)
{
return;
}
if (currentModelMetadata.ModelType.IsValueType)
{
return;
}
if (currentModelMetadata.ModelType == typeof(string))
{
return;
}
if (currentModelMetadata.ModelType.IsGenericType)
{
foreach (var modelType in currentModelMetadata.ModelType.GenericTypeArguments)
{
var modelMetadata = _metadataProvider.GetMetadataForType(modelType);
UpdateSchema(context.SchemaRegistry, modelMetadata);
}
}
else if (currentModelMetadata.IsCollectionType)
{
var modelType = currentModelMetadata.ModelType.GetElementType();
var modelMetadata = _metadataProvider.GetMetadataForType(modelType);
UpdateSchema(context.SchemaRegistry, modelMetadata);
}
else
{
UpdateSchema(context.SchemaRegistry, currentModelMetadata);
}
}
public static void SetSchema(Schema schema, ModelMetadata modelMetadata)
{
if (!(modelMetadata is DefaultModelMetadata metadata)) return;
var attributes = GetAtributes(metadata);
SetDescription(attributes, schema);
SetTitle(attributes, schema);
}
private static List<Attribute> GetAtributes(DefaultModelMetadata modelMetadata)
{
return modelMetadata.Attributes.Attributes.Select(x => (Attribute)x).ToList();
}
private static void SetTitle(List<Attribute> attributes, Schema schema)
{
//LastOrDefault because we want the attribute from the dervived class.
var displayAttribute = (DisplayNameAttribute)attributes.LastOrDefault(x => x is DisplayNameAttribute);
if (displayAttribute != null)
schema.Title = displayAttribute.DisplayName;
}
private static void SetDescription(List<Attribute> attributes, Schema schema)
{
//LastOrDefault because we want the attribute from the dervived class. not sure if this works.
var descriptionAttribute = (DescriptionAttribute)attributes.LastOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
schema.Description = descriptionAttribute.Description;
}
private void UpdateSchema(ISchemaRegistry schemaRegistry, ModelMetadata modelMetadata, Schema schema = null)
{
if (modelMetadata.ModelType.IsValueType) return;
if (modelMetadata.ModelType == typeof(string)) return;
var idFor = _schemaIdManager.IdFor(modelMetadata.ModelType);
if (_updatedSchemeList.Contains(idFor))
return;
if (schema == null || schema.Ref != null)
{
if (schemaRegistry.Definitions.ContainsKey(idFor) == false) return;
schema = schemaRegistry.Definitions[idFor];
}
_updatedSchemeList.Add(idFor);
SetSchema(schema, modelMetadata);
if (schema.Type == "array")//Array Schema
{
var metaData = _metadataProvider.GetMetadataForType(modelMetadata.ModelType.GenericTypeArguments[0]);
UpdateSchema(schemaRegistry, metaData);
}
else//object schema
{
if (schema.Properties == null)
{
return;
}
foreach (var properties in modelMetadata.Properties)
{
if (!(properties is DefaultModelMetadata defaultModelMetadata))
{
continue;
}
var name = ToLowerCamelCase(defaultModelMetadata.Name);
if (schema.Properties.ContainsKey(name) == false)
{
//when this doesn't match the json object naming.
return;
}
var subSchema = schema.Properties[name];
SetSchema(subSchema, defaultModelMetadata);
UpdateSchema(schemaRegistry, defaultModelMetadata, subSchema);
}
}
}
private static string ToLowerCamelCase(string inputString)
{
if (inputString == null) return null;
if (inputString == string.Empty) return string.Empty;
if (char.IsLower(inputString[0])) return inputString;
return inputString.Substring(0, 1).ToLower() + inputString.Substring(1);
}
}

ASP.net MVC 4 site gets slow on first request to database

I have an ASP.net MVC 4 site and it gets slow on the first request. I tried breakpoint while running the application. During the login process it almost stays for a minute at my first database query:
var InstnCode = form["code"].ToString();
var ComAccount = Context.Companies.Where(x => x.CompanyCode == InstnCode);
After that everything runs smoothly.
Why is it so how can I rectify this process. Due to this problem sometimes I get a Server Timeout error.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(UserProfile model, string returnUrl, FormCollection form)
{
var InstnCode = form["code"].ToString();
var ComAccount = Context.Companies.Where(x => x.CompanyCode == InstnCode);
if (ComAccount.Any())
{
var modelvalue =
(from d in Context.UserProfiles
where d.UserName == model.UserName && d.Password == model.Password && d.Company.CompanyCode == InstnCode
select d).FirstOrDefault();
if (modelvalue != null)
{
string code = null;
Session["UName"] = modelvalue.UserName;
Session["Theme"] = modelvalue.Theme;
Session["InstnName"] = modelvalue.Company.CompanyName;
Session["Role"] = modelvalue.Role.RoleName;
Session["StartUp"] = modelvalue.StartUp;
var permission =
Context.AccountPermissions.Where(x => x.RoleId == modelvalue.RoleId)
.AsQueryable()
.FirstOrDefault();
if (permission != null)
{
SetSessions(permission, "yes");
}
else
{
SetSessions(permission, "no");
}
if (modelvalue.CompanyId != 0 && modelvalue.StaffId == null && modelvalue.StudentProfileId == null)
{
Session["ComID"] = modelvalue.CompanyId;
code = modelvalue.Company.CompanyCode;
}
else if (modelvalue.CompanyId != 0 && modelvalue.StudentProfileId != null)
{
var student =
(from d in Context.StudentProfiles
where d.StudentProfileId == modelvalue.StudentProfileId
select d).FirstOrDefault();
code = student.Company.CompanyCode;
Session["ComID"] = student.CompanyId;
}
else if (modelvalue.CompanyId != 0 && modelvalue.StaffId != null)
{
var staff =
(from d in Context.Staff where d.StaffId == modelvalue.StaffId select d).FirstOrDefault();
code = staff.Company.CompanyCode;
Session["ComID"] = staff.CompanyId;
Session["StaffID"] = staff.StaffId;
}
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect");
return View(model);
}
}
ModelState.AddModelError("", "The institution code provided is incorrect");
return View(model);
}
This is my login function. I'm using
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { enctype = "multipart/form-data" })) for my login form.
Any help will be greatly appreciated.
Thanks in advance