Error: Only primitive types or enumeration types are supported in this context - asp.net-mvc-4

[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.

Related

Convert EntityFramework to Raw SQL Queries in MVC

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 }
};

How do I Reply a Comment So it can capture the comment

Please Guys, I have a forum and I want users to be able to reply comments so that the reply would appear with the comment.
This is what I have:
public ActionResult Quote(int? id)
{
var user = User.Identity.Name;
var userId = WebSecurity.CurrentUserId;
//var userId = db.UserProfiles.FirstOrDefault(x => x.UserName == user).UserId;
if (User.Identity.Name == null)
{
return RedirectToAction("Login", "Account");
}
if (id == null)
{
return RedirectToAction("topics", "forum");
}
//var p = db.Posts.FirstOrDefault(x => x.PostId == id.Value);
var post = db.Posts.Find(id.Value);
var comment = db.UserComments.FirstOrDefault();
var usercomment = db.UserComments.Find(comment.UserCommentId);
if (usercomment == null)
{
return RedirectToAction("topics");
}
return View(new Quote { UserId = WebSecurity.CurrentUserId, PostId = id.Value, UserCommentId = usercomment.UserCommentId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Quote(Quote quote, int id = 0)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
System.Random randomInteger = new System.Random();
int genNumber = randomInteger.Next(1000000);
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0 && file.ContentType.ToUpper().Contains("JPEG") || file.ContentType.ToUpper().Contains("PNG") || file.ContentType.ToUpper().Contains("JPG"))
{
WebImage img = new WebImage(file.InputStream);
if (img.Width > 500)
{
img.Resize(width: 500, height: 400, preserveAspectRatio: true, preventEnlarge: true);
}
if (img.Height > 700)
{
img.Resize(width: 500, height: 400, preserveAspectRatio: true, preventEnlarge: true);
}
string fileName = Path.Combine(Server.MapPath("~/Uploads/"), Path.GetFileName(genNumber + file.FileName));
img.Save(fileName);
if (fileName == null)
{
ViewBag.image = "True";
}
quote.QuoteFile = fileName;
}
}
var user = WebSecurity.CurrentUserId;
//var userId = db.UserProfiles.FirstOrDefault(a => a.UserId == user);
db.Quotes.Add(quote);
quote.QuotedBy = User.Identity.Name;
var post = db.Quotes.Include(f => f.Posts).Where(x=>x.UserCommentId == quote.UserCommentId).OrderByDescending(s => s.QuoteId);
quote.DateQuoted = DateTime.Now;
db.SaveChanges();
return RedirectToAction("topics", "forum", new { id = quote.PostId});
}
return View(quote);
}
public ActionResult _Quote(int id = 0)
{
//var comment = db.UserComments.FirstOrDefault(x => x.PostId == id);
var user = WebSecurity.CurrentUserId;
var comments = db.Quotes.Where(x => x.PostId == id).ToList();
//var quotes = db.UserComments.Where(x => x.PostId == id).ToList();
var p = new UserComment();
p.DateUserCommented = DateTime.Now;
DateTime dt = Convert.ToDateTime(p.DateUserCommented);
string strDate = dt.ToString("dd MMMM yyyy - hh:mm tt");
ViewBag.p = strDate;
ViewBag.data = comments;
return PartialView(comments);
}

Having error in updating my record in database my method as follows

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";
}
}
}

Convert cookie string to a Cookie object in C# or Java

I need to automatically access a website that requires authentication. I found cookie string of this website's http host (using fiddler). Is there a way to convert this string to a cookie object and pass it to a Webclient to pass the authentication?
Convert the Sting to a cookie object. For this you need to parse the String to get name, value, path, domain, etc.
You have to do something like this -
String[] cArray = cookieValueIs.split(";");
for (String s : cArray) {
s = s.trim();
int i1 = s.indexOf('=');
if (i1 != -1) {
String k = s.substring(0, i1).trim();
String v = s.substring(i1 + 1).trim();
if (k.equalsIgnoreCase(VERSION)) {
version = v;
} else if (k.equalsIgnoreCase(COMMENT)) {
comment = v;
} else if (k.equalsIgnoreCase(DOMAIN)) {
domain = v;
} else if (k.equalsIgnoreCase(PATH)) {
path = v;
} else if (k.equalsIgnoreCase(MAX_AGE)) {
maxAge = v;
} else if(k.equalsIgnoreCase(EXPIRES)){
continue;
}
else {
key = k;
value = v;
}
} else {
if (s.equalsIgnoreCase(SECURE)) {
secure = true;
} else if (s.equalsIgnoreCase(HTTPONLY)) {
httpOnly = true;
}
}
Once you are done with this create a cookie object-
Cookie cookie = new Cookie(key,value);
if(comment != null){
cookie.setComment(comment);
}
if(domain != null){
cookie.setDomain(domain);
}
if(path != null){
cookie.setPath(path);
}
if(version != null){
cookie.setVersion(Integer.parseInt(version));
}
if(secure){
cookie.setSecure(true);
Now your string is converted to the Cookie object --> cookie
This worked for me in c#.
public static Cookie ToCookie(this string #this)
{
String[] array = #this.Split(';');
var cookie = new Cookie();
foreach (var ss in array)
{
string key;
object value;
var s = ss.Trim();
int indexOf = s.IndexOf('=');
if (indexOf != -1) {
key = s.Substring(0, indexOf).Trim();
value = s.Substring(indexOf + 1).Trim();
} else
{
key = s.ToTitleCase();
value = true;
}
var prop = cookie.GetType().GetProperty(key.ToTitleCase());
if (prop != null)
{
var converted = Convert.ChangeType(value, prop.PropertyType);
prop.SetValue(cookie, converted, null);
}else
{
cookie.Name = key;
cookie.Value = value.ToString();
}
}
return cookie;
}

Nhibernate Throws Found shared references to a collection

I have read thru a number of other questions similar to this one - but being new to Nhibernate, none of them seem to answer my question of why is Inhibernate throwing a "Found shared references to a collection: Order.ShippingAddress.Items" to the following code:
VendorOrderNotificationAcknowledgement ICheckoutVendorService.SendOrderNotification(VendorOrderNotification request)
{
OrderRepository repo = new OrderRepository();
var order =(AbstractOrder) repo.FindByCartId(request.OrderNotification.CartOrderId);
ShippingAddress billingAddress = order.ShippingAddresses[0];
var itemsFromDb = billingAddress.Items;
order.ClearAllShippingAddresses();
wcfFactory.UpdateOrder(order); //NO ERROR THROWN HERE!
ShippingAddress shippingAddress = orderHelper.CreateShippingAddress(request.ShippingDetails);
shippingAddress.Items = itemsFromDb;
order.AddShippingAddress(shippingAddress);
order.SourceCode = _sourceCode;
order.TaxAmount = 0;
order.GiftCertificateAmount = 0;
order.Status = StatusCode.Approved;
order.CreatedAt = request.OrderNotification.OrderTime.Year >2010
? request.OrderNotification.OrderTime
: DateTime.Now;
order.PurchasedDate=
request.OrderNotification.OrderTime.Year>2010
? request.OrderNotification.OrderTime
: DateTime.Now;
order.UpdatedAt = DateTime.Now;
if (request.OrderNotification.OrderCharges != null)
{
order.ShippingAmount = request.OrderNotification.OrderCharges.Shipping;
order.TaxAmount = request.OrderNotification.OrderCharges.DutyAndTaxes;
}
else
{
order.ShippingAmount = 0;
order.TaxAmount = 0;
}
order.UseGiftWrap = false;
order.SourceCode = _sourceCode;
UpdateEshopWorldOrder(order); // THROWS FOUND SHARED REFERENCES TO A COLLECTION: ORDER.SHIPPINGADDRESS.ITEMS
var orderDto = orderHelper.CreateOrderDto(billingAddress, orderHelper, order);
var dtoShippingAddresses = orderHelper.CreateDtoShippingAddresses(order);
orderDto.ShippingAddresses = dtoShippingAddresses;
ShippingMethodDto shippingMethodDto = 0;
var mine = wcfFactory.SendOrder(orderDto);
//More Code below here ...
}
public OrderDto CreateOrderDto(ShippingAddress billingAddress, OrderHelper orderHelper, AbstractOrder order)
{
OrderDto orderDto = new OrderDto();
orderDto.AlternateOrderId = order.Id.ToString();
orderDto.ConfirmationNumber = order.ConfirmationNumber;
orderDto.Coupons = new string[0];
orderDto.DiscountAmount = order.DiscountAmount;
orderDto.GiftCardAmount = order.GiftCertificateAmount;
orderDto.PurchaseDate = order.PurchasedDate;
orderDto.ShippingAmount = order.ShippingAmount;
orderDto.SourceCode = order.SourceCode;
orderDto.TaxAmount = order.TaxAmount;
orderDto.UseGiftWrap = order.UseGiftWrap;
var customerDto = orderHelper.CreateCustomerDto(billingAddress);
orderDto.SoldTo = customerDto;
return orderDto;
}
public void UpdateEshopWorldOrder(AbstractOrder order)
{
try
{
//Session.Update(order);
// transaction.Commit();
Session.Flush();
}
catch (Exception ex)
{
_logger.Debug("order saved failed with an error of " + ex.Message);
_logger.Error(ex);
throw;
}
}
Any insights are appreciated....
thnx
I think the problem is, that your itemsFromDB collection object is referenced by shippingAddress and also by billingAddress.
Both entities need their own collection-objects. Both collections however may contain references to the same address-objects.
So I assume replacing shippingAddress.Items = itemsFromDb; with something like
shippingAddress.Items.AddRange(itemsFromDb)
or
shippingAddress.Items = new List<ShippingAddress>(itemsFromDb) should do the trick