How do I do an EF Database.ExecuteSQLCommand async? - asp.net

Here's the code that I am using:
public async Task<IHttpActionResult> NewTopicTests([FromBody] NewTopicTestsDTO testSpec)
{
var sql = #"dbo.sp_new_topic_tests #Chunk";
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("#Chunk", testSpec.Chunk)
};
int result = db.Database.ExecuteSqlCommand(sql, parameters);
await db.SaveChangesAsync();
return Ok();
}
Can someone confirm if this is the correct way to do this using async? In particular do I need to do this:
int result = db.Database.ExecuteSqlCommand(sql, parameters);
await db.SaveChangesAsync();
Note that the code works however I am having a problem with my application where it suddenly stops without any error message. I am looking into every possible problem.

What's being saved here ? I think there is no need to call save changes here.
Remove save changes and you will see the same behavior, because any changes you've made in your stored procedure, are not tracked by entity framework context.
And you can rewrite your code as following:
int result = await db.Database.ExecuteSqlCommandAsync(sql, parameters);
Have you checked every where to find the reason of your problem ? Windows Error Log etc ?
Go to Debug menu of Visual Studio IDE, and open Exceptions, then check both 'throw' and 'user_unhandled' for 'Common Language Runtime Exceptions' and test your code again.

Related

Xamarin Offline Sync issue with getting data

I am getting some issues returning data from azure mobile backend api using android emulator. The mobile app is written with Xamarin and I am using MobileServiceClient and IMobileServiceSyncTable. The following is what I have coded:
var _mobileServiceClient = new MobileServiceClient(url);
var store = new MobileServiceSQLiteStore("notesdb.db");
store.DefineTable<Notes>();
_mobileServiceClient.SyncContext.InitializeAsync(store);
var _notesTable = _mobileServiceClient.GetSyncTable<Notes>();
var temp = await _notesTable.ReadAsync();
Backend code is as followed:
public IQueryable<Notes> GetAllNotes()
{
return Query();
}
Whenever I do that, the app will become unresponsive and never returned. Its like it is in deadlock mode.
Has anyone had this problem?
After looking at the MobileServiceClient usage: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-dotnet-how-to-use-client-library
Your calls seem fine except one:
_mobileServiceClient.SyncContext.InitializeAsync(store);
Since you are not awaiting this method, the sync context will not be initialized for your next methods.
So just await the method and you should be fine:
await _mobileServiceClient.SyncContext.InitializeAsync(store);
One general rule your can apply almost everytime: always await the methods returning Task objects.
Also since you are in the service/repository layer, you should ConfigureAwait(false) your methods:
var _mobileServiceClient = new MobileServiceClient(url);
var store = new MobileServiceSQLiteStore("notesdb.db");
store.DefineTable<Notes>();
await _mobileServiceClient.SyncContext.InitializeAsync(store).ConfigureAwait(false);
var _notesTable = _mobileServiceClient.GetSyncTable<Notes>();
var temp = await _notesTable.ReadAsync().ConfigureAwait(false);
Doing that your code won't run in the UI thread (well it's not guaranteed but I don't want to confuse you :). Since you are not running the code on the same thread, it will also reduce possible deadlocks.
more on that: https://medium.com/bynder-tech/c-why-you-should-use-configureawait-false-in-your-library-code-d7837dce3d7f

The session state Information is invalid and might be corrupted in ASP.Net

I am using ASP.Net 3.5 with C#,Development ID:Visual Studio 2008. When I am using
Session["FileName1"] = "text1.txt"
it is working fine, but then I am using
number1=17;
string FileName1="FileName1" + number1.toString();
then setting with
Session[FileName1]="text1.txt";
gives me runtime error
The session state information is invalid and might be corrupted
at System.Web.SessionState.SessionStateItemCollection.Deserializer(BinaryReader reader)
Can anybody solve my problem, when I am using string in the Session variable? Remember it works on my development machine (meaning local Visual Studio) but when deployed to the server it gives mentioned error.
Make sure the FileName1 variable is not null before trying to access it via the Session[FileName1] syntax...
Here's a link to someone else that was having the same problem:
http://forums.asp.net/t/1069600.aspx
Here's his answer:
In the code, I found the following line:
//some code
Session.Add(sessionVarName, sessionVarValue);
//some other code
Apparently, because of some dirty data, there is a time when
sessionVarName is null.
Session.Add will not throw any exception in this case, and if your
Session Mode is "InProc", there will be no problem. However, if your
Session Mode is "SQLServer", during deserialization of the session
store, you will got the exception that I got. So, to filter out dirty
data, I modified the code to become:
if (sessionVarName != null)
{
//somecode
Session.Add(sessionVarName, sessionVarValue);
//some other code
}
the reason of your error is
xyz = new Guid() is also xyz= Guid.Empty;
so when you try to convert to string it's throw error.
just modify you code something like that.
Guid guId = System.Guid.NewGuid();
string x = guId .ToString();
string FileName1="text1.txt" + x;
Session[FileName1]="text1.txt";
Check your values before storing them in session they may cause this exception during deserialization of the session store, Filter your data .
Check Here
if(!string.IsNullOrEmpty(FileName1))
{
Session.Add(FileName1, "text1.txt");
}
Or check for Invalid characters in your string .
You can add the Value into session Like this
string FileName1="FileName1" + number1.toString();
if(!string.IsNullOrEmpty(FileName1))
{
Session.Add(FileName1, "text1.txt");
}

asp.net app calling service says its not initialized?

So this code runs in an asp.net app on Linux. The code calls one of my services. (WCF doesn't work on mono currently, that is why I'm using asmx). This code works AS INTENDED when running from Windows (while debugging). As soon as I deploy to Linux, it stops working. I'm definitely baffled. I've tested the service thoroughly and the service is fine.
Here is the code producing an error: (NewVisitor is a void function taking 3 strings in)
//This does not work.
try
{
var client = new Service1SoapClient();
var results = client.NewVisitor(Request.UserHostAddress, Request.UrlReferrer == null ? String.Empty : Request.UrlReferrer.ToString(), Request.UserAgent);
Logger.Debug("Result of client: " + results);
}
Here is the error generated: Object reference not set to an instance of an object
Here is the code that works perfectly:
//This works (from the service)
[WebMethod(CacheDuration = _cacheTime, Description = "Returns a List of Dates", MessageName = "GetDates")]
public List<MySqlDateTime> GetDates()
{
return db.GetDates();
}
//Here is the code for the method above
var client = new Service1Soap12Client();
var dbDates = client.GetDates();
I'd love to figure out why it is saying that the object is not set.
Methods tried:
new soap client.
new soap client with binding and endpoint address specified
Used channel factory to create and open the channel.
If more info is needed I can give more. I'm out of ideas.
It looks like a bug in mono. You should file a bug with a reproducible test case so it can be fixed (and possibly find a workaround you can use).
Unfortunately, I don't have Linux to test it but I'd suggest you put the client variable in an using() statement:
using(var client = new Service1SoapClient())
{
var results = client.NewVisitor(Request.UserHostAddress, Request.UrlReferrer == null ?
String.Empty : Request.UrlReferrer.ToString(), Request.UserAgent);
Logger.Debug("Result of client: " + results);
}
I hope it helps.
RC.

Microsoft Speech Recognition in webservices is not returning the result

Well i'm using Microsoft Speech Platform SDK 10.2.
I made a asp.Net WebService application and most of the WebServices works fine (HelloWorld(), etc...), but I have one service that uses the SpeechRecognitionEngine and when I deploy the application and try to run this webservice I get no result, i.e, I can see through the debug mode that it reaches the return line, but when I call it trought the browser the page keeps loading for ever, without any response.
Here's a sample of the code:
[WebMethod]
public bool voiceRecognition() {
SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("pt-PT"));
Choices c = new Choices();
c.Add("test");
GrammarBuilder gb = new GrammarBuilder();
gb.Append(c);
Grammar g = new Grammar(gb);
sre.LoadGrammar(g);
sre.InitialSilenceTimeout = TimeSpan.FromSeconds(5);
//// just for Testing
RecognitionResult result = null;
if (result != null) {
return true;
} else {
return false;
}
}
Note: I'm using IIS to deploy the WebService Application.
If someone have some thoughts please let me know.
I don't know if you've found your answer or not. When trying to solve this myself a couple of days ago, I stumbled across your question and it matched our circumstances to a "T".
In order to fix it all we had to do was put...
sre.RecognizeAsyncStop();
sre.Dispose();
where "sre" is your SpeechRecognitionEngine variable. If you don't stop it and dispose of it at the end of your web service then the web service won't return.
Hope this helps. :)

Oracle query fired off, then never returns

I have this problem in my ASP.NET application where I'm seeing some of my Oracle queries fired off to the server then not returning. Ever. It happens in several places in my app and I can't explain it. Here's one specific scenario where I'm seeing this behavior:
During application start-up I am pre-fetching data asynchronously into the application state (the choice was made to use app state instead of cache b/c the data never changes during the lifetime of the app).
Action<string, object> AddApplicationState = (string name, object data) =>
{
Application.Lock();
Application.Add(name, data);
Application.UnLock();
};
Func<DataTable> GetFullNames = () => Database.GetAllNames();
Func<DataTable> GetProvinceNames = () => Database.GetProvinceNames();
Func<DataTable> GetTribeNames = () => Database.GetTribeNames();
GetFullNames.BeginInvoke(result => AddApplicationState("AllNames", GetFullNames.EndInvoke(result)), null);
GetProvinceNames.BeginInvoke(result => AddApplicationState("ProvinceNames", GetProvinceNames.EndInvoke(result)), null);
GetTribeNames.BeginInvoke(result => AddApplicationState("TribeNames", GetTribeNames.EndInvoke(result)), null);
The second two return just fine, but the first either never returns or returns after about 10 minutes. After firing up Oracle SQL Developer I go to the 'monitor sessions' tool and can see a single session for the query. It looks like it has completed, b/c the wait time is (null) and the session is inactive. Here's the ADO.NET code used to query the database:
public static DataTable GetAllNames()
{
using (OracleConnection oraconn = GetConnection())
{
using (OracleCommand oracmd = GetCommand(oraconn))
{
var sql = new StringBuilder();
sql.AppendLine("SELECT NAME_ID, NATIVE_NAME, NVL(FREQUENCY,0) \"FREQUENCY\", CULTURE_ID,");
sql.AppendLine("ENGLISH_NAME, REGEXP_REPLACE(ENGLISH_NAME, '[^A-Za-z]', null) \"ENGLISH_NAME_STRIPPED\"");
sql.AppendLine("FROM NAMES");
oracmd.CommandText = sql.ToString();
var orada = new OracleDataAdapter(oracmd);
var dtAllNames = new DataTable();
orada.Fill(dtAllNames);
return dtAllNames;
}
}
}
public static DataTable GetTribeNames()
{
using (OracleConnection oraconn = GetConnection())
{
using (OracleCommand oracmd = GetCommand(oraconn))
{
var sql = new StringBuilder();
sql.AppendLine("SELECT DISTINCT NAME_ID, English_Name \"TRIBE_NAME_ENGLISH\",");
sql.AppendLine("REGEXP_REPLACE(English_Name, '[^A-Za-z]',null) \"TRIBE_ENGLISH_NAME_STRIPPED\",");
sql.AppendLine("NATIVE_NAME \"TRIBE_NATIVE_NAME\"");
sql.AppendLine("FROM NAMES");
sql.AppendLine("WHERE NAME_ID IN ");
sql.AppendLine("(SELECT NAME_ID_TRIBE FROM TRIBES UNION SELECT NAME_ID_FAMILY FROM TRIBES)");
sql.AppendLine("ORDER BY English_Name");
oracmd.CommandText = sql.ToString();
var orada = new OracleDataAdapter(oracmd);
var dt = new DataTable();
orada.Fill(dt);
return dt;
}
}
}
public static DataTable GetProvinceNames()
{
using (OracleConnection oraconn = GetConnection())
{
using (OracleCommand oracmd = GetCommand(oraconn))
{
oracmd.CommandText = "SELECT DISTINCT PROVINCE_ID, PROVINCE_NAME_NATIVE, PROVINCE_NAME_ENGLISH FROM PROVINCES";
var orada = new OracleDataAdapter(oracmd);
var dtRC = new DataTable();
orada.Fill(dtRC);
return dtRC;
}
}
}
As you can see, the ADO.NET code is pretty standard (and boring!) stuff. When run in SQL Developer, the queries return less than a second. The first query returns x rows, the second x rows, and the third x rows. But this problem of queries being fired off then never returning happens often and I can't seem to track down the issue. Anyone have any thoughts?
And finally, since I realize it could be something completely unrelated to code, I am running the app locally (from Visual Studio) on a Windows XP SP3 machine and connecting via VPN to a remote Oracle 10g Enterprise instance running on Windows 2003 Server. Locally, I have installed Oracle Data Access Components v11.1.0.6.20.
Thanks!
Are you watching your output window for any exceptions? I don't see any catch blocks in your code.
Oracle's ODP.net has almost exactly the same syntax as ADO, but performs better in many situations. If you're only using Oracle, it might be worth a look.
Is there a reason to use StringBuilder? A single string variable will perform better and makes code easier to read.
It seems that the queries were actually returning, just taking a very long time due to poor query performance, low bandwidth, and the enormous amount of rows being returned. The VS debugger seems to give up after a few seconds for these long-running queries. However, if I let it sit for a few minutes my breakpoints would get hit and things would work as expected.
Thanks for the replies / comments!

Resources