I am following the example here: http://developer.db4o.com/Forums/tabid/98/aft/10114/Default.aspx to setup my MVC2 app with db4o using an HttpModule. I also have a LINQPad instance open to query the data as I develop. The web app seems to work like a charm, but LINQPad keeps getting DatabaseFileLockedExceptions until I close down the web server.
As I said, I'm using the HttpModule from Gamlor practically verbatim (using ClientServer instead of embedded is the only difference), and here's my LINQPad code:
01 void Main()
02 {
03 using(var server = Db4oClientServer.OpenServer(db4opath, 0))
04 {
05 using(var db = server.OpenClient()){
06 var result = (from Object o in db select o);
07 result.Dump();
08 }
09 }
10 }
11
12 private string db4opath = #"C:\blah\blah\blah\blah.db4o";
The LINQPad code works fine if the web server isn't running.
What am I doing wrong?
When you open the db4o database it locks the database-file to prevent corruption. This means while your server is running, the database file is locked and no other process can access it. (Yes there's a way to disable this, but that will almost certainly corrupt the database)
Is you're webserver also running client server mode? If thats the case you could connect the the running db4o-instance. You also can first try to connect and only if you fail directly open the server?
If you're only using the embedded-client server in your ASP.NET application, you could change that for debugging-purposes to real client server. The ASP.NET only uses the embedded clients. But it lets you connect with LINQ-Pad.
Answer for the comment:
You need to open a fully server, which supports clients which connect over the network. For example:
// in your application
int PortNumber = 8888;
using(var server = Db4oClientServer.OpenServer("database.db4",PortNumber))
{
server.GrantAccess("debug-user","debug-pwd");
// application uses embedded client:
using(var container = server.OpenClient())
{
// your application does stuff
}
}
And then in LINQPad:
using(var client = Db4oClientServer.OpenClient("localhost",8888,"debug-user","debug-pwd"))
{
// do stuff
}
Related
I am struggling to achieve the following:
I have created a Java websocket server which publishes data every 1 sec.
In ASP MVC projest I would like to receive the data and save them in database only so no JS involved here.
I am able to read the websocket data using console application method below :
using WebSocketSharp;
List<string> readoutList = new List<string>();
public void receiveMessage() {
using (var ws = new WebSocket("ws://localhost:4567/socket/"))
{
ws.OnMessage += (sender, e) =>
{
if (e.IsText)
{
readoutList.Add(e.Data.ToString());
Console.WriteLine(e.Data.ToString());
}
};
ws.Connect();
Console.ReadKey(true);
}
}`
How to create a service of this kind within the ASP MVC project? I need some direction here.
MVC is stateless so you have to request back to the server to initiate the request (such as from a form post) but within the MVC controller response, you can kick off the request to the server (as an example using a different technology). The problem is there isn't necessarily a 1 to 1 translation in MVC; initiating the request using client-side JavaSvcript would be the option here. Initiating these types of requests within MVC may cause issues with timeouts too that you have to be aware of.
OR, you can consider a scheduled windows program or a windows service that is installed, which can manage itself and initiate the request every so often. I think this is the better option.
In my mvc webapplication, I am using webapi to connect to my database through odata.
Both MVC WebApp and Odata WebApi are on different ports of Azure cloud service webrole endpoints.
MVC WebApp - 80
Odata WebApi - 23900
When I do a odataproxy updateobject and call savechanges like
odataProxy.UpdateObject(xxx);
odataProxy.SaveChanges(System.Data.Services.Client.SaveChangesOptions.PatchOnUpdate);
I am getting a weird exception on savechanges method call - unable to connect to remote server.
When I tried to look into inner exceptions, It says that - No connection could be made as the target machine actively refused it 127.0.0.1:23901
So if you observe the port number in the exception, it shows as 23901 and obviously this error should come as the request is supposed to hit 23900.
I am facing this exception only when running on azure cloud solution. Whenever I do an update request, it fails by hitting a wrong port (added by 1).
Another thing is, apart from this updateobject -> savechanges, rest all works like fetching data and adding data.
FWIW, I've just run across this same thing. Darn near annoying and I really hope it doesn't happen in production. I'm surprised no other people have come across this though.
The idea of creating a new context, attaching the object(s) and calling SaveChanges really repulsed me because not only does it practically break all forms of testing, it causes debug code and production code to be fundamentally different.
I was however able to work around this problem in another way, by intercepting the request just before it goes out and using reflection to poke at some private fields in memory to "fix" the port number.
UPDATE: It's actually easier than this. We can intercept the request generation process with the BuildingRequest event. It goes something like this:
var context = new Context(baseUri);
context.BuildingRequest += (o, e) =>
{
FixPort(e);
};
Then the FixPort method just needs to test the port number and build a new Uri, attaching it back to the event args.
[Conditional("DEBUG")]
private static void FixPort(BuildingRequestEventArgs eventArgs)
{
int localPort = int.Parse(LOCAL_PORT);
if (eventArgs.RequestUri.Port != localPort)
{
var builder = new UriBuilder(eventArgs.RequestUri);
builder.Port = localPort;
eventArgs.RequestUri = builder.Uri;
}
}
Here's the original method using reflection and SendingRequest2, in case anyone is still interested.
First we create a context and attach a handler to the SendingRequest2 event:
var context = new Context(baseUri);
context.SendingRequest2 += (o, e) =>
{
FixPort(e.RequestMessage);
};
The FixPort method then handles rewriting the URL of the internal request, where LOCAL_PORT is the port you expect, in your case 23900:
[Conditional("DEBUG")]
private static void FixPort(IODataRequestMessage requestMessage)
{
var httpWebRequestMessage = requestMessage as HttpWebRequestMessage;
if (httpWebRequestMessage == null) return;
int localPort = int.Parse(LOCAL_PORT);
if (httpWebRequestMessage.HttpWebRequest.RequestUri.Port != localPort)
{
var builder = new UriBuilder(requestMessage.Url);
builder.Port = localPort;
var uriField = typeof (HttpWebRequest).GetField("_Uri",
BindingFlags.Instance | BindingFlags.NonPublic);
uriField.SetValue(httpWebRequestMessage.HttpWebRequest, builder.Uri);
}
}
I have found the root cause and a temporary workaround.
Cause:
When you hit WebApi through some port :23900 in Azure compute emulator and do an update or delete operation, somehow the last request is blocking the port and because of the port walking feature in Azure emulator, it is jumping to next port where there is no service available which is causing the issue.
Even this issue is found only in development emulators.
Temp Workaround:
Use a different proxy to attach to updated context object and then save from the other proxy object.
var odataProxy1 = xxx;
var obj = odataProxy1.xyz.FirstOrDefault();
obj.property1="abcd";
...//Other update assignments
var odataProxy2 = xxx;
odataProxy2.AttachTo("objEntitySet",obj);
odataProxy2.UpdateObject(obj)
odataProxy2.SaveChanges(ReplaceOrUpdate);
I'm brand new to using MVC, and I'm trying to use an initializer to initialize data into my DB when the application is first started. Here is what I've got in Global.asax.cs:
System.Data.Entity.Database.SetInitializer(new MyAppInitializer());
MyAppContext db = new MyAppContext();
db.Database.Initialize(true);
In Web.config, here is my connection string:
<connectionStrings>
<add name="MyAppContext"
connectionString="data source= MyServer; Integrated Security=True; database=MyDatabase"
providerName="System.Data.SqlClient"/>
This is using MS SQL 2008 R2. My Initializer looks like this:
public class MyAppInitializer : DropCreateDatabaseAlways<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
var organizations = new List<Organizations>
{
new Organizations { OrgName = "AT", OrgPhone = 5093333433, OrgOfficeLocation = "ITB", OrgPointOfContact = "Tony", OrgIsActive = 1 },
new Organizations { OrgName = "Libraries", OrgPhone = 5093331122, OrgOfficeLocation = "Holland-Terrell", OrgPointOfContact = "Herald", OrgIsActive = 1 }
};
organizations.ForEach(s => context.Organizations.Add(s));
context.SaveChanges();
I made sure I closed my connection to the server and database in SQL Server Management Studio, but multiple people have access to this DB, although none should be using it right now. How can I get it so I can initialize this data in my DB? Thanks!
Edit: I've already got the DB created on the server, but it is completely empty (no tables, procedures, etc). Would this cause an issue?
I faced a similar issue today when using MVC codefirst. After 20 mins of trying out various stuff I noticed that, the "Server Explorer" tab in Visual Studio had a connection open to my database. After I "closed" the connection in the server explorer tab of visual studio, the code was able to run and automatically recreate the database.
In SSMS run something like this...
USE master -- be sure that you're not on MYDB
ALTER DATABASE MYDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE MYDB;
As described by Vardhini... close DB connection in Server Explorer.
In the SSMS "Delete" window make sure that "Close existing connections" is checked.
Closing all existing connections of the database in visual studio server explorer and SQLManagement studio solved the problem for me.
My observations are:
Cannot be logged in to application
Cannot be connected to db with Server Explorer
Cannot be connected with SSMS
Then the application rebuild DB even when Database.SetInitializer<DbContext>(new DbInitializer()); is in public DbContext(); - NOT as other answears stand to put it into Application_Start();
Can someone please help me fix my connection string? I am an absolute beginner using the MS SQL Management Studio but I am an experienced C# programmer. I am trying to figure out how to connect to a local database on my PC. I just installed SQL server 2012 Express today and I created a table with one row of data. I am trying to access that table from a C# program. I've been looking for help calling a stored procedure (with no parameters) and it seems like I am doing everything right, but I get an exception error "Could not find stored procedure 'GetCustomers'." I have also tried changing my the procedure name to "dbo.GetCustomers" and also "SqlTest.dbo.GetCustomers" and also "SqlTest.GetCustomers", but nothing seems to work. Clearly I am not connecting to my database correctly. I've been working on this for 4 hours now so it's time for me to stop and find help. I think all I need is a good connection string and the proper syntax for the procedure.
Connect c = new Connect();
if(c.MakeConnection())
{
try
{
DataSet data = new DataSet();
SqlDataAdapter adaptor = new SqlDataAdapter();
//changed to use stored procedure
adaptor.SelectCommand = new SqlCommand("GetCustomers", c.MyConnect);
adaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
//adaptor.SelectCommand.ExecuteNonQuery();//this throws an exception.
adaptor.Fill(data);//this throws an exception.
}
catch (Exception e)
{
Logger.WriteMessage(e.Message);
}
finally
{
c.CloseConnection();
}
My connection class contains the following:
string connection = Properties.Settings.Default.DatabaseConnectString;
sqlConnection = new SqlConnection(connection);
sqlConnection.Open();
Connection string I have tried which seem to connect OK:
Server=(localdb)\v11.0;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Integrated Security=true;
My Database name is SqlTest. I have tried several variations in my connection string, but most of them throw a logon failed exception error. I verified that my windows user ID has admin privileges for the database.
Connection strings I have tried which cive me logon errors:
Server=(localdb)\v11.0;Initial Catalog=SqlTest;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Initial Catalog=dbo;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Integrated Security=true;
I guess all I needed was some sleep. ;-)
I needed to set all of my SQL server services to Automatic. For some reason, they were set to manual, and so they were not started.
Then, I also needed to set the correct server name in my connection string. This is the same server name that is used to logon when starting SQL Server Management Studio. Here is a connection string that connects and accesses the correct database and table:
Server=RAPHAEL\SQLEXPRESS;Database=SqlTest;Trusted_Connection=Yes;
Is it possible to connect to a remote database from my flex4.5 Mobile application ?
I am trying to develop a flex 4.5 mobile application and my data is in Oracle Database.
I choose Java as my back end technology. How can I call the java services from flex.
I wanted my mobile application to run on iOS devices.
Yes. You can connect to any database, as long as that database can be connected to via php or Java (possibly other server-side languages as well). It uses a remote call, similiar to Ajax (but faster).
You can use a RemoteObject component. RemoteObject components use the AMF protocol to send and receive data, while WebService and HTTPService components use the HTTP protocol. AMF is significantly faster than HTTP.
On the Flex Side:
<mx:RemoteObject id="Hello" destination="roDest">
<mx:method name="getHelloData"/>
</mx:RemoteObject>
On the Java side:
...
public void getHelloData() {
try{
InitialContext ctx = new InitialContext();
Object obj = ctx.lookup("/Hello");
HelloHome ejbHome = (HelloHome)
PortableRemoteObject.narrow(obj, HelloHome.class);
HelloObject ejbObject = ejbHome.create();
String message = ejbObject.sayHello();
}
catch (Exception e);
}
...
The code examples were taken from:
http://help.adobe.com/en_US/flex/accessingdata/WS2db454920e96a9e51e63e3d11c0bf69084-7fda.html#WS2db454920e96a9e51e63e3d11c0bf66651-7fd7