When calling RavenDb store.DatabaseCommands.GlobalAdmin.CreateDatabase() the call hangs - asp.net

The project that I am currently working on is using RavenDb as an embedded datastore, while attempting to call out to make sure that the database exists in the store, I am finding that it hangs.
var docStore = new EmbeddableDocumentStore()
{
DataDirectory = "Data",
};
docStore.Initialize();
// Check to make sure that the database exists
bool bcDatabaseExists = docStore.DatabaseCommands.GlobalAdmin.GetDatabaseNames(1024).Contains(DatabaseName);
if (!bcDatabaseExists)
{
Dictionary<string, string> settings = new Dictionary<string, string>();
DatabaseDocument databaseDocument = new DatabaseDocument()
{
Id = DatabaseName,
Settings =
{
{ "Raven/DataDir", "~\\Data" }
}
};
try
{
docStore.DatabaseCommands.GlobalAdmin.CreateDatabase(databaseDocument);
}
catch (Exception ex)
{
log.Error(ex);
}
}
However when I hit the CreateDatabase call the process just hangs without any notification. I wanted to check to make sure I wasn't using the call incorrectly, or if there was a better call.
Any thoughts or suggestions that you can offer would be greatly appreciated.

Although the question has nothing to do with NancyFX, probably you need EnsureDatabaseExists method. It will create the database, if it's not there yet.

Related

How to use Dapper asynchronously with multiple stored procedure calls?

I'm using the Dapper ORM in an ASP.Net Core 2.1 CRUD application, with a SQL Server database. For a new form I'm developing, I want to retrieve all reference data (to populate SELECT field options) in one go when the screen is invoked. This involves a series of stored procedure calls, which I want to do asynchronously for best performance.
This Dapper tutorial suggests I should look at using QueryMultipleAsync, but I can't find an example of its use with stored procedures, only hard-coded SQL statements.
My C# code currently looks like this:
public async Task<ContactReferenceData> Get()
{
ContactReferenceData refData = new ContactReferenceData();
try
{
using (IDbConnection dbConnection = _connection)
{
dbConnection.Open();
var countryData = await dbConnection.QueryAsync<Country>(sql: "usp_GetCountries", commandType: CommandType.StoredProcedure);
refData.CountryDetails = countryData.AsList();
var companyData = await dbConnection.QueryAsync<Company>(sql: "usp_GetCompanies", commandType: CommandType.StoredProcedure);
refData.CompanyDetails = companyData.AsList();
var groupData = await dbConnection.QueryAsync<Group>(sql: "usp_GetGroups", commandType: CommandType.StoredProcedure);
refData.GroupDetails = groupData.AsList();
var groupPositionData = await dbConnection.QueryAsync<GroupPosition>(sql: "usp_GetGroupPositions", commandType: CommandType.StoredProcedure);
refData.GroupPositionDetails = groupPositionData.AsList();
}
return refData;
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
throw;
}
}
This works OK in my test environment, but I'm not sure it's the correct way to execute async queries. In particular, I have the following concerns:
is it robust enough to be trusted in live operation?
in its current form, is it maximising the benefits (if any) of asynchronous operation, or should I be using QueryMultipleAsync to properly achieve this?
Have you tried something like this?
public async Task<ContactReferenceData> Get()
{
var sql = "EXEC usp_GetCountries; EXEC usp_GetCompanies; EXEC usp_GetGroups; EXEC usp_GetGroupPositions";
ContactReferenceData refData = new ContactReferenceData();
try
{
using (IDbConnection dbConnection = _connection)
{
using (var multi = connection.QueryMultipleAsync(sql: sql, commandType: CommandType.StoredProcedure ).Result)
{
refData.CountryDetails = multi.Read<countryDetails>().ToList();
refData.CompanyDetails = multi.Read<CompanyDetails>().ToList();
refData.GroupData = multi.Read<Groups>().ToList();
refData.GroupPositionsData= multi.Read<GroupPositions>().ToList();
}
}
return refData;
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
throw;
}
}

How to use Transactions in ASP.NET MVC identity 2?

In My ASP.NET MVC5 Identity 2 Application trying to use transactions but it is not working.please see the below code the transactions not working.If var saveteacher = _teacherService.Create(aTeacher); not insert successfully then AspNetUsers not rollback from database.
Code:
using (var dataContext = new SchoolMSDbContext())
{
using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
{
try
{
var adminresult =await UserManager.CreateAsync(user, teacherViewModel.Password);
if (adminresult.Succeeded)
{
aTeacher.Id = user.Id;
var saveteacher = _teacherService.Create(aTeacher);
}
else
{
trans.Rollback();
ModelState.AddModelError("", adminresult.Errors.First());
return View();
}
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine(ex.InnerException);
}
}
}
I think the problem could be with async stuff.
Try creating the transaction like this:
TransactionScope transaction = new TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled);
(you'll have to add System.Transactions) to references.
To commit transaction go transaction.Complete() to rollback do transaction.Dispose().
The problem is that you are creating a new instance of SchoolMSDbContext when you should be acquiring the existing one from the HttpContext.
Example:
using (var dataContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>())
{
//...
}
Make sure _teacherService and UserManager uses same DB Context. No need to create a TransactionScope.

Windows Phone 8 Hanging on GetFolderAsync and OpenStreamForReadAsync

I am making a windows phone 8 application. Part of this application requires state to be saved. I am saving it as a string of Json. If I open the application, save some data, exit the application and the load it again, it hangs on either GetFolderAsync or OpenStreamForReadAsync. It does not happen every time, but once it starts hanging, I have to kill the whole emulator and make a new one to start the application again.
I have even tried just making an empty file with no data in it and the problem still persistes.
Below is the code I am using to save and load the data. It does not matter where I call the data load whether it be on application start or on the form load it still breaks.
private async Task SaveLists()
{
//XmlSerializer serializer = new XmlSerializer(typeof(ListHolder));
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("Lists.json",
CreationCollisionOption.ReplaceExisting);
string json = JsonConvert.SerializeObject(Lists, Formatting.Indented);
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(json.ToCharArray());
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
private async Task LoadLists()
{
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
try
{
// Get the DataFolder folder.
var dataFolder = await local.GetFolderAsync("DataFolder");
// Get the file.
var files = dataFolder.GetFilesAsync();
var file = await dataFolder.OpenStreamForReadAsync("Lists.json");
string jsonString = "";
// Read the data.
using (StreamReader streamReader = new StreamReader(file))
{
jsonString = streamReader.ReadToEnd();
}
if (jsonString.Length > 0)
{
Lists = JsonConvert.DeserializeObject<List<ItemList>>(jsonString);
}
else
{
Lists = new List<ItemList>();
}
}
catch (Exception ex)
{
Lists = new List<ItemList>();
}
}
}
You are causing a deadlock by calling Result. I explain this deadlock on my blog and in a recent MSDN article. In summary, await will (by default) attempt to resume execution within a context (the current SynchronizationContext unless it is null, in which case it uses the current TaskScheduler).
In your case, the current SynchronizationContext is the UI context, which is only used by the UI thread. So when you block the UI thread by calling Result, the async method cannot schedule back to the UI thread to complete.

Reading from HttpContext.Current.Session fails on multi server environment

Environment: IIS 7.5, .Net 4.0
I have a problem reading from HttpContext.Current.Session on a multi server environment.
First in my code I store an object in HttpContext.Current.Session an later try to read it again. The read (performed a number of times) fails randomly and I suspect it has something to do with what server the call hits. The storing and reading of the object is done through ajax calls and a colleague told me to store the object in Page_Load. I was fairly skeptic and as it turns out the problem has not been solved using this approach.
Storing:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream GetHierarchy(string invId, string zoomLevel)
{
Hierarchy hierarchy = new Hierarchy();
try
{
hierarchy = businessLogic.GetHierarchy(invId);
HttpContext.Current.Session["hierarchy"] = hierarchy;
}
catch (Exception ex)
{
throw ex;
}
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(hierarchy)));
}
Reading:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream GetCustomer(string invId, string includeDetails, string zoomLevel)
{
Hierarchy hierarchy = (Hierarchy)HttpContext.Current.Session["hierarchy"];
Customers customers = null;
Customer customer = null;
if (hierarchy != null) {
customers = hierarchy.Customers;
if (customers != null)
{
try
{
customer = (from e in customers.DiagramCustomers where e.InvId == invId select e).ToList()[0];
}
catch (Exception ex)
{
}
}
}
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(customer)));
}
Everything is working just fine in a single server environment...
Can anyone shed some light over what kind of problem it is I'm facing here? And preferably how to solve it :-)
./CJ
Use Sql Server to Store Asp.NET Session State
http://support.microsoft.com/kb/317604

flex 4.5 + wbservice .net

Im working on a example that im trying to use a webservice make it in .net c# and i have a some questions. I have a method in webservice like that:
public string login(string user, string pass)
{
//string msg = "";
string res = "";
person n = new person(user, pass);
if (n.login())
{
Session["user"] = Server.HtmlEncode(u);
setTimeOutLogIn(u);
res = u;
}
else
{
// msg = "Error";
}
return res;
}
now with this I return a string with a unique user for flex to make a state of user.
my doubt is how can I work properly on flex with session?
Other question and problem having here, and is a big one:
when is made any request to webservice the flex only answer the second ask. for example:
public function LogUser()
{
var name:String=Login.text;
var pass:String=Password.text;
Service.login.send(name, pass);
checkLogin();
}
public function checkLogin():Boolean
{
var boll:Boolean= new Boolean;
Service.checkLogin.send(util);
boll = Service.checkLogin.lastResult;
if(boll==false)
{
Llogout.visible=false;
Lregist.visible=true;
Llogin.visible=true;
Luser.visible=false;
currentState="default";
}
else
{
Llogin.visible=false;
Llogout.visible=true;
Lregist.visible=false;
Luser.visible=true;
Luser.text=util;
currentState="default";
}
return boll;
}
<s:operation name="login"> </s:operation>
<s:operation name="checkLogin" result="checkLog()"></s:operation>
</s:WebService>
this simple operation only respond rightly for the second time.
Any thoughts?
Sorry for the trouble
Webservice calls are not like website calls. You will not be able to set a user session that will persist and only be available to your users session. You may want to check out FlorineFX I dont think it will do exactly what you want but I know you can do some of this stuff and interact with the asp.net more like a website. We used this for several projects a couple years ago.

Resources