Embedded RavenDB in asp.net MVC website does not initialize - c#

Why can't I make an embedded RavenDB work in a fresh asp.net MVC website?
I have successfully tried and tested the following code in a simple .net console application. It works just fine, until I try and use it in an MVC website.
It doesn't throw any error, it just hangs after attempting to Initialize()
In my bug-finding process, I installed a RavenDB server on localhost, which I can connect to in my MVC application - that is not a problem. But the initialize error was there before I installed the localhost RavenDB as well as after.
I hope you can help sort this out!
public static class Store {
private static IDocumentStore store = createStore();
private static EmbeddableDocumentStore createStore() {
var returnStore = new EmbeddableDocumentStore();
returnStore.DataDirectory = #"./PersistedData";
returnStore.Initialize(); // It never gets past this in any MVC website
return returnStore;
}
public static myDocument Read(string key) {
using (var session = store.OpenSession()) {
var anEntity = session.Query<myDocument>().Where(item => item.key == key).Single();
return anEntity;
}
}
public static void Write(myDocument d) {
using (var session = store.OpenSession()) {
session.Store(d);
session.SaveChanges();
}
}
}
public class myDocument {
public string key { get; set; }
public string description { get; set; }
}
UPDATE
The following errors are logged and show up in the Event Viewer:
INFORMATION: Raven (11096) 1-RT4um-C:\Users\***\RavenEmbed\./PersistedData\Data:
The database engine attached a database (1, C:\Users\***\RavenEmbed\PersistedData\Data).
(Time=0 seconds)
ERROR: Windows cannot open the 64-bit extensible counter DLL ASP.NET_64_2.0.50727 in a
32-bit environment. Contact the file vendor to obtain a 32-bit version. Alternatively if
you are running a 64-bit native environment, you can open the 64-bit extensible counter
DLL by using the 64-bit version of Performance Monitor. To use this tool, open the
Windows folder, open the System32 folder, and then start Perfmon.exe.
ERROR: Disabled performance counter data collection for this session from the
"ASP.NET_64_2.0.50727" service because the performance counter library for that service
has generated one or more errors. The errors that forced this action have been written
to the application event log.
ERROR: The Open Procedure for service "BITS" in DLL "C:\Windows\System32\bitsperf.dll"
failed. Performance data for this service will not be available. The first four bytes
(DWORD) of the Data section contains the error code.
ERROR: The Open Procedure for service "Lsa" in DLL "C:\Windows\System32\Secur32.dll"
failed. Performance data for this service will not be available. The first four bytes
(DWORD) of the Data section contains the error code.
ERROR: The Open Procedure for service "MSDTC" in DLL "C:\Windows\system32\msdtcuiu.DLL"
failed. Performance data for this service will not be available. The first four bytes
(DWORD) of the Data section contains the error code.
ERROR: The configuration information of the performance library "perf-MSSQL$SQLEXPRESS-
sqlctr11.1.3000.0.dll" for the "MSSQL$SQLEXPRESS" service does not match the trusted
performance library information stored in the registry. The functions in this library
will not be treated as trusted.
UPDATE 2
I can download an MVC 3 project from this link, which works. But I still can't the MVC 4 embedded RavenDB to work.
http://archive.msdn.microsoft.com/mag201111NoSQL/Release/ProjectReleases.aspx?ReleaseId=5778

Related

Firestore C#: Missing or insufficient permissions

I am currently exploring Firebase's Cloud Firestore in C# and has encountered with the error which I could not resolve after searching SO. It seems that the resources for Firestore in C# is quite limited:
"Status(StatusCode=PermissionDenied, Detail=\"Missing or insufficient permissions.\")"
My code so far:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "FirebaseCsharpTest.json");
string project = "MyProjectId";
FirestoreDb db = FirestoreDb.Create(project);
Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
AddPerson(db).GetAwaiter().GetResult();
}
public static async Task AddPerson(FirestoreDb db)
{
CollectionReference collection = db.Collection("users");
DocumentReference document = await collection.AddAsync(new
{
Name = new
{ First = "Ada", Last = "Lovelace" },
Born = 1815
});
}
}
I have checked on my Firebase console that the Firestore security rules are set to public (as of now, for testing sake). I have also ensured that the authentication json file is the right file generated from Google Developer Console as suggested in this post.
Is there something I'm missing?
EDIT:
My permissions on google cloud console:
Do check the projectID that you have been adding.
ProjectID is supposed to be the one that is specified in your json file.
This is a Cloud IAM issue and not a security rule issues. The C# server client library creates a privileged server environment that doesn't take into account Cloud Firestore security rules.. It seems that either your key file's service account doesn't have the correct IAM role or your code is not finding your keyfile.
Try using the full path to your keyfile instead of the relative path.
You can also try setting up a new service account and key file as described here.
Also, make sure you are changing the project variable:
string project = "NewFirebaseCsharpTest";
FirestoreDb db = FirestoreDb.Create(project);
Change the string project to the Id of the project and not the name of the project. The Id will probably start with the name and have a numeric suffix.
If that fails, go to the Log Explorer and query the logs. You will see an error that explains why your permission was denied.
You're never going to get enough information from the client-side for security reasons. Google isn't going to tell someone trying to gain access to something they shouldn't have access to what is going wrong. But, an admin can view the logs on the other side which will log all the information.

Precompiled Azure Function Output to Blob Storage receiving 500 Internal Server Error

The final output of my C# Precompiled Azure Function is to write to a blob storage as a JSON file. Am I writing to the Blob storage wrong? I hit the breakpoints set on the curly brackets at to the end of the function and it looks like it exits the function. Around 20 seconds later I get the exception:
Exception while executing function: ServiceBusTriggeredProcessAccepted. Microsoft.Azure.WebJobs.Host: Error while handling parameter outboundStringForBlobStorage after function returned:. Microsoft.WindowsAzure.Storage: The remote server returned an error: (500) Internal Server Error.
The Azure Function is a Service Bus triggered event. After processing fails the Service Bus queued item auto-increments and retries, a total of 10 times, before it's moved to the dead-letter queue. It should be noted the objects are large enough in size that regular Queue's are too small for them.
public class SomeObject
{
//15 Properties all string and boolean
public string Attachment{ get; set;}
public string AnotherProperty{ get; set;}
public bool IsConditionMet { get; set; }
//Maybe these aren't needed now since it's blob storage but it's part of the object currently
public string PartitionKey { get; set; }
public string RowKey { get; set; }
}
[FunctionName("ServiceBusTriggeredProcessAccepted")]
public static void Run([ServiceBusTrigger("accepted")]
SomeObject someObject,
TraceWriter log,
[Blob("accepted-attachments/{Attachment}", FileAccess.Read)] Byte[] blobContent
, [Blob("accepted-sent/{rand-guid}.json")] out string outboundStringForBlobStorage
)
{
someObject.PartitionKey = "email";
someObject.RowKey = Guid.NewGuid().ToString();
//Business Logic to execute here
SomeService.SomeFunctionToSendBlobFile(someObject, blobContent)
outboundStringForBlobStorage = JsonConvert.SerializeObject(someObject);
}
I am using:
Azure Functions SDK NuGet Package 1.0.21
Microsoft.Azure.Webjobs 2.2.0
WindowsAzure.ServiceBus 5.0.0
DotNetFramework 4.6.1
Windows Azure Storage Emulator 5.8.0.0
Runtime Version=1.0.11702.0
Does the serialization have to be sanitized somehow? I haven't had to sanitize in the past but the data in that object has changed and that is when the problems started to occur. I would expect that the file to get written to the blob storage immediately or return the exception immediately and not 20 seconds after exiting the function.
The error may have nothing to do with serialization, let's focus on this line.
Microsoft.WindowsAzure.Storage: The remote server returned an error: (500) Internal Server Error.
If I understand correctly, the blob input and output both connect with Azure Storage Emulator. There's sth wrong in v5.8 Emulator failing blob writing. Install latest Emulator(v5.9 right now) could get rid of the problem.
And also note that Runtime Version=1.0.11702.0 means the CLI and templates are obsolete, to consume the latest, force VS to download on startup.
Ensure Azure Functions and Web Jobs Tools is the latest, right now it's 15.10.2046. On VS menus> Tools> Extensions and Updates> Updates, Update the extension if it's in the list.
Remove %localappdata%\AzureFunctionsTools and %userprofile%\.templateengine folder.
Reopen VS to create a new Function project, wait at the creation dialog, See Making sure all templates are up to date....
After a while, we can see the tip changes as
Click Refresh to work with the latest template instantly.
Don't forget to update Microsoft.NET.Sdk.Functions to latest(1.0.24 right now). And we don't need to install Microsoft.Azure.Webjobs separately which is referenced by Microsoft.NET.Sdk.Functions internally.
Once function starts we can see runtime Version=1.0.12205.0 right now.

Autodesk.Inventor.Interop.dll on WinServer 64-bit 2012 R2 - interface non registred

i'm trying to develop a very simple web application based on the Autodesk Inventor engine.
I'm developing on Win7 64-bit with Visual Studio 2010 and Inventor 2015 and everything it's working perfectly on debugging but when i publish on the web server i get the error:
HRESULT: 0x800401F3 (CO_E_CLASSSTRING)
and the message
interface string not valid
The C# code line where i receive the error is:
Inventor.Application _invApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");
The full code for my test is the following:
using Inventor;
using System.Runtime.InteropServices;
namespace web_debug_cs
{
public partial class debug_runinventor : Ssytem.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) { startInventorApplication(); }
private void startInventorApplication()
{
string sDebug = string.Empty;
try
{
Inventor.Application _invetorApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");
sDebug = "Success!!!";
}
catch (Exception ex) { sDebug = "UNSUCCESS!<br />" + ex.Message; }
lblAnswer.Text = sDebug;
}
}
}
I get this code directly from the Inventor 2015 guide, but (repeat) on the local machine everything it's ok, but not on the server.
I checked the permission (everyone: full control)
I registred manually with regsvr32 (impossible to register) both on system32 and SysWOW64
I registred on the framework 32 and 64 with regasm (registration success!)
I set the web site to work with 32-bit application
but nothing could solve this issue.
I thought about the possibility to import manually the dll with pInvoke, but with no success...
I googled a lot, i tryed to ask to Autodesk with no success.
I started Inventor on the Server to verify if it works, and it work perfectly!
Could anyone try to help me?
Thanks in advance for any kind reply!
Emanuele
I would not expect this to work due a simple reason: the webpage is running as a service, and Inventor runs as a user-level application. Imagine the following: the web page is requested by 100 clients/browsers, your app will launch Inventor 100 times. But more than that, the webpage is not on the user-level.
The best chance to work would be: your webpage receives a request (let's say create a .ipt file), create a record that the action must be performed (for instance, a new .txt file with instructions or a database entry), a Windows services detects the request and launch Inventor to process it. In this case you'll have a queue where requests are placed by your webpage, but processed later.
But I must say this is not supported nor allowed on the EULA, please review it.

ASP.NET Web Application - on deploy, System.Speech.dll object not getting set to an instance of an object

I have an ASP.NET web application that uses System.Speech to transform text to a WAV file. It works fine locally but when I deploy it to the server, I get the below error message. This is using Windows Server 2012, ASP.NET 4.5, and IIS 8.5:
Object reference not set to an instance of an object.
System.Speech
at System.Speech.Internal.ObjectTokens.RegistryDataKey..ctor(String fullPath, RegistryDataKey copyKey)
at System.Speech.Internal.ObjectTokens.SAPICategories.DefaultDeviceOut()
at System.Speech.Internal.Synthesis.VoiceSynthesis..ctor(WeakReference speechSynthesizer)
at System.Speech.Synthesis.SpeechSynthesizer.get_VoiceSynthesizer()
at QuinnSDS.handlerTransform.<>c__DisplayClass6.<ProcessRequest>b__1()
The code which is generating this error message runs on the server:
if (context.Request.ContentLength > 0)
{
string line = new StreamReader(context.Request.InputStream).ReadToEnd();
// ********* generate wav file voicing the response *****************
// Using Microsoft voices
// initiate new instance of speech synthesizer
Thread t = new Thread(() =>
{
try
{
// The object creation works fine
System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();
if (synth != null)
{
// The code breaks at synth.GetInstalledVoices() below. It will break any time I try to do anything with the synth object
foreach (System.Speech.Synthesis.InstalledVoice voice in synth.GetInstalledVoices())
{
System.Speech.Synthesis.VoiceInfo info = voice.VoiceInfo;
string voiceName = info.Name;
ws.WriteLine(voiceName);
}
}
}
catch (Exception e)
{
ws.WriteLine(e.Message);
ws.WriteLine(e.Source);
ws.WriteLine(e.StackTrace);
}
//... code continues...
It does not break when the Speech Synthesis object is created; it breaks whenever I try to use that object in any way.
I'm not sure if it's an access issue but I'm pretty new to ASP.NET and IIS and I can't figure out how to give the web app access to the GAC or if that's even what the problem is. I tried changing the property Local Copy for the System.Speech reference to True in Visual Studio, before I deploy the app, but that hasn't worked. I searched online and while the "object reference not set to an instance of an object" seems fairly common, I cannot find any similar issues where it is because of a .NET framework class library...I have run the text-to-speech code locally on the server and it ran fine. I have not run the entire app locally on the server because the web app requires speech input and there is not a microphone on the server.
Any ideas of anything to try would be most welcome!
What user account is the code running under when executed from ASP.NET? If the Speech API is touching the registry like the call stack suggests, it possibly has different permissions than the account you used to run the code manually.
If you can't just make the application pool for your site run with the same account you log into the machine with, I've had some success using Process Monitor to track down this kind of problem before. Basically, execute the code that fails while Process Monitor is running and look for 'ACCESS DENIED' in the 'Result' column (or anything else that looks suspicious). Quickly switching the application pool to use your standard user account will be the fastest way to rule out security or permission related problems though.

C# classes not being called when using MongoDB project

I have an MVC4 website and I am trying to integrate some Mongodb functionality (just experimenting for now). I am using this mongodb project as I am also trying to deploy to Azure, this project provides connection utilities for connecting to the mongodb worker role. I have a MovieController with the following constructor:
public class MovieController : Controller
{
MongoMovieHelper _movies;
public MovieController()
{
_movies = new MongoMovieHelper();
}
}
This in turn calls the class:
public class MongoMovieHelper
{
public MongoCollection<Movie> Collection { get; private set; }
public MongoMovieHelper()
{
MongoServerSettings serverSettings = ConnectionUtilities.GetConnectionSettings();
MongoServer server = MongoServer.Create(serverSettings);
MongoDatabase db = server["movies"];
Collection = db.GetCollection<Movie>(typeof(Movie).Name.ToLower());
}
...
When trying to load any page from the Movie controller I get an internal server error in the Chrome debugger.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
So I tried debugging in visual studio. The controller constructor gets hit, but any breakpoints within MongoMovieHelper do not, and trying to Step into just hits the controller constructor again. The stack trace displays the following error:
Could not load file or assembly 'MongoDB.Driver, Version=1.4.2.4500,
Culture=neutral, PublicKeyToken=f686731cfb9cc103' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
Previously I had another class which makes the Mongodb connection so Controller calls MongoMovieHelper which calls MongoDBHelper. In this case, both the controller and MongoMovieHelper were being called, but MongoDBHelper was not, so I believe the problem lies within the mongodb connection.
This is probably some rookie mistake but I just can't figure out what the problem might be, any ideas?
I tried to recreate your problem using the latest version of the official mongodb c# driver but I could not.
I am using the latest official driver available on NuGet:
I changed your code to use non-obsolete methods to get the server object:
public MongoMovieHelper()
{
var client = new MongoClient(MongoUrl.Create("mongodb://localhost:27017"));
var server = client.GetServer();
var db = server["movies"];
Collection = db.GetCollection<Movie>(typeof (Movie).Name.ToLower());
}
So if you are not using the official driver then please use it:
get using the following command:
Install-Package mongocsharpdriver
Then try and change your code to look something like mine and then see if it works.
The error you are getting suggests you are either using an old version of the official driver, or you aren't using the official driver at all.
Note: uninstall the old driver, either through the nuget console (/ui), alternatively remove the binary ref and clean your project ensuring that you don't have any bin dll left hanging around.

Categories