Visual Studio 2012 stackoverflow after entity framework connectionstring missing - c#

I'm working in VS2012 with update 1 on a win2k8 r2 64 bit.
Within a simple class library application i do Add > New Item> ADO.NET Entity Data Model
I select a SQL Server on the network and select the database and add a single table. The table gets added, and I can access it as a class name in my code.
The issue: When I do anything with backend DB, the app using my library crashes with stackoverflow error (no exception). For instance this will crash: var logs =_db_context.LOGs.ToList();
Any ideas?
EDIT: The same projects were working in VS2010 on the same machine. This only started happening when I upgraded to VS2012 which upgraded entity framework as well. Also worth mentioning that if I remove the code the access the database, the app runs just fine.
Also, removing and re-adding .edmx does not help, neither does clean/re-build or restart VS.
EDIT2: After debugging I've noticed when the line LogServerEntities context = new LogServerEntities() is reached, and I try to expand the context variable from "Locals" VS ends debugging saying Managed (v4.0.30319)' has exited with code -2146233082 (0x80131506).

The class library was actually a custom trace listener and looked like following. When I commented the FirstChanceHandler in the constructor, the exception actually made its way to the console output: an assembly reference (System.Management.Automation) was failing to load. I did not really need that assembly and simply removed it, and the stackoverflow error (which I'm guessing is a bug) went away.
public Listener()
{
AppDomain.CurrentDomain.FirstChanceException += FirstChanceHandler;
}
public void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e)
{
WriteException(e.Exception);
}
public void WriteException(Exception e)
{
string app_identity = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;
string server_name = System.Environment.MachineName;
using (LogServerEntities context = new LogServerEntities())
{
LOG log = new LOG();
log.DATE = DateTime.Now;
log.THREAD = Thread.CurrentThread.Name;
log.MESSAGE = e.Message;
log.LOGGER = string.Format("{0} {1}", app_identity, server_name);
log.LEVEL = Level.Exception.ToString();
log.EXCEPTION = e.GetType().FullName;
var web_exception = e as WebException;
if (web_exception != null)
{
if (web_exception.Status == WebExceptionStatus.ProtocolError)
{
var response = web_exception.Response as HttpWebResponse;
if (response != null)
log.HTTP_RESPONSE_CODE = ((int)response.StatusCode).ToString();
else
log.HTTP_STATUS = web_exception.Status.ToString();
}
else
{
log.HTTP_STATUS = web_exception.Status.ToString();
}
}
context.LOGs.Add(log);
context.SaveChanges();
}
}

Related

How to download data from Firebase?

I'm attempting to retrieve some data from a Firebase database. I've been able to do it fine in the past, but there's something wrong with my GetValueAsync() code below. When debugging it gets stuck at the "await reference.Database" line, but I'm not sure what I'm doing wrong. When running without debugging, none of the information is ever retrieved.
I'm uncertain if the problem is with the path, or the await/async function. Debugging shows that loggedUserId is storing the value before referencing it in the next line, but the rest of the function never completes or faults. The application compiles but I'm never able to capture any info from the snapshot.
The format of my database is "users" -> 78cVqzA8qNTNigsao3VvdnM0Qol2 (Which is correct) -> (several data pairs such as level : 1, lives : 3, etc)
public static async void GetUserData()
{
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl("https://narwhaltrivia.firebaseio.com/");
if (app.Options.DatabaseUrl != null) app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
DatabaseReference reference = Firebase.Database.FirebaseDatabase.DefaultInstance.RootReference;
loggedUserId = FirebaseAuth.DefaultInstance.CurrentUser.UserId;
await reference.Database.GetReference("users").Child(loggedUserId).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Error retrieving user data");
return;
}
if (task.IsCompleted)
{
DataSnapshot userSnapshot = task.Result;
loggedEmail = userSnapshot.Child("email").GetRawJsonValue();
loggedCurrentScore = userSnapshot.Child("currentScore").GetRawJsonValue();
loggedLevel = userSnapshot.Child("level").GetRawJsonValue();
loggedLives = userSnapshot.Child("lives").GetRawJsonValue();
loggedRound = userSnapshot.Child("round").GetRawJsonValue();
loggedTotalScore = userSnapshot.Child("totalScore").GetRawJsonValue();
return;
}
});
}

System.AccessViolationException in C# interface to Swi-prolog

I am new here and I hope that i will find a solution for my problem. The background of the problem is as follows:
I am trying to build an expert system that constitute a C# front-end which is interacting with Swi-prolog.
I have downloaded SwiPlCs.dll (A CSharp class library to connect .NET languages with Swi-Prolog)
And added a reference to it in a Visual Studio project(Win form app) that I have created to test if I can query prolog from c# (I followed the example used in the documentation found here).
It worked fine.
Then, in a more complicated scenario, I have built a WCF service that will act as an intermediary layer between Swi-Prolog and C# client application (it consumes the service).
The service is hosted in IIS 7.0.
For the sake of simplicity, lets say my service contains three methods.
The first method initializes the prolog engine, consults prolog source file then queries the file.
The second method performs another query.
The third method calls PlCleanup().
Method#1:
public void LaunchAssessment()
{
Dictionary<string, string> questions = new Dictionary<string, string>();
#region : Querying prolog using SwiPlCs
try
{
if (!PlEngine.IsInitialized)
{
String[] param = { "-q" };
PlEngine.Initialize(param);
PlQuery.PlCall("consult('D:/My FYP Work/initialAssessment')");
using (var q = new PlQuery("go(X, Y)"))
{
foreach (PlQueryVariables v in q.SolutionVariables)
{
questions.Add("name", v["X"].ToString());
questions.Add("age", v["Y"].ToString());
}
}
}
}
catch (SbsSW.SwiPlCs.Exceptions.PlException exp)
{
throw new FaultException<PrologFault>(new PrologFault(exp.Source), exp.MessagePl);
}
#endregion
Callback.PoseQuestion(questions, ResponseType.None);
}
Method#2:
public void DetermineAgeGroup(int age)
{
//Determine age group
string age_group = string.Empty;
try
{
using (var query = new PlQuery("age_group(" + age + ", G)"))
{
foreach (PlQueryVariables v in query.SolutionVariables)
age_group += v["G"].ToString();
}
}
catch (SbsSW.SwiPlCs.Exceptions.PlException exp)
{
throw new FaultException<PrologFault>(new PrologFault(exp.Source), exp.MessagePl);
}
//Check whether age_group is found or not
if (string.IsNullOrEmpty(age_group))
{
throw new FaultException<NoSolutionFoundFault>(new NoSolutionFoundFault("No solution found"), "Age specified exceeds the diagnosis range!");
}
else
{
Callback.RespondToUser(age_group, ResponseType.Age);
}
}
Method#3:
public void QuitProlog()
{
if (PlEngine.IsInitialized)
{
PlEngine.PlCleanup();
}
}
The client invokes the first method just fine and a result of the first query is successfully returned. When client tries to call the second method an exception is thrown with message (attempted to read or write protected memory) which causes the application to freeze. I checked the event viewer and this is what I get:
Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at SbsSW.SwiPlCs.SafeNativeMethods.PL_new_term_ref()
at SbsSW.SwiPlCs.PlQuery..ctor(System.String, System.String)
at SbsSW.SwiPlCs.PlQuery..ctor(System.String)
at PrologQueryService.PrologQueryService.DetermineAgeGroup(Int32)
I also tried to use the interface for a .NET project.
Looking in the official repository of the CSharp interface to SWI-Prolog I noticed that the project is very old and the latest updates do not seem included in the binaries available in the download page of the official website.
Then I did the following steps:
The contrib repository dedicated to .NET indicates that the compatible SWI-Prolog version (at the time of writing) is "8.0.3-1" (look in the README file).
-> Then I uninstalled from my computer the latest stable and installed the indicated one. I got it from the full list of downloads of the old versions at this link.
I cloned the SWI-Prolog/contrib-swiplcs repository, unloaded the incompatible projects from the solution, in my case, since I don't use Visual Studio.
-> I set the target framework to Net Framework 4.8 and recompiled it (you can also do this with standard NET). Beware of some pragma directives defined in the old project file (For example I re-defined _PL_X64 variable via code.
I brought the main unit test methods into a new project with xUnit wiht the appropriate changes.
I set the target to x64, recompiled and rebuilt the tests and the "hello world" example.
It worked!
I was able to use SWI-Prolog both for Net 4.8 and in other Net Core applications (if you make the needed changes in order to target the Net Standard). You should not have any problem in both cases).
This is my fork as a preliminary example.
Finally, I can load a *.pl Prolog file with a program in my C# application and use it to evaluate some business logic rules (example with boolean answer [Permitted/Not-Permitted]):
[Fact]
public void ShouldLoadAProgramAndUseIt()
{
var pathValues = Environment.GetEnvironmentVariable("PATH");
pathValues += #";C:\Program Files\swipl\bin";
Environment.SetEnvironmentVariable("PATH", pathValues);
// Positioning to project folder
var currentDirectory = Directory.GetCurrentDirectory().Split('\\').ToList();
currentDirectory.RemoveAll(r => currentDirectory.ToArray().Reverse().Take(3).Contains(r));
var basePath = currentDirectory.Aggregate((c1, c2) => $"{c1}\\{c2}");
var filePath = $"{basePath}\\prolog_examples\\exec_checker.pl";
String[] param = { "-q", "-f", filePath };
PlEngine.Initialize(param);
try
{
var query = "exutable('2020-08-15',[('monthly', ['2019-12-30', '2020-03-10'])])";
_testOutputHelper.WriteLine($"Query: {query}");
using (var q = new PlQuery(query))
{
var booleanAnswer = q.NextSolution();
_testOutputHelper.WriteLine($"Answer: {booleanAnswer}");
Assert.True(booleanAnswer);
}
query = "exutable('2020-08-15',[('daily', ['2019-12-30', '2020-08-15'])])";
_testOutputHelper.WriteLine($"Query: {query}");
using (var q = new PlQuery(query))
{
var booleanAnswer = q.NextSolution();
_testOutputHelper.WriteLine($"Answer: {booleanAnswer}");
Assert.False(booleanAnswer);
}
}
finally
{
PlEngine.PlCleanup();
}
}
Try to close engine in the end of the first method and initialize it in the second again.
You can check this as the answer to the question unless you object.

How to use Clutch for debugging SQL statements executed by the Entity Framework?

I am very new to the Entity Framework. Tried to save an object and it fails with the message
error in saving entities which do not make foreign key properties available
As something wrong happens when EF tries writing to the database, I wanted to see the actual query it is trying to execute. I am not yet using EF 6, so I can't use context.Database.Log. Some search told me that there is a library called Clutch Diagnostics which will help me.
I installed it from NuGet and set it up as described in this blog post. Basically, it involved adding the methods
public void CommandFailed(DbTracingContext context)
{
Debug.WriteLine("\nFAILED\n " + context.Command.CommandText);
// or Trace.WriteLine("\nFAILED\n " + context.Command.CommandText);
}
public void CommandExecuted(DbTracingContext context)
{
Debug.WriteLine("\nExecuted\n " + context.Command.CommandText);
// or Trace.WriteLine("\nExecuted\n " + context.Command.CommandText);
}
to a class which implements the IDbTracingListener interface, and adding
// Enable Tracing queries
DbTracing.Enable();
// Adding the listener (implementation of IDbTracingListener)
DbTracing.AddListener(new DbTracingListener());
to the application start method in Global.asax.
I expected to now see the SQL queries in my Debug window. But instead I got
What am I doing wrong? Did I miss something? Are my expectations wrong? Is the debug output the wrong place to look for the query? Is the listener meant to work for saving objects to the database?
My method for saving to the database is very simple,
if (keyword.ExtractedKeywords_ID == 0)
{
context.ExtractedKeywords.Add(keyword);
}
else
{
ExtractedKeyword dbEntry = context.ExtractedKeywords.Find(keyword.ExtractedKeywords_ID);
if (dbEntry != null)
{
dbEntry.CorrectSpelling = keyword.CorrectSpelling;
dbEntry.Embryonen = keyword.Embryonen;
dbEntry.ExcelNumber = keyword.ExcelNumber;
dbEntry.IsCell = keyword.IsCell;
dbEntry.IsOrgan = keyword.IsOrgan;
dbEntry.IsRecombinase = keyword.IsRecombinase;
dbEntry.IsReporter = keyword.IsReporter;
dbEntry.IsResearchTopic = keyword.IsResearchTopic;
dbEntry.ModificationStatus = keyword.ModificationStatus;
dbEntry.OriginalSpelling = keyword.OriginalSpelling;
dbEntry.Synonym = keyword.Synonym;
}
}
context.SaveChanges();
I have only tried it with brand-new objects (the if part gets executed), because I don't yet have any entries in the database table for going into the else part.

"Access Denied" error whilst programmatically activating a feature in SharePoint 2010

I am new to SharePoint so I am following some Microsoft Learning Guides. One exercise is to create a feature reciever to modify the Web.Config file.
I detect the feature being activated or deactivated and call the following routine with the appropriate flag.
void setProliferationFlag(bool status)
{
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://SharePoint"));
try
{
SPWebConfigModification mySetting = null;
if (status)
{
mySetting = new SPWebConfigModification();
mySetting.Path = "configuration/appSettings";
mySetting.Name = "add [#key='preventProliferation'] [#value='1']";
mySetting.Sequence = 0;
mySetting.Owner = "Lab05Owner";
mySetting.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
mySetting.Value = "<add key='preventProliferation' value='1' />";
webApp.WebConfigModifications.Add(mySetting);
}
else
{
foreach (SPWebConfigModification modification in
webApp.WebConfigModifications)
{
if (modification.Owner == "Lab05Owner")
{
modification.Value = "<add key='preventProliferation' value='0' />";
}
}
}
webApp.Update();
webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
catch
{
}
The event receivers work fine. When I activate the feature this code is run, but when it reaches the "webApp.Update()" line it fails with an "Access Denied" error. No other detils on the error. I am not sure to what the access is denied.
I am running in my development environment on my laptop. This is a Sharepoint Server 2010 installation on Window 7.
Regards Tim
Most likely you will need administrative access. Look at the SPSecurity.RunWithElevatedPrivileges method which allows you to execute such actions within the system account's security context.
You will have to run the whole code elevated, that is including opening the SPWebApplication object. You method will then look like this:
void SetProliferationFlag(…)
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
// … your code goes here …
});
}
Please also note, it's a very bad practice to have empty catch clauses in your code. Do always handle all exceptions, at least by logging them and rethrowing.

Out Of Context Variables In Visual Studio 2010 Debugger

I am having a very odd problem with local variables being out of context in the Visual Studio 2010 debugger for a C# console application targeting .NET 4.0. I've searched for other similar questions on SO, but while some have the same symptoms, none seem to apply directly to this problem (they all appear to have other root causes).
The problem is that for some variables (but not all) I do not get a tooltip with their value, they do not appear in the Locals window, and I get "The name 'xyz' does not exist in the current context" if I add them to the Watch window. It appears to affect some variables but not others, and I can't figure out a pattern (it doesn't seem to be based on member vs. local, class vs. struct, or any other differentiator). I've restarted my computer and Visual Studio, verified I'm in a clean Debug build, made sure the debugging frame is correct, made sure to refresh the variables in the watch screen, and attempted various spells and incantations.
I've included a screenshoot below (bigger version at http://i.stack.imgur.com/JTFBT.png).
Any thoughts?
EDIT:
Adding some additional information:
The problem is repeatable. The exact same variables either work or don't work, even after completely shutting down and restarting Visual Studio. This leads me to believe there's actually something systematic going wrong rather than just memory corruption or something.
I've also discovered that it appears to be related to the try-catch block. If I position the breakpoint outside the try statement I can see any of the in-scope variables normally. As soon as the execution point enters the try statement all the variables outside the try block become inaccessible and I can only access the ones inside the try statement. It's almost as though the debugger is treating the try block as a separate method (though you can see the code/compiler still does have access to in-scope variables). Has anyone seen this behavior before?
ANOTHER EDIT:
I (partially) take back what I said about the try-catch being suspect - it appears that in this portion of the code the debugger exhibits this odd taking stuff out of context for any enclosing block. For example, if I set a breakpoint directly inside the foreach statement in the screenshot I can see the "port" variable value on each iteration, but none of the variables outside the foreach statement (which disappear as soon as I enter the foreach block). Then as soon as you enter the try block, the "port" variable suddenly goes away. This is getting really weird.
Also, as requested, the code for the entire method is below.
private void ConfigureAnnouncerSockets(XDocument configDocument)
{
XElement socketsElement = configDocument.XPathSelectElement("/Configuration/Network/AnnouncerSockets");
bool useDefault = true;
if (socketsElement != null)
{
//Use the default announcers? (they will be added at the end)
XAttribute defaultAttribute = socketsElement.Attribute("useDefault");
if (defaultAttribute != null)
{
useDefault = Convert.ToBoolean(defaultAttribute);
}
//Get the default frequency
int defaultFrequency = Announcer.DefaultFrequency;
XAttribute frequencyAttribute = socketsElement.Attribute("frequency");
if (frequencyAttribute != null)
{
defaultFrequency = Convert.ToInt32(frequencyAttribute.Value);
}
//Get all sockets
foreach (XElement socketElement in socketsElement.XPathSelectElements("./Socket"))
{
//Get the address
IPAddress address = IPAddress.Broadcast;
string addressAttribute = (string)socketElement.Attribute("address");
if(!GetAddress(addressAttribute, ref address, true))
{
Intelliplex.Log.Warn("Invalid announcer socket address: " + addressAttribute);
continue;
}
//Get the local address
IPAddress localAddress = null;
string localAddressAttribute = (string)socketElement.Attribute("localAddress");
if(!GetAddress(localAddressAttribute, ref localAddress, false))
{
Intelliplex.Log.Warn("Invalid announcer socket local address: " + localAddressAttribute);
continue;
}
//Get the port(s)
List<int> ports = new List<int>();
string[] ranges = ((string)socketElement.Attribute("port")).Split(new[] { ',' });
foreach (string range in ranges)
{
string[] portPair = range.Split(new[] { '-' });
int firstPort = Convert.ToInt32(portPair[0]);
int lastPort = portPair.Length > 1 ? Convert.ToInt32(portPair[1]) : firstPort;
do
{
ports.Add(firstPort);
} while (++firstPort <= lastPort);
}
//Get the local port
int localPort = socketElement.Attribute("localPort") != null
? Convert.ToInt32((string)socketElement.Attribute("localPort")) : 0;
//Get the frequency
int frequency = socketElement.Attribute("frequency") != null
? Convert.ToInt32((string)socketElement.Attribute("frequency")) : defaultFrequency;
//Create the socket(s) and add it/them to the manager
foreach (int port in ports)
{
try
{
IPEndPoint endPoint = new IPEndPoint(address, port);
IPEndPoint localEndPoint = localAddress == null
? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(localAddress, localPort);
Announcer socket = new Announcer(frequency, endPoint, localEndPoint);
AnnouncerSockets.Add(socket);
}
catch (Exception ex)
{
Intelliplex.Log.Warn("Could not add announcer socket: " + ex.Message);
}
}
}
}
//Add default announcement sockets?
if (useDefault)
{
ConfigureDefaultAnnouncerSockets();
}
}
So it turns out this is related to a bug in PostSharp. I had been using PostSharp but removed all aspects from my code and ensured that none were applied. I also verified with Reflector that the methods were intact in the assembly. However, it appears simply referencing PostSharp triggers some kind of manipulation of the debugging symbols that causes this problem. A (little) more information can be found here:
http://www.sharpcrafters.com/forum/Topic5794-21-1.aspx#bm7927
Also, in the release notes for the latest PostSharp hotfix states one of the fixed issues in hotfix 2.1.5.6 is "Debugging symbols: local variable symbols lost in implicit iterators."
When I installed the latest and greatest PostSharp the problem went away and the universe returned to normal. Hopefully this question/answer will help anyone else using PostSharp who stumbles on this odd behavior before the next official PostSharp release. Make sure you're on hotfix 2.1.5.6 or greater (given the severity of the bug, this probably should have been an actual release).
Thanks for all the help everyone.

Categories