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
Related
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?
I am trying to make a crud calendar in my .net, my question is, How do make the below entity framework codes to SQL queries?
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Thanks guys
You can run raw query in entity framework with dc.Database.ExecuteSqlCommand() command like below:
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
dc.Database.ExecuteSqlCommand(&#"
UPDATE Events
SET Subject = {e.Subject},
Start = {e.Start},
End = {End},
Description = {Description},
IsFullDay = {IsFullDay},
ThemeColor = {ThemeColor},
WHERE EventID = {e.EventID}
IF ##ROWCOUNT = 0
INSERT INTO Events (EventID, Subject, Start, End, Description, IsFullDay, ThemeColor)
VALUES ({e.EventID}, {e.Subject}, ...)
");
status = true;
}
return new JsonResult { Data = new { status = status }
};
What I have done wrong in this code ? (I am using MVC4 and EF)
As an example: Please clear this am fresher to use MVC4
EditResponse response = new EditResponse();
try
{
using (WeMatchContext db = new WeMatchContext())
{
B_MEMBER_REGISTER update = new B_MEMBER_REGISTER();
var output = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(output != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
You have to attach updated data with the db entity. please try this,
using (WeMatchContext db = new WeMatchContext())
{
var update = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(update != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
//below line of code is very important.
db.B_MEMBER_REGISTER.Attach(update);
db.Entry(update).State = EntityState.Modified;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
}
}
[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.
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;
}