ExecuteSqlRawAsync returns -1 in Entity Framework 3.1 - asp.net-mvc

In my ASP.NET Core 3.1 web application, I am mostly using stored procedures. When using ExecuteSqlRawAsync in Entity Framework Core it always returns -1. Below given is my generalized method to execute stored procedures.
public async Task<int> ExecuteSqlNonQuery(string StoredProcName, params object[] parameters)
{
int iTotalRecordsAffected = 0;
List<TEntity> listOfObject = null;
try
{
if (!string.IsNullOrEmpty(StoredProcName))
{
StringBuilder sbStoredProc = new StringBuilder();
sbStoredProc.Append("Exec ");
sbStoredProc.Append(StoredProcName);
if (parameters != null)
{
foreach (SqlParameter item in parameters)
{
if (listOfObject == null)
{
sbStoredProc.Append(" #");
listOfObject = new List<TEntity>();
}
else
{
sbStoredProc.Append(", #");
}
sbStoredProc.Append(item.ParameterName.Replace("#", ""));
if (item.Direction == System.Data.ParameterDirection.Output)
{
sbStoredProc.Append(" OUT");
}
}
}
iTotalRecordsAffected = await _DBContext.Database.ExecuteSqlRawAsync(sbStoredProc.ToString(), parameters);
}
}
catch (Exception ex)
{
}
finally
{
if (_DBContext.Database.GetDbConnection().State == System.Data.ConnectionState.Open)
{
_DBContext.Database.GetDbConnection().Close();
}
}
return iTotalRecordsAffected;
}
Here is my controller method that calls a SP to update data.
public async Task<int> UpdateCustomerData(EditCustomerDetail editCustomerDetail)
{
int iTotalRecordsEffected = 0;
try
{
List<SqlParameter> sqlParamList = new List<SqlParameter>()
{
new SqlParameter("#CustomerID",editCustomerDetail.CorporateID),
new SqlParameter("#CustomerName",editCustomerDetail.CorporateName),
new SqlParameter("#CustomerAddress",editCustomerDetail.Address),
new SqlParameter("#City",editCustomerDetail.City),
new SqlParameter("#CountryID",editCustomerDetail.CountryID),
new SqlParameter("#StateID",editCustomerDetail.StateID),
new SqlParameter("#Description",editCustomerDetail.Description),
new SqlParameter("#Phone",editCustomerDetail.Phone),
new SqlParameter("#Fax",editCustomerDetail.Fax),
new SqlParameter("#ModifiedBy",editCustomerDetail.UserID)
};
iTotalRecordsEffected = await _unitOfWork.GetRepository<EditCustomerDetail>().ExecuteSqlNonQuery("UpdateCustomerDetails", sqlParamList.ToArray());
}
catch (Exception ex)
{
}
finally
{
}
return iTotalRecordsEffected;
}
Any suggestion what I am doing wrong?

Related

.NET CORE 3.1, MVC Async method not updating DB

AI am just moving to ASYNC methods and trying to get my data to update. I can select just find so I know the repository is working.
Action
[HttpPost]
public async Task<IActionResult> EditTeam(EmployeeVm empVm)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", _errorUpdateMsg);
}
else
{
if (await _teamRepository.UpdateEmployee(empVm.Employee))
{
return RedirectToAction("Index");
}
ModelState.AddModelError("", _errorUpdateMsg);
}
return View(empVm);
}
My Constructor in repo
public TeamRepository(EnvisionDbContext envisionDbContext)
{
_envisonDbContext = envisionDbContext;
}
Here is my Update that does not save
public async Task<bool> UpdateEmployee(Employee employee)
{
var result = await _envisonDbContext.Employees.FirstOrDefaultAsync<Employee>(e => e.Id == employee.Id);
if (result != null)
{
result.FirstName = employee.FirstName;
result.LastName = employee.LastName;
result.Phone = employee.Phone;
result.IsActive = employee.IsActive;
await _envisonDbContext.SaveChangesAsync();
return true;
}
return false;
}
Thanks in advance for the help.
UPDATED: If I add this, it works. Is this because the two await calls are disconnected?
result.IsActive = employee.IsActive;
_envisonDbContext.Entry(result).State = EntityState.Modified;
Seems like you forgot update-method before savingchanges
if (result != null)
{
result.FirstName = employee.FirstName;
result.LastName = employee.LastName;
result.Phone = employee.Phone;
result.IsActive = employee.IsActive;
_envisionDbContext.Update(result); //paste it before you save changes
await _envisonDbContext.SaveChangesAsync();
return true;
}

Vaadin upload with PipedInputStream & PipedOutputStream example

I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.

How to edit/update records using "TryUpdateModel" with "User.Identity.GetUserId()" in mvc.net?

This following code works fine
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id, string[] selectedCourses)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var instructorToUpdate = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.ID == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "",
new string[] { "LastName", "FirstMidName", "HireDate", "OfficeAssignment" }))
{
try
{
if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
{
instructorToUpdate.OfficeAssignment = null;
}
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Courses = new List<Course>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Courses.Select(c => c.CourseID));
foreach (var course in db.Courses)
{
if (selectedCoursesHS.Contains(course.CourseID.ToString()))
{
if (!instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Remove(course);
}
}
}
}
But I don't want to get id from view and I am using string id = User.Identity.GetUserId(); but only my checkboxes are getting updated and not the other database.
I tried db.Entry(abc).State = EntityState.Modified; but it gives an error. It says, context is already in use. How to update both tables?

I copy/pasted code from ArcGIS .NET ashx proxy into my Controller method, now debugging is jumping all over the place (multi-threaded, apparently)

I have a controller that takes in JSON data via HTTP POST. Inside this controller is a call to a method that I copied/pasted from ArcGIS's .NET implementation of the proxy that's needed to connect to ArcGIS's servers. For the sake of the problem I'm having, that part was irrelavent.
Before copying/pasting, the execution flow was line by line. But now, after copying and pasting (and subsequently adding the call to the method), my debugging execution flow is jumping all over the place (because of different threads going on at the same time). I don't know why this is happening- I didn't see anything that had to do with threads in the code I copied and pasted. Could you tell me why this is happening just because of code that I copied/pasted that appears to not have anything to do with multithreading?
Here's my controller code that makes the call to the method I copied/pasted:
[HttpPost]
public void PostPicture(HttpRequestMessage msg)
{
HttpContext context = HttpContext.Current;
ProcessRequest(context);
...
Here's the code I copied and pasted from ArcGIS (I'm sorry, it's very long):
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(context.Request.Url);
req.Method = context.Request.HttpMethod;
req.ServicePoint.Expect100Continue = false;
// Set body of request for POST requests
if (context.Request.InputStream.Length > 0)
{
byte[] bytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(bytes, 0, (int)context.Request.InputStream.Length);
req.ContentLength = bytes.Length;
string ctype = context.Request.ContentType;
if (String.IsNullOrEmpty(ctype))
{
req.ContentType = "application/x-www-form-urlencoded";
}
else
{
req.ContentType = ctype;
}
using (Stream outputStream = req.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
}
// Send the request to the server
System.Net.WebResponse serverResponse = null;
try
{
serverResponse = req.GetResponse();
}
catch (System.Net.WebException webExc)
{
response.StatusCode = 500;
response.StatusDescription = webExc.Status.ToString();
response.Write(webExc.Response);
response.End();
return;
}
// Set up the response to the client
if (serverResponse != null)
{
response.ContentType = serverResponse.ContentType;
using (Stream byteStream = serverResponse.GetResponseStream())
{
// Text response
if (serverResponse.ContentType.Contains("text") ||
serverResponse.ContentType.Contains("json"))
{
using (StreamReader sr = new StreamReader(byteStream))
{
string strResponse = sr.ReadToEnd();
response.Write(strResponse);
}
}
else
{
// Binary response (image, lyr file, other binary file)
BinaryReader br = new BinaryReader(byteStream);
byte[] outb = br.ReadBytes((int)serverResponse.ContentLength);
br.Close();
// Tell client not to cache the image since it's dynamic
response.CacheControl = "no-cache";
// Send the image to the client
// (Note: if large images/files sent, could modify this to send in chunks)
response.OutputStream.Write(outb, 0, outb.Length);
}
serverResponse.Close();
}
}
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
// Gets the token for a server URL from a configuration file
// TODO: ?modify so can generate a new short-lived token from username/password in the config file
private string getTokenFromConfigFile(string uri)
{
try
{
ProxyConfig config = ProxyConfig.GetCurrentConfig();
if (config != null)
return config.GetToken(uri);
else
throw new ApplicationException(
"Proxy.config file does not exist at application root, or is not readable.");
}
catch (InvalidOperationException)
{
// Proxy is being used for an unsupported service (proxy.config has mustMatch="true")
HttpResponse response = HttpContext.Current.Response;
response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
response.End();
}
catch (Exception e)
{
if (e is ApplicationException)
throw e;
// just return an empty string at this point
// -- may want to throw an exception, or add to a log file
}
return string.Empty;
}
}
[XmlRoot("ProxyConfig")]
public class ProxyConfig
{
#region Static Members
private static object _lockobject = new object();
public static ProxyConfig LoadProxyConfig(string fileName)
{
ProxyConfig config = null;
lock (_lockobject)
{
if (System.IO.File.Exists(fileName))
{
XmlSerializer reader = new XmlSerializer(typeof(ProxyConfig));
using (System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
config = (ProxyConfig)reader.Deserialize(file);
}
}
}
return config;
}
public static ProxyConfig GetCurrentConfig()
{
ProxyConfig config = HttpRuntime.Cache["proxyConfig"] as ProxyConfig;
if (config == null)
{
string fileName = GetFilename(HttpContext.Current);
config = LoadProxyConfig(fileName);
if (config != null)
{
CacheDependency dep = new CacheDependency(fileName);
HttpRuntime.Cache.Insert("proxyConfig", config, dep);
}
}
return config;
}
public static string GetFilename(HttpContext context)
{
return context.Server.MapPath("~/proxy.config");
}
#endregion
ServerUrl[] serverUrls;
bool mustMatch;
[XmlArray("serverUrls")]
[XmlArrayItem("serverUrl")]
public ServerUrl[] ServerUrls
{
get { return this.serverUrls; }
set { this.serverUrls = value; }
}
[XmlAttribute("mustMatch")]
public bool MustMatch
{
get { return mustMatch; }
set { mustMatch = value; }
}
public string GetToken(string uri)
{
foreach (ServerUrl su in serverUrls)
{
if (su.MatchAll && uri.StartsWith(su.Url, StringComparison.InvariantCultureIgnoreCase))
{
return su.Token;
}
else
{
if (String.Compare(uri, su.Url, StringComparison.InvariantCultureIgnoreCase) == 0)
return su.Token;
}
}
if (mustMatch)
throw new InvalidOperationException();
return string.Empty;
}
}
public class ServerUrl
{
string url;
bool matchAll;
string token;
[XmlAttribute("url")]
public string Url
{
get { return url; }
set { url = value; }
}
[XmlAttribute("matchAll")]
public bool MatchAll
{
get { return matchAll; }
set { matchAll = value; }
}
[XmlAttribute("token")]
public string Token
{
get { return token; }
set { token = value; }
}
}

Blackberry screen renew with new data

I am developing a Blackberry Application. I have a map in a screen. I want to refresh map's data with new data which i am getting from my web service. I am using BlockingSenderDestination in a Thread. When i request "get data" its return new data. no problem. I am using invokelater function to call my maprefresh function with passing arguments but i got illegalargumentexception.
Any suggestion to solve my problem or any better way to do this?
Here is my code:
public class MyMainScreen extends MainScreen {
RichMapField map;
MyClassList _myclassList;
private String _result2t;
public MyMainScreen(JSONArray jarray)
{
map = MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
private void GetTerminals(String companyNo){
final String companyNoR= companyNo;
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://webservice";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("o", URI.create(uriStr));
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("o"),
URI.create(uriStr)
);
}
response = bsd.sendReceive();
if(response != null)
{
BSDResponse(response,companyNoR);
}
}
catch(Exception e)
{
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
private void BSDResponse(Message msg,final String companyNo)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result2t = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result2t = new String(data);
}
}
try {
final JSONArray jarray= new JSONArray(_result2t);
final String username=_userName;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("The Toolbar i");
Yenile(jarray);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Yenile(JSONArray jarray){
MapDataModel mapDataModel = map.getModel();
mapDataModel.remove("1");
map.getMapField().update(true);
_terminalList = new TerminalList();
map= MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray_terminaller.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
}
To refresh the screen: do like this:
public class LoadingScreen extends MainScreen{
LoadingScreen()
{
createGUI();
}
public void createGUI()
{
//Here you write the code that display on screen;
}}
we know that this is the actual way of creating a screen;
Now if you want to refresh the screen write like below:
deleteAll();
invalidate();
createGUI();//here it creates the screen with new data.
Instead of writing in InvokeLater method better to write the above three lines in run method after Thread.sleep(10000);
If you have any doubts come on stackOverFlow chat room name "Life for Blackberry" for clarify your and our doubts.
I found a solution to my question.
After getting the data i was sending it via new run method:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
MyFunction(jarray);
}});
But i was need to synchronize with main thread. So the solution:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized(Application.getEventLock()) {
Yenile(jarray);
}
}
});

Resources