Linq to SQL Bombing Out on DataContext - c#

For some reason my code just decided to stop working after doing a build and not sure what the issue is.
public class clsSaveError
{
public clsSendEmail.clsSendEmail SendEmail = new clsSendEmail.clsSendEmail();
public clsSettings.clsSEttings Settings = new clsSettings.clsSEttings();
public clsLinqToSQL.K12DataClassesDataContext dbContext = new clsLinqToSQL.K12DataClassesDataContext();
public void InsertErrorIntoDatabase(string monsterID, string dbtable, string errormessage, string stacktrace, EventLog log)
{
clsLinqToSQL.K12DataClassesDataContext dbContext = new clsLinqToSQL.K12DataClassesDataContext();
try
{
dbContext.tblErrors err = new dbContext.tblErrors();
err.monsterid = monsterID;
err.dbtable = dbtable;
err.errormessage = errormessage;
err.stacktrace = stacktrace;
dbContext.tblErrors.Insertonsubmit(err);
dbContext.SubmitChanges();
}
catch (Exception except)
{
//write the error to the event log
log.WriteEntry("ERROR! Unable to write error to database. Here are the details:" + "\n" +
"Exception Message: " + except.Message + "\n" +
"Exception Stacktrace: " + except.StackTrace + "\n" +
"Database Error Details: " + "\n" +
"Monster ID: " + monsterID + "\n" +
"Database Table: " + "\n" +
"Error Message: " + "\n" +
"Stacktrace: " + stacktrace);
SendEmail.SendEmail(Settings.mailport, Settings.mailhost, Settings.mailtimeout, Settings.mailusername, Settings.mailpassword, Settings.mailfrom, Settings.mailto, "Database Error - Unable to update Error Log", "Message: " + except.Message + "\n" + "Stacktrace: " + except.StackTrace);
}
}
}
The error is:
'clsSaveError.clsSaveError.dbContext' is a 'field' but is used like a 'type'
I know this is a generic error but I am not sure why it is occurring now. Thanks for the input!

You're declaring a variable here:
clsLinqToSQL.K12DataClassesDataContext dbContext = new clsLinqToSQL.K12DataClassesDataContext();
Then trying to use that variable as a type here:
dbContext.tblErrors err = new dbContext.tblErrors();
If dbContext is the name of a type, don't declare variables by the same name. If it isn't the name of a type, then I have no idea what the above line of code is trying to do.
Your type names and variable names are entirely breaking C# conventions, making the code difficult to read. For example:
public clsSendEmail.clsSendEmail SendEmail = new clsSendEmail.clsSendEmail();
Your type names are lowercase, and your variable is uppercase. This is backward from standard convention. Prepending cls to every type name isn't helping.

Related

StackOverflow in WCF caused by R.Net

Good Day,
i am trying to write an R code in .net to run as a WCF function. this function is suppose to import a csv file to MSSQL using R using .net code.
I am getting a stackoverflow error when i try to reference the odbc library over wcf, however if i try to run the function using debug instance it passes that point.
public string R_to_MSSQL_Server(string data, string Server, string Database,string Tablename)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null, true, rinit);
StringBuilder Data = new StringBuilder();
Data.Append(data);
string filepath = Path.Combine(Path.GetTempPath(), "RTable.csv");
//"UID= Tester;" +
//"PWD= rstudioapi::askForPassword(\"password\"); " +
try
{
UploadCSV(Data);
filepath = PathCleaning(filepath);
engine.Evaluate("Data <- read.csv(file<- '" + filepath + "', heade= TRUE, sep=',')");
engine.Evaluate("Table <- data.frame(Data)");
engine.Evaluate("connectionString <- ' " +
"driver={SQL Server}; " +
"server= "+ Server + "; " +
"database=" + Database + ";" +
"UID= Tester;" +
"PWD= rstudioapi::askForPassword(\"password\"); " +
"'");
engine.Evaluate("library(odbc)");
engine.Evaluate("library(healthcareai)");
engine.Evaluate("con<- DBI::dbConnect(odbc::odbc(),.connection_string=connectionString)");
engine.Evaluate("DBI::dbwriteTable(conn=con," + Tablename + " , Table)");
return "Completed successfully";
}
catch( Exception x)
{
return "Fail to complete" + x;
}
}
the error when i run it through WCF hits at "engine.evaluate("library(odbc)");"
This is where its being called by another machine accessing it through wcf.
static void Main(string[] args)
{
MainServiceClient client = new MainServiceClient();
string tablename = "Test Table";
string Table = "";
string Pkey ="Name";
Table=File.ReadAllText(#"\\lonvmfs02\Home\kr.williams\TestTable2.csv");
string query = client.R_to_MSSQL_Server(Table, "stage04", "CWDataSets", "Tester");
this is the error thats being thrown inside the WCF Machine ( W3wp debugging ).
System.StackOverflowException
HResult=0x800703E9
Source=
StackTrace:
this is all the exception details give.
how do it increase the size of the stack / get around this problem?
Thanks

Object not set to an instance of an object in sql query, null reference exception

In this specific case I am getting null reference exception, and I cant solve it.
public class Tiket
{
private Korisnik korisnik;
public Korisnik Korisnik
{
get { if (korisnik == null)
{
korisnik = new Korisnik();
}
return korisnik; }
set { korisnik = value; }
}
}
Inside form I am taking value inserted in textbox and sending it to method which deal with database(its much more complex but I am trying to make it simple):
Tiket t = new Tiket();
t.Korisnik.Ime = txtImeKorisnika.Text;
thatMethod(t);
So above, I am not getting null reference exception while assigning value to t.Korisnik.Ime, but Inside method I am getting one:
string upit = "SELECT * FROM " + Tiket + " " + " WHERE " + t.Korisnik.Ime;
extra question connected to this topic:
I am having same problem while trying to add values to these fields from database which are also class properties inside Tiket.
tikeet.Korisnik.JMBG = red[5].ToString();
tikeet.Radnik.SifraRadnika = Convert.ToInt32(red[6]);
I know why is this happening but I dont know how to initialize Korisnik, Radnik here.
EDIT: I hope this helps now, so You can help me !
I have client server app and I am sending Tiket to Server..than its sent as OpstiDomenskiObjekat(instead of Tiket) to method I have problem now.
OpstiDomenskiObjekat is interface, so I could have one or few methods for many similar things I need.
public List<OpstiDomenskiObjekat> vratiZaUslovJedanPlus(OpstiDomenskiObjekat odo)
{
string upit = "SELECT * FROM " + odo.tabela + " " + " WHERE " + odo.uslovJedan;
OleDbDataReader citac = null;
OleDbCommand komanda = new OleDbCommand(upit, konekcija, transakcija);
try
{
citac = komanda.ExecuteReader(); // **here is exception thrown**
DataTable tabela = new DataTable();
tabela.Load(citac);
List<OpstiDomenskiObjekat> lista = new List<OpstiDomenskiObjekat>();
foreach (DataRow red in tabela.Rows)
{
OpstiDomenskiObjekat pom = odo.napuni(red);
lista.Add(pom);
}
return lista;
}
catch (Exception ex)
{
throw ex;
}
//this is implementation in class Tiket
public string uslovJedan
{
get
{
return Korisnik.Ime;
}
}
//this should happen after method, I will have List as I needed
List<Tiket> lista = Broker.dajSesiju().vratiZaUslovJedanPlus(odo).OfType<Tiket>().ToList<Tiket>();
return lista;
Connection, transaction etc.. its all somewhere else, but It all works, I promise :)
The + operator in this case is a string concatenation operator. Ticket is the name of your class and its not clear whether you have a property with that same name. If you do have a property by that name,
string upit = "SELECT * FROM " + Tiket + " " + " WHERE " + t.Korisnik.Ime;
it is possible that the above line is failing because the Tiket property is null. And also, it's ToString() might not be valid for the FROM clause of a query.
Update
As you can see, it didn't compile for me at all. When I wrote a property with the same name. It compiled, and constructed the string, inserting a null character where Ticket was.
The second screenshot shows what happens if it was a property.
Your string is still constructed in that case and you will get an invalid query at the line string upit = "SELECT * FROM " + Tiket + " " + " WHERE " + t.Korisnik.Ime; which is probably causing your issues. Please update with a screenshot of where the exception is being thrown.

{C# - Logging} Application_BeginRequest() Object reference not set to an instance of an object [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Hey guys I have a web application and some times when I publish it to the server it drives me crazy cause it's not loading. It returns an error of System.NullReferenceException: Object reference not set to an instance of an object and it hits on Global.asax Application_BeginRequest (I tried Application_AuthenticateRequest - same result).
Global.asax Application_BeginRequest code:
try
{
HttpRequest request = HttpContext.Current.Request;
string header = request.Headers["X-MicrosoftAjax"];
if(header != "Delta=true")
{
string path = "~/Logs/TrafficAnalytics.txt";
string txt = "Visit from: " + ClientInfo.GetClientIP() + " at: " + ClientInfo.GetClientLastRoute + ". Traceback below:\r\nIP Address: " + ClientInfo.GetClientIP() + "\r\nHostname: " + ClientInfo.GetClientHostname + "\r\nCoordinates: " + ClientInfo.GetClientCoordinates() + "\r\nLocation: " + ClientInfo.GetClientLocation() + "\r\nOS & Browser Info: " + ClientInfo.GetClientBrowserOs + "\r\nBrowser Info: " + ClientInfo.GetClientBrowserInfo() + "\r\nOperating System: " + ClientInfo.GetClientOsInfo() + "\r\nISP: " + ClientInfo.GetClientIsp();
Logger.Create(path, txt);
}
}
catch (Exception ex)
{
HttpContext con = HttpContext.Current;
HttpException code = ex as HttpException;
string bos = Request.UserAgent;
string path = "~/Logs/ErrorReports.txt";
string txt = "URL: " + con.Request.Url.ToString() + "\r\nError Message: " + ex.Message + "\r\nAnalyzed Message: " + ex.ToString() + "\r\nError Code: " + code.GetHttpCode().ToString() + "\r\nIpAddressTraceResult: " + ClientInfo.GetClientIP() + "\r\nOS & Browser Info: " + bos;
Logger.Create(path, txt);
}
Logger.cs source:
using System;
using System.IO;
using System.Web;
public class Logger
{
public static void Create(string p, string t)
{
FileInfo path = new FileInfo(HttpContext.Current.Server.MapPath(p));
string txt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + " :::::::::: " + t + "\r\n------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------";
path.IsReadOnly = false;
StreamWriter sw = new StreamWriter(path.ToString(), true);
sw.WriteLine(txt);
sw.Flush();
sw.Close();
}
}
The error is happening only sometimes it usualy works so I don't know what am I doing wrong. Thanks for all responses...
Well, the best answer is to debug or gather a full stack trace to find which specific line is throwing.
One obvious issue - what if the exception you're catching isn't an HttpException? For example, what if your logging code had an exception in StreamWriter's constructor? It can throw seven different exceptions, none of which are HttpExceptions.
You'd end up in the catch, the value of code would be null because the exception couldn't be cast to an HttpException, and code.GetHttpCode() would throw a NullReferenceException.

VB / C# Query Event Logs from Domain Controller by looking at username in EventData

I am attempting to have specific event logs that contain a username that are Security Audit Failures from a DC, in powershell I can easily do this with something like this:
Where the variables would be something like: $DC = "MyDomainController" and $user = "jdoe"
Get-WinEvent -ComputerName $DC -FilterHashtable #{Logname='Security';Keywords='4503599627370496';Data=$user} -MaxEvents 4 | Format-List -Property ID, TimeCreated, MachineName, Message
This would pull 4 event logs that are security audit failures with the person's username from a DC I am looking at, however I have been unable to find or reproduce this behavior to something similar in vb.net, I have been searching pages for the last few days and coming up with a lot of writing and pulling all logs on DC's but not filtering down, any help or guidance would be great, thank you!
I was able to find the answer to this by looking at custom log query's by using xpath, I did the following in C# but the same can be applied in VB, Domaincontroller.text = The domain controller your looking up: Username.text = The AD username to lookup Statustextbox = I have all the logs go to a textbox to read but you could do something like console.writeline
private void LookupLogs_Click(object sender, EventArgs e)
{
Statustextbox.Clear();
string query = "<QueryList>" +
" <Query Id=\"0\" Path=\"Security\">" +
" <Select Path=\"Security\">" +
" *[System[band(Keywords,4503599627370496)]] and *[EventData[Data[#Name='TargetUserName'] and (Data='" + Username.Text + "')]]" +
" </Select>" +
" </Query>" +
"</QueryList>";
EventLogSession session = new EventLogSession(DomainController.Text);
EventLogQuery evntquery = new EventLogQuery("Security", PathType.LogName, query);
evntquery.Session = session;
try
{
EventLogReader logreader = new EventLogReader(evntquery);
DisplayEventAndLogInformation(logreader);
}
catch (Exception ex)
{
MessageBox.Show("An exception occured: " + ex.Message);
}
}
private void DisplayEventAndLogInformation(EventLogReader logReader)
{
for (EventRecord eventInstance = logReader.ReadEvent();
null != eventInstance; eventInstance = logReader.ReadEvent())
{
Statustextbox.AppendText(Environment.NewLine + Environment.NewLine);
Statustextbox.AppendText("---------------------------------------------------------------------------------------------------------------------------------------------------------------" + Environment.NewLine);
Statustextbox.AppendText("Event ID: " + eventInstance.Id + Environment.NewLine);
Statustextbox.AppendText("Publisher: " + eventInstance.ProviderName + Environment.NewLine);
try
{
Statustextbox.AppendText("Description: " + eventInstance.FormatDescription() + Environment.NewLine);
}
catch (EventLogException ex)
{
Statustextbox.AppendText("An exception was thrown: " + ex.Message + Environment.NewLine);
}
EventLogRecord logRecord = (EventLogRecord)eventInstance;
Statustextbox.AppendText(Environment.NewLine);
Statustextbox.AppendText("Container Event Log: " + logRecord.ContainerLog + Environment.NewLine);
}
}

How to avoid 2019 MQRC_HOBJ_ERROR on getting Topic.Name

The following is used when
int topicOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
MQTopic mqTopic = qmgr.AccessTopic(mqCloneSpecs.topicString, "",
MQC.MQTOPIC_OPEN_AS_PUBLICATION, topicOptions);
The above part of the program builds a list of QueueManagers and a list of Topics which are used to call a listener class in a Windows service.
int tLoopCounter = 0;
foreach (MQTopic topic in topicOut)
{
tLoopCounter++;
// NOTE: We blow up here with 2019 MQRC_HOBJ_ERROR if we access the property topic.Name
//Console.WriteLine("Loop through topics topic.IsOpen: " + topic.IsOpen);
//Console.WriteLine(" OpenOptions:" + topic.OpenOptions);
debugLocation = "4053";
Console.WriteLine(" OpenStatus=" + topic.OpenStatus);
debugLocation = "4054";
i = tLoopCounter - 1;
Console.WriteLine("i=" + i);
debugQueueInfo = " topicPut #" + tLoopCounter + " QueueMgr:" + queueManagerForTopicsOut[i].Name.TrimEnd();
// currently getting 2019 : MQRC_HOBJ_ERROR on the line below
debugLocation = "4055";
debugQueueInfo += "Topic:" + topic.Name;
Console.WriteLine("Pump:Topic.Put:" + debugLocation + ":" + debugQueueInfo);
debugLocation = "4057";
topic.Put(mqMessage);
Console.WriteLine("Pump:Topic.Put completed");
}
When I try to add the Inquire option, as shown here:
int topicOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE;
then I die with this error:
DebugLocation=Q3012 Exception: System.ApplicationException:
MQException in Acce ssQueue ---> IBM.WMQ.MQException:
MQRC_OPTIONS_ERROR
Also, the OpenStatus=True from the Console.WriteLIne at debugLocation=4053. My first thought that if it were closed, that would cause this error.

Categories

Resources