How To Get Value From DB While Editting Entry with Null value - asp.net-mvc

Error Message:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I want to get Image Url from database if fileupload has null value(not change).
I mean if i change smallImage and not change LargeImage,then it should get largeImage value from DB.
[HttpPost]
public ActionResult Edit(Blog blog, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (ModelState.IsValid)
{
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = db.Blogs.Find(blog.ID).SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = db.Blogs.Find(blog.ID).LargeImage;
}
blog.PostDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
db.Entry(blog).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(blog);
}
Thank you.

You are both loading a copy of the blog
db.Blogs.Find(blog.ID)
and attaching another with the same id to the context
db.Entry(blog).State = EntityState.Modified;
meaning you have 2 copies of the same blog in the context (not allowed).
I'd recommend the replacing the one posted back with a viewmodel instead, something like
public ActionResult Edit(BlogViewModel viewModel, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var blog = db.Blogs.Find(viewModel.ID);
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
blog.Title = viewModel.Title;
blog.Body = viewModel.Body; //etc
db.SaveChanges();
return RedirectToAction("Index");
}

Looks like issue here is that you load same blog twice.
Load it once instead, something like this:
Blog existingBlog = db.Blogs.Find(blog.ID);
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength +
"_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"),
smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = existingBlog.SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" +
largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"),
largeImage.ContentLength + "_" +
largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = existingBlog.LargeImage;
}

Related

Changing synchronous call to async await(Asynchronous ) MvC controller

I am new to C# Asp.net mvc asynchronous programming. I need to uplaod vidoe to my server but it video upload is locked when I uploading the video. I can not do another tasks in parallel. I have tried like this but it is not working.
public async Task<ActionResult> upload()
{
if (Request.Files.Count > 0)
{
int chunk = Request["chunk"] != null ?
int.Parse(Request["chunk"]) : 0;
string fileName = Request["name"] != null ? Request["name"] :
string.Empty;
string upath = "";
if (Request.Headers["UName"] != null)
upath = Request.Headers["UName"].ToString();
//if (CloudSettings.EnableCloudStorage && upath != "")
// _fileName = upath.Substring(0, 3) + "-" + _fileName; // void duplication in cloud storage
long AlbumID = 0;
if (Request.Headers["MediaID"] != null)
AlbumID = Convert.ToInt64(Request.Headers["MediaID"]);
string uploadPath = "";
// default path
if (upath == "")
uploadPath = UrlConfig.Published_Video_Path(); // direct upload to published area
else
uploadPath = UrlConfig.Published_Video_Path(upath); // source video path
FileStream fs;
using (fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
{
byte[] buffer = new byte[Request.Files[0].InputStream.Length];
await Request.Files[0].InputStream.ReadAsync(buffer, 0, buffer.Length);
await fs.WriteAsync(buffer, 0, buffer.Length);
}
string url = "";
string filetype = System.IO.Path.GetExtension(fileName);
string fileIndex = fileName.Replace(filetype, "");
string elementid = UtilityBLL.ReplaceSpaceWithHyphin(fileIndex);
//eturn fileName; // "Success";
return this.Content("{\"jsonrpc\" : \"2.0\", \"result\" : \"OK\", \"id\" : \"id\", \"fname\" : \"" + fileName + "\", \"url\" : \"" + url + "\", \"filetype\" : \"" + filetype + "\", \"filename\" : \"" + fileName + "\", \"fileIndex\" : \"" + fileIndex + "\", \"eleid\" : \"" + elementid + "\"}", "text/plain");
}
else
{
return this.Content("failed", "text/plain");
}
}

'sorry some error occurred' while integrating PayUMoney payment gateway in asp.net mvc

I'm trying to integrate PayUMoney payment gateway in my client site.
1) My account is already activated.
2) Merchant key & Salt key is right.
3) I have already added payu_paisa in service provider field.
when adding more than 700 amounts it gives the message: sorry some error occurred.
Here is the code:
public ActionResult PaymentWithPayuMoney()
{
var objOrderBal = new OrderBal();
var objOrderDetail = objOrderBal.GetOrderDetail(User.Identity.GetUserId());
//var userDetails = UserManager.FindById(User.Identity.GetUserId());
var userDetails = objOrderBal.GetOrder(User.Identity.GetUserId());
var ordersubTotal = 0.00m;
var shipping = 0;
foreach (var objOrder in objOrderDetail)
{
ordersubTotal = objOrder.TotalPrice * objOrder.Quantity + ordersubTotal;
shipping = Convert.ToInt32(shipping) + Convert.ToInt32(objOrder.ShippingCharge);
}
var orderTotal = Convert.ToString(Convert.ToDouble(shipping) + Convert.ToDouble(ordersubTotal), CultureInfo.InvariantCulture);
var key = ConfigurationManager.AppSettings["MERCHANT_KEY"];
var myremotepost = new RemotePost { Url = ConfigurationManager.AppSettings["PAYU_BASE_URL"] + "/_payment" };
myremotepost.Add("key", key);
myremotepost.Add("txnid", Generatetxnid());
myremotepost.Add("amount", orderTotal);
myremotepost.Add("productinfo", "productname");
myremotepost.Add("firstname", userDetails.Name);
myremotepost.Add("phone", userDetails.MobileNo);
myremotepost.Add("email", userDetails.Email);
if (Request.Url != null)
{
myremotepost.Add("surl", "" + Request.Url.Scheme + "://" + Request.Url.Authority + "/Order/Return");
myremotepost.Add("furl", "" + Request.Url.Scheme + "://" + Request.Url.Authority + "/Order/Return");
}
myremotepost.Add("service_provider", "payu_paisa");
string hashString = key + "|" + Generatetxnid() + "|" + orderTotal + "|productname|" + userDetails.Name + "|" + userDetails.Email + "|||||||||||" + ConfigurationManager.AppSettings["SALT"];
string hash = Generatehash512(hashString);
myremotepost.Add("hash", hash);
myremotepost.Post();
return View("SuccessView");
}
public class RemotePost
{
public readonly System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head>");
System.Web.HttpContext.Current.Response.Write($"</head><body onload=\"document.{FormName}.submit()\">");
System.Web.HttpContext.Current.Response.Write($"<form name=\"{FormName}\" method=\"{Method}\" action=\"{Url}\" >");
for (var i = 0; i < Inputs.Keys.Count; i++)
{
System.Web.HttpContext.Current.Response.Write($"<input name=\"{Inputs.Keys[i]}\" type=\"hidden\" value=\"{Inputs[Inputs.Keys[i]]}\">");
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
System.Web.HttpContext.Current.Response.End();
}
}
public string Generatehash512(string text)
{
var message = Encoding.UTF8.GetBytes(text);
var hashString = new SHA512Managed();
var hashValue = hashString.ComputeHash(message);
return hashValue.Aggregate("", (current, x) => current + $"{x:x2}");
}
public string Generatetxnid()
{
var rnd = new Random();
var strHash = Generatehash512(rnd.ToString() + DateTime.Now);
var txnid1 = strHash.Substring(0, 20);
return txnid1;
}
Please check the hash calculated by you is matching with the one generated at payu server.

through exception in mvc on send email

I want to send email from an excel file.
When It get wrong email address it stop sending.
I want it send all email and at last show me wrong email that isn't able to send.
This my code for read Excel file:
if (!string.IsNullOrWhiteSpace(excel))
{
var src = excel;
DataSet ds = new DataSet();
string fileExtension = System.IO.Path.GetExtension(Server.MapPath("~/") + src);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/") + src;
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/") + src;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
And this is code for send email:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string excelname = "";
if (lang == "1")
{
excelname = "<div style='text-align:right;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
else
{
excelname = "<div style='text-align:left;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
exceltotal = excelname + text + newslink + attach;
//sender
message = string.Format(body, img, exceltotal, title, prehead, senderemail);
MailMessage email = new MailMessage();
email.To.Add(ds.Tables[0].Rows[i][2].ToString());
email.From = new MailAddress(senderemail);
email.Subject = maintitle;
email.Body = message + makedelivey(ds.Tables[0].Rows[i][2].ToString(), maintitle);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.IsBodyHtml = true;
SmtpClient ssmtp = new SmtpClient();
ssmtp.Host = server;
ssmtp.Port = port;
ssmtp.UseDefaultCredentials = false;
ssmtp.Credentials = new System.Net.NetworkCredential(senderemail, senderpassword);
ssmtp.EnableSsl = false;
ssmtp.Send(email);
exceltotal = "";
message = "";
}
It read a text file and add some value from excel or database base on user selection.
I couldn't find line of code which sends email. But wherever you are sending the email inside the loop, make sure you enclose that code in try catch block. This ensures even if a mail send operation is failed, the error is handled and goes on with other mails. You can include your consolidate and formatting of failures issues in catch block.
var consolidateErrors = string.Empty;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Try
{
//Mail sending logic here
}
Catch(Exception ex)
{
consolidateErrors += YourErrorDetails;
}
}

Reading Windows event log using JNA provides me only part of the description available in Event Veiwer

This is my code Provide me details where am going wrong so that am
getting only the part of the description available
========================================================================
http://code.dblock.org/jna-reading-windows-event-log-entries-in-java
#SuppressWarnings("unused")
public void testReadEventLogEntries() throws CharacterCodingException {
final Charset charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
final CharsetEncoder encoder = charset.newEncoder();
final CharsetDecoder decoder = charset.newDecoder();
int i = 0;// loop contro variable
String type = null; // Type of the event
String user = null;
String str[] = { "System", "Application" };
while (i < 2) {
System.out.println("\n\n" + str[i]);
HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, str[i]);
IntByReference pnBytesRead = new IntByReference();
IntByReference pnMinNumberOfBytesNeeded = new IntByReference();
Memory buffer = new Memory(1024 * 64);
IntByReference pOldestRecord = new IntByReference();
int dwRecord = pOldestRecord.getValue();
int rc = 0;
while (true) { // Travesing the read log records
if (!Advapi32.INSTANCE.ReadEventLog(h,
WinNT.EVENTLOG_SEQUENTIAL_READ
| WinNT.EVENTLOG_FORWARDS_READ, 0, buffer,
(int) buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
rc = Kernel32.INSTANCE.GetLastError();
if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) {
buffer = new Memory(pnMinNumberOfBytesNeeded.getValue());
continue;
}
break;
}
int dwRead = pnBytesRead.getValue();
Pointer pevlr = buffer;
while (dwRead > 0) {
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
EventLogRecord event = new EventLogRecord(pevlr);
org.hyperic.sigar.win32.EventLogRecord sigar;
EventLog log = new EventLog();
if (record.EventType.intValue() == 1)
type = "Error";
else if (record.EventType.intValue() == 10)
type = "Failure Audit";
else if (record.EventType.intValue() == 8)
type = "Sucess Audit";
else if (record.EventType.intValue() == 4)
type = "Information";
else
type = "Warning";
ByteBuffer names = pevlr
.getByteBuffer(
record.size(),
(record.UserSidLength.intValue() != 0 ? record.UserSidOffset
.intValue() : record.StringOffset
.intValue())
- record.size());
names.position(0);
CharBuffer namesBuf = names.asCharBuffer();
String[] splits = namesBuf.toString().split("\0");
if (record.UserSidLength.intValue() != 0) {
ByteBuffer usersid = pevlr.getByteBuffer(
record.UserSidOffset.intValue(),
record.UserSidLength.intValue());
usersid.position(0);
CharBuffer sidBuf = usersid.asCharBuffer();
String[] sp = sidBuf.toString().split("\0");
// System.out.println(sp[0] + sp[1] + sp[2]);
/*
* dst.get user= new String(dst);
*/
} else {
user = "N/A";
}
System.out.println(type + "\t" + toDate(record) + "\t"
+ event.getSource() + "\t" + record.EventCategory
+ "\t" + record.EventID.shortValue() + "\t" + user
+ "\t" + splits[1]);
ByteBuffer strings = pevlr.getByteBuffer(
record.StringOffset.longValue(),
record.DataOffset.intValue()
- record.StringOffset.intValue());
CharBuffer stringsBuf = strings.asCharBuffer();
System.out.println("Desc: " + stringsBuf.toString());
dwRecord++;
dwRead -= record.Length.intValue();
pevlr = pevlr.share(record.Length.intValue());
}
}
i++;
}
}
// Method to convert the timestamp to formated date
public Date toDate(EVENTLOGRECORD record) {
Timestamp stamp = new Timestamp(record.TimeWritten.longValue() * 1000);
Date date = new Date(stamp.getTime());
return date;
}
}
Finally I figured out the solution....The description returned by the
above code is just the insertion strings needed to build the message.
Instead of using jna I used WMI which is simple to use and more handy
/**
* #param args
*/
public static void main(String[] args) throws COMException {
String computerName = ".";
String userName = "";
String password = "";
String namespace = "root/cimv2";
String Message = "";
String queryProcessor = "Select * from Win32_NTLogEvent where Logfile='System'or Logfile='Application'";
DispatchPtr dispatcher = null;
try {
ISWbemLocator locator = new ISWbemLocator(
"WbemScripting.SWbemLocator");
ISWbemServices wbemServices = locator.ConnectServer(computerName,
namespace, userName, password, "", "", 0, dispatcher);
ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery(
queryProcessor, "WQL", 0, null);
DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()];
IUnknown unknown = wbemObjectSet.get_NewEnum();
IEnumVariant enumVariant = (IEnumVariant) unknown
.queryInterface(IEnumVariant.class);
enumVariant.Next(wbemObjectSet.getCount(), results);
for (int i = 0; i < results.length; i++) {
ISWbemObject wbemObject = (ISWbemObject) results[i]
.queryInterface(ISWbemObject.class);
if (wbemObject.get("Message") != null) {
Message = (String) wbemObject.get("Message");
} else {
Message = "The description for Event ID ("
+ wbemObject.get("EventCode")
+ " ) in Source ( "
+ wbemObject.get("SourceName")
+ ") cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.";
}
System.out.println(wbemObject.get("Logfile") + "\t"
+ wbemObject.get("Type") + "\t"
+ toDate(wbemObject.get("TimeGenerated").toString())
+ "\t"
+ toTime(wbemObject.get("TimeGenerated").toString())
+ "\t" + wbemObject.get("EventCode") + "\t"
+ wbemObject.get("ComputerName") + "\t" + Message);
// System.out.println(wbemObject.GetObjectText_(0));
}
} catch (COMException e) {
e.printStackTrace();
}
}
public static String toDate(String time) throws COMException {
String date = time.substring(6, 8) + "-" + time.substring(4, 6) + "-"
+ time.substring(0, 4);
return date;
}
public static String toTime(String time) throws COMException {
String Generatedtime = time.substring(8, 10) + ":"
+ time.substring(10, 12) + ":" + time.substring(12, 14) + ":"
+ time.substring(16, 21) + "-" + "GMT" + time.substring(21, 25);
return Generatedtime;
}

MissingMethodException on domain class save in Grails 1.3.7

I'm having a problem calling the save method on a domain object. The error is:
groovy.lang.MissingMethodException: No signature of method: static my.awesome.Class.FeedHit.save() is applicable for argument types: () values: []
Possible solutions: save(), save(java.lang.Boolean), save(java.util.Map), wait(), any(), wait(long)
I'm going through an array of FeedHits, updating a flag, and then calling the save method:
void updateFeedHits(Set<FeedHit> list, FeedHitStatus status) {
for (FeedHit feedHit: list) {
feedHit.status = status
try {
feedHit.save()
} catch (Exception ex) {
log.info("unknown exception during update FeedHit", ex)
}
}
}
I've seen other StackOVerflow users have the same problem, but only during tests. This code is in normal release code.
Any help would be appreciated.
EDIT:
Here is the FeedHit object, slightly edited.
class FeedHit {
Feed feed
String title
String body
String url
FeedHitStatus status
String sourceId
String hash
Date publishedDate
Date dateCreated = new Date()
Integer pos = -1
static constraints = {
alert(nullable: true)
title(nullable: true)
body(nullable: true)
url(nullable: true)
status(nullable: true)
sourceId(nullable: true)
hash(nullable: true)
pos(nullable: true)
publishedDate(nullable: true)
dateCreated(nullable: true)
}
static mapping = {
table('alert_hit')
autoTimestamp false
version(false)
alert(column: 'alert_id')
body(sqlType: 'text')
url(sqlType: 'text')
sourceId(column: 'sourceId')
publishedDate(column: 'publishedDate')
dateCreated(column: 'dateCreated')
}
/**
* Generates a hash from title, body and url.
*/
public AlertHit generateHash() {
StringBuffer sb = new StringBuffer();
if (this.title != null) {
sb.append(this.title);
}
if (this.body != null) {
sb.append(this.body);
}
if (this.url != null) {
sb.append(this.url);
}
if (this.publishedDate != null) {
sb.append(this.publishedDate.getTime());
}
if (sb.length() > 0) {
hash = Md5Hash.hash(sb.toString());
}
this
}
#Override
public String toString() {
return "AlertHit{" +
"id=" + id +
", alert=" + alert +
", title='" + title + '\'' +
", body='" + body + '\'' +
", url='" + url + '\'' +
", status=" + status +
", sourceId='" + sourceId + '\'' +
", hash='" + hash + '\'' +
", publishedDate=" + publishedDate +
", dateCreated=" + dateCreated +
", pos=" + pos +
", version=" + version +
'}';
}
}
You need to annotate GORM functions, if you want to use domain class outside grails. See http://www.rimerosolutions.com/using-gorm-standalone-outside-grails/
I would recommend you to use another way than native threads. Try: Quartz-Plugin

Resources