C# SQL output to text like SSMS message tab - c#

I'm having some trouble finding a way to get the results from updates/inserts/deletes/table creates...
I would like to get it like you see in the SSMS (SQL Server Management Studio) message tab (guess the tool is done_in_proc).
At the moment, I can get the exceptions, and I can capture the prints done in the SQL script.
I already tried ExecuteScalar, ExecuteReader, ExecuteWithResults and got nothing.
Thanks,
Code:
public void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError err in e.Errors)
{
richTextBoxDeployCopy.AppendText("Info : "+err.Message + Environment.NewLine);
}
}
public void ExecSQLScript(string Instance, string Database, string SQLScript, string Username, string Password)
{
if (Application2Deploy == "DUMMY")
{
server = "Server";
}
else
{
server = Instance;
} string sqlConnectionString = #"User ID=" + Username + "; Password = " + Password + ";Persist Security Info=False;Initial Catalog=" + Database + ";Data Source=" + server + "\\" + Instance;
FileInfo file = new FileInfo(SQLScript);
string script = file.OpenText().ReadToEnd();
conn = new SqlConnection(sqlConnectionString);
conn.FireInfoMessageEventOnUserErrors = true;
Server SQLserver = new Server(new ServerConnection(conn));
if (checkBoxDeployCopyTestingScript.Checked)
{
richTextBoxDeployCopy.AppendText("Test: Running SQL Script......" + Environment.NewLine);
LogFile(DateTime.Now + "Test: Running SQL Script......", LogPath);
}
else
{
try
{
SQLserver.ConnectionContext.Connect();
SQLserver.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);
SQLserver.ConnectionContext.BeginTransaction();
SQLserver.ConnectionContext.ExecuteNonQuery(script);
Error = false;
}
catch (Exception SQLEx)
{
Error = true;
richTextBoxDeployCopy.AppendText("Error executing SQL Script." + Environment.NewLine);
LogFile(DateTime.Now + "Error executing SQL Script", LogPath);
richTextBoxDeployCopy.AppendText("Exception: " + SQLEx.InnerException.Message + Environment.NewLine);
LogFile(DateTime.Now + "Exception: " + SQLEx.InnerException.Message, LogPath);
try
{
SQLserver.ConnectionContext.RollBackTransaction();
}
catch (Exception ex2)
{
richTextBoxDeployCopy.AppendText("Error executing rollback." + Environment.NewLine);
richTextBoxDeployCopy.AppendText("Exception: " + ex2.Message + Environment.NewLine);
}
}
if (Error == false)
{
SQLserver.ConnectionContext.CommitTransaction();
CopyExit("End");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
else
{
CopyExit("Abort");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
}
}

Related

Connect IIS on different server

I'm having an IIS on a different machine that I need to connect and I'm not able to do so.
How is it possible to do?
My add pool function:
private string addPool(string companyName, string serverName)
{
string errorMsg = string.Empty;
string result = run_AC("add apppool /name:" + companyName, serverName);
if (result.EndsWith("added" + Environment.NewLine))
errorMsg = string.Empty;//"Create application pool ... OK";
else if (result.StartsWith("ERROR ( message:Failed to add duplicate collection element"))
errorMsg = "Create application pool ... already exists";
else
errorMsg = "Create application pool ... failed - ";
return errorMsg;
}
</code>
<code>
private string siteCreation(string companyName, string BaseSite, string envirementFolderPath, string serverName)
{
string errorMsg = string.Empty;
string result = run_AC("add app /site.name:\"" + BaseSite + "\" /app.name:" + companyName + " /path:/" + companyName + " \"/physicalPath:" + envirementFolderPath + "\" /applicationPool:" + companyName, serverName);
if (result.EndsWith("added" + Environment.NewLine))
errorMsg += string.Empty;// "Create app ... OK";
else if (result.StartsWith("ERROR ( message:Failed to add duplicate collection element"))
errorMsg += "Create app ... already exists";
else
errorMsg += "Create app ... failed - " + result;
return errorMsg;
}

Windows Service Stuck on "Starting"

I've just created and installed my first Windows Service. When I start the service is never changes it's status to "Started". The status stays "Starting" but the service is doing it's job. I thought that perhaps the way I'm interacting with the OnStart method. I simply get the OnStart method to call another method that executes fine. Here is a sample:
protected override void OnStart(string[] args)
{
try {
Logger("Start");
}
catch (Exception ex)
{
string filePath2 = #"C:/ProgramData/Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
}
}
What would I need to change to get the client to register that the service has started and is running. PS, the service is doing what it's meant to do.
Thanks in advance for any and all help!
EDIT
This is what Logger does:
public void Logger(string state)
{
try
{
{
Random a = new Random(Environment.TickCount);
//unique name PhoneSystem.ApplicationName = "TestApi";//any name
PhoneSystem.ApplicationName = PhoneSystem.ApplicationName + a.Next().ToString();
}
#region phone system initialization(init db server)
String filePath = #"C:/ProgramData/3CXLogger/3CXPhoneSystem.ini";
if (!File.Exists(filePath))
{
//this code expects 3CXPhoneSystem.ini in current directory.
//it can be taken from the installation folder (find it in Program Files/3CXPhone System/instance1/bin for in premiss installation)
//or this application can be run with current directory set to location of 3CXPhoneSystem.ini
//v14 (cloud and in premiss) installation has changed folder structure.
//3CXPhoneSystem.ini which contains connectio information is located in
//<Program Files>/3CX Phone System/instanceN/Bin folder.
//in premiss instance files are located in <Program Files>/3CX Phone System/instance1/Bin
throw new Exception("Cannot find 3CXPhoneSystem.ini");
}
String value = _3cxLogger.Utilities.GetKeyValue("ConfService", "ConfPort", filePath);
Int32 port = 0;
if (!String.IsNullOrEmpty(value))
{
Int32.TryParse(value.Trim(), out port);
PhoneSystem.CfgServerPort = port;
}
value = _3cxLogger.Utilities.GetKeyValue("ConfService", "confUser", filePath);
if (!String.IsNullOrEmpty(value))
PhoneSystem.CfgServerUser = value;
value = _3cxLogger.Utilities.GetKeyValue("ConfService", "confPass", filePath);
if (!String.IsNullOrEmpty(value))
PhoneSystem.CfgServerPassword = value;
#endregion
DN[] ps = PhoneSystem.Root.GetDN(); //Access PhoneSystem.Root to initialize ObjectModel
//_3cxLogger.SampleStarter.StartSample(args);
}
catch (Exception ex)
{
string filePath2 = #"C:\ProgramData\3CXLogger\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
//Console.WriteLine(ex.ToString());
}
string constring = "Data Source = LEWCOMP1\\COMPLIANCE; Initial Catalog = 3CXCallStats; Integrated Security = True";
while (state == "Start")
{
Thread.Sleep(5000);
int count = 0;
foreach (DN dn in PhoneSystem.Root.GetDN())
{
ActiveConnection[] a = dn.GetActiveConnections();
foreach (ActiveConnection ac in a)
{
try
{
if (ac.Status == ConnectionStatus.Connected)
{
count = count + 1;
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source);
string filePath2 = #"C:\ProgramData\3CXLogger\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath2, true))
{
writer.WriteLine(DateTime.Now + Environment.NewLine + "Message: " + ex.ToString() + Environment.NewLine + "Stack Trace: " + ex.StackTrace);
}
}
}
}
count = count / 2;
string update = "UPDATE callsCounter SET Counter = '" + count + "' WHERE ID='1';";
string insert = "INSERT Interval_Counter (Date_Time, Count) VALUES ('" + DateTime.Now + "','" + count + "')";
SqlConnection myCon = new SqlConnection(constring);
SqlCommand updateCMD = new SqlCommand(update, myCon);
SqlCommand insertCMD = new SqlCommand(insert, myCon);
SqlDataReader myReaderUpdate;
SqlDataReader myReaderInsert;
myCon.Open();
myReaderUpdate = updateCMD.ExecuteReader();
myReaderUpdate.Read();
myCon.Close();
myCon.Open();
myReaderInsert = insertCMD.ExecuteReader();
myReaderInsert.Read();
myCon.Close();
}
}
Additionaly, I checked the event logs and there are events for the service has successfully started. Odd.
Thanks for all the help!
I created a new class and started a new thread that targeted the method.
protected override void OnStart(string[] args)
{
Log oLog = new Log();
Thread t = new Thread(new ThreadStart(oLog.Logger));
t.Start();
}

How can I receive only the computer names which are accessible for me at this time?

Windows 7 domain network.
I get the domain computer names:
List<String> compNames = new List<String>();
// If it isn't possible to be connected to a domain
// network then we will receive an exception.
using (DirectoryEntry domainEntry = domain.GetDirectoryEntry())
using (DirectorySearcher searcher = new DirectorySearcher(
domainEntry, "objectClass=computer", new[] { "Name" }))
using (SearchResultCollection resultCollection =
searcher.FindAll()) {
foreach (SearchResult searchResult in resultCollection) {
compNames.Add(searchResult.Properties["Name"][0]
.ToString());
}
}
This code returns also the names of computers which already are not existing many years and the computers which are off. How can I recive only the computer names which are accessible for me at this time? Is it possible?
I recommend you to ping each computer on domain to check their accessibility.
Below function you can use to ping computer:
public String PingTest(string asMac)
{
String lsReturn = "";
try
{
Ping pingreq = new Ping();
PingReply rep = pingreq.Send(asMac);
if (rep.Status == IPStatus.Success)
{
lsReturn = "Success"
return lsReturn;
}
else
{
lsReturn = "Error Pinging " + asMac + " " + rep.Status;
}
}
catch (PingException pEx)
{
lsReturn = "PingException Error Pinging " + asMac + " " + pEx.Message + Environment.NewLine + pEx.StackTrace;
}
catch (NetworkInformationException nEx)
{
lsReturn = "NetworkInformationException Error Pinging " + asMac + " " + nEx.Message + Environment.NewLine + nEx.StackTrace;
}
catch (Exception ex)
{
lsReturn = "Error Pinging " + asMac + " " + ex.Message + Environment.NewLine + ex.StackTrace;
}
return lsReturn;
}

Commit after MessageBox in C#

I have this code in my winform C# application:
public void InsertValidationDate(Validar v, string descanso)
{
bool insert = false;
try
{
bd.con.Open();
bdag.bd.trans = bdag.bd.con.BeginTransaction();
insert = InsertDate(v);
if (insert == true)
{
MessageBox.Show("Insert Ok");
pk = ReturnInsertDate(DateTime.Parse(v.Date), v.User);
insert = UpdateReference(DateTime.Parse(v.Date), pk);
if (insert == false)
{
Rollback();
MessageBox.Show("Update Error");
}
else
{
Commit();
MessageBox.Show("Update OK");
}
}
}
catch (Exception ex)
{
Rollback();
}
finally
{
con.Close();
}
}
After displaying the message ("Insert Ok") the connection to the database is closed and the transaction is not posible commited. Why? Because the Insert function don't close the database connection. Any Ideas? Thanks!!.
public int ReturnInsertDate(DateTime date, int user)
{
int validate = -1;
try
{
bd.CadSQL = "select " + bd.Validar.id + " from " + bd.Validar.tabla + " where ";
bd.CadSQL += bd.Validar.date + " = '" + date.Year + "-" + date.Month.ToString("d2") + "-" + date.Day.ToString("d2") + "'";
bd.CadSQL += " and " + bd.Validar.user+ " = " + user;
bd.comandoSQL.CommandText = bd.CadSQL;
bd.reader = bd.comandoSQL.ExecuteReader();
while (bd.reader.Read())
{
if (!bd.reader.IsDBNull(0))
validate = bd.reader.GetInt32(0);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
bd.reader.Close();
}
return validate;
}
public bool UpdateReference(DateTime date, int validate)
{
bool updateR = false;
try
{
bd.CadSQL = "update " + bd.Fichar.tabla;
bd.CadSQL += " set " + bd.Fichar.validateId + " = " + validate;
bd.CadSQL += " where " + bd.Fichar.date + " = '" + date.Year + "-" + date.Month.ToString("d2") + "-" + date.Day.ToString("d2") + "'";
bd.comandoSQL.CommandText = bd.CadSQL;
bd.comandoSQL.ExecuteNonQuery();
updateR = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return updateR ;
}
i would set your transaction as follows since it seems you are working with different connection objects.
using (var scope = TransactionHelper.Instance)
{
var process = true;
var aMessage = "";
try
{
//Enter you code and functions here
//Whenever you find a piece of code to be working incorrectly, Raise an error
if(!someCode(blabla))
throw new Exception("This someCode quited on me!");
//Whenever your code does what it needs to do, end with a commit
scope.Commit();
}
catch(Exception ex) //Catch whatever exception might occur
{
scope.FullRollBack();
aMessage = ex.Message;
process = false;
}
finally
{
//only here you will use messageboxes to explain what did occur during the process
if (process)
MessageBox.Show("Succesfully Committed!");
else
MessageBox.Show(string.Format("Rollback occurred, exception Message: {0}"
, aMessage);
}
}
It's a bit strange that you're referring to con when you open the connection, and then you use bdag.bd.con for the BeginTransaction call. Are you absolutely certain these two variables are pointing to the same connection object?

Using Redemption (Outlook) with a user other than the logged in user - and getting errors

I'm using Redemption dll (http://www.dimastr.com/redemption/) and I've created an exe that accesses my mail box.
I run the exe in Windows Scheduler under my username and it works fine, I get an email sent to me (see below code).
When I change the runas username in Scheduler to someone else and try to access their mail box Profile I get an error. System.IO.FileLoadException
static void Main(string[] args)
{
System.Diagnostics.Debugger.Break();
object oItems;
//string outLookUser = "My Profile Name";
string outLookUser = "Other User Profile Name";
string ToEmailAddress = "abc.email#xyz.com";
string FromEmailAddress = "abc.email#xyz.com";
string outLookServer = "exchangeServer.com";
string sMessageBody =
"\n outLookUser: " + outLookUser +
"\n outLookServer: " + outLookServer +
"\n\n";
RDOSession Session = null;
try
{
rdoDefaultFolders olFolderInbox = rdoDefaultFolders.olFolderInbox;
Session = new RDOSession();
RDOFolder objFolder;
Session.LogonExchangeMailbox(outLookUser, outLookServer);
int mailboxCount = Session.Stores.Count;
string defaultStore = Session.Stores.DefaultStore.Name;
sMessageBody +=
"\n mailboxCount: " + mailboxCount.ToString() +
"\n defaultStore: " + defaultStore +
"\n\n";
//RDOStore rmpMetering = Session.Stores.GetSharedMailbox("Name of another mailbox");
//objFolder = rmpMetering.GetDefaultFolder(olFolderInbox);
objFolder = Session.GetDefaultFolder(olFolderInbox);
oItems = objFolder.Items;
int totalcount = objFolder.Items.Count;
if (totalcount > 10) totalcount = 10;
for (int loopcounter = 1; loopcounter < totalcount; loopcounter++)
{
RDOMail oItem = objFolder.Items[loopcounter];
string attachmentName = string.Empty;
foreach (RDOAttachment attachment in oItem.Attachments)
{
attachmentName += attachment.FileName + " ";
if (attachmentName.Trim() == "Data.csv")
{
attachment.SaveAsFile(#"C:\datafiles\" + attachmentName.Trim());
foreach (RDOFolder archiveFolder in objFolder.Folders)
{
if (archiveFolder.Name == "DataFileArchive")
{
oItem.MarkRead(true);
oItem.Move(archiveFolder);
}
}
}
}
sMessageBody += oItem.Subject + " " + attachmentName + "\n";
if ((oItem.UnRead))
{
//Do whatever you need this for
//sMessageBody = oItem.Body;
//oItem.MarkRead(true);
}
}
System.Web.Mail.SmtpMail.Send(ToEmailAddress,FromEmailAddress
, "Data File Processing-" + DateTime.Now.ToString()
,"" + sMessageBody);
}
catch (Exception ex)
{
Session = null;
System.Web.Mail.SmtpMail.Send(ToEmailAddress, FromEmailAddress, "Error", sMessageBody + " " + ex.Message);
}
finally
{
if ((Session != null))
{
if (Session.LoggedOn)
{
Session.Logoff();
}
}
}
}
When I try to run the same exe on another machine with me logged in I get this error,
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass
embly 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken=null
' or one of its dependencies. The system cannot find the file specified.
File name: 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken
=null'
at RPMDataFileProcessing.Program.Main(String[] args)
Has anyone got any ideas on what I'm doing wrong, can Redemption be used in this way?
I got this working in the end by ensuring that the user you are logged in as, has 'full mailbox rights' to the mail box you are trying to see.

Categories

Resources