Exception creating transaction after running sql server backup via SMO - sql

I keep on getting the following error every time i try to create a new transaction after i have backed up my database using SMO (Sql Server Management Objects):
New transaction is not allowed because there are other threads running in the session.
I have created a little console app that demonstrates the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Data;
namespace TestSMO
{
class Program
{
string username = "radandba";
string password = "belmont";
string servername = "e2idev\\e2isqlexpress";
string databaseName = "e2i";
string backupfilename = "c:\\e2i.bak";
Server server;
static void Main(string[] args)
{
Program prog = new Program();
prog.server = new Server(prog.servername);
prog.server.ConnectionContext.LoginSecure = false;
prog.server.ConnectionContext.Password = prog.password;
prog.server.ConnectionContext.Login = prog.username;
try
{
prog.server.ConnectionContext.Connect();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
return;
}
Console.WriteLine("Connected");
//prog.SelectData();
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = prog.databaseName;
backup.Devices.Clear();
backup.Incremental = false;
backup.Devices.AddDevice(prog.backupfilename, DeviceType.File);
backup.BackupSetName = prog.databaseName + " database backup";
backup.BackupSetDescription = prog.databaseName + " database - Full backup";
backup.Initialize = true;
backup.CopyOnly = true;
backup.LogTruncation = BackupTruncateLogType.NoTruncate;
backup.CompressionOption = BackupCompressionOptions.Default;
backup.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Complete);
backup.Information += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Information);
backup.PercentComplete += new PercentCompleteEventHandler(prog.backup_PercentComplete);
backup.SqlBackupAsync(prog.server);
}
void backup_PercentComplete(object sender, PercentCompleteEventArgs e)
{
Console.WriteLine("Backup progress: " + e.Percent);
}
void backup_Information(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
}
void backup_Complete(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
SelectData();
}
public void SelectData()
{
SqlConnection sqlCon = server.ConnectionContext.SqlConnectionObject;
try
{
if (sqlCon.State != System.Data.ConnectionState.Open)
sqlCon.Open();
SqlTransaction trans = sqlCon.BeginTransaction();
SqlDataAdapter adapter = new SqlDataAdapter("select * from version", sqlCon);
adapter.SelectCommand.Transaction = trans;
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row[0]);
}
trans.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
sqlCon.Close();
}
Console.ReadLine();
}
}
}

You could try to enable MARS on connection (msdn about MARS)
In connection string should be: "MultipleActiveResultSets=true;"

As stated by Anders UP turned out it was the NoLogTruncation was affecting it.

Related

Creata Jade Agent with another agent

please , I need help. How to create a JADE agent in the body of another agent ?
Profile p = new ProfileImpl();
p.setParameter(Profile.MAIN_HOST, "localhost");
p.setParameter(Profile.MAIN_PORT, "1099");
AgentContainer ac = rt.createMainContainer(p);
AgentController agent ac.createNewAgent ("agentBD", "agents.AgentBD");
agent.start();
try something like this ("agent" is you current agent from whitch you create other agent):
private static Codec codec = new SLCodec();
private static ContentManager cm = new ContentManager();
static
{
cm.registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0);
cm.registerOntology(FIPAManagementOntology.getInstance());
cm.registerOntology(JADEManagementOntology.getInstance());
}
public static AID createNewAgent(Agent agent, String name, String className)
{
CreateAgent ca = new CreateAgent();
ca.setAgentName(name);
ca.setClassName(className);
ca.setContainer((ContainerID) agent.here());
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.addReceiver(agent.getAMS());
request.setOntology(JADEManagementOntology.getInstance().getName());
request.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
request.setReplyWith("new-agent-" + agent.getName() + System.currentTimeMillis());
try
{
cm.fillContent(request, new Action(agent.getAMS(), ca));
agent.send(request);
MessageTemplate mt = MessageTemplate.MatchInReplyTo(request.getReplyWith());
ACLMessage reply = agent.blockingReceive(mt, 10000);
if(reply == null)
throw new RuntimeException("cannot create agent [" + name + "; " + className + "]");
return new AID(name, AID.ISLOCALNAME);
}
catch (Codec.CodecException e)
{
throw new RuntimeException(e);
}
catch (OntologyException e)
{
throw new RuntimeException(e);
}
}

"The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value...." How to Fix Code in .cs file

I'm getting this error on my .Cs Log file. cant understand why this showing now.
the error says its in Line 43
Another issue is that this code sometimes for this project is that it logs in fine sometimes, sometimes its giving the above error.
Here is my LogApplication.cs code.
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Drawing;using System.Data;
namespace YCT.Moderator
{
public class LogApplication
{
public static void LogApplicationActivity(string IPAddress, string timestamp, string username, string activity, string urlcurrent, string referrerurl, string useragent)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
try
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.CommandText = "insert into LogApplication(IPAddress,TimeStamp,Username,Activity,URLCurrent,ReferrerURL,UserAgent) values (#IPAddress,#TimeStamp,#Username,#Activity,#URLCurrent,#ReferrerURL,#UserAgent)";
cmd1.Parameters.AddWithValue("#IPAddress", IPAddress);
cmd1.Parameters.AddWithValue("#TimeStamp", timestamp);
cmd1.Parameters.AddWithValue("#Username", username);
cmd1.Parameters.AddWithValue("#Activity", activity);
cmd1.Parameters.AddWithValue("#URLCurrent", urlcurrent);
cmd1.Parameters.AddWithValue("#ReferrerURL", referrerurl);
cmd1.Parameters.AddWithValue("#UserAgent", useragent);
cmd1.Connection = con;
con.Open();
cmd1.ExecuteNonQuery();
}
}
catch
{
throw;
}
finally
{
con.Close();
}
}
public static string RetrieveLatestLoggedinActivity(string username, string activity)
{
string value = "";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
try
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.CommandText = "select top 1 timestamp from LOGAPPLICATION where username=#Username and activity=#Activity order by timestamp desc ";
cmd1.Parameters.AddWithValue("#Username", username);
cmd1.Parameters.AddWithValue("#Activity", activity);
cmd1.Connection = con;
cmd1.Connection = con;
con.Open();
if (cmd1.ExecuteScalar() != null)
value = cmd1.ExecuteScalar().ToString();
}
}
catch
{
throw;
}
finally
{
con.Close();
}
return value;
// return dt;
}
}
}

Object reference not set to an instance of an object when using SPGridViewPager

It's my first sharepoint project and eveything looks very confusing.
I need to have a SPGridView with paging.
Here is an entire code of mx webpart:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace FirstSPGridView.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/FirstSPGridView/SPGridViewWebPartTest/VisualWebPart1UserControl.ascx";
SPGridView _grid;
protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(mySite.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
_grid = new SPGridView();
_grid.AutoGenerateColumns = false;
_grid.PageSize = 3;
_grid.AllowPaging = true;
_grid.DataSource = SelectData();
Controls.Add(_grid);
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
}
}
});
}
catch (Exception ex)
{ }
}
protected sealed override void Render(HtmlTextWriter writer)
{
try
{
GenerateColumns();
_grid.DataBind();
base.Render(writer);
}
catch (Exception e)
{
throw new NotImplementedException();
}
}
private void GenerateColumns()
{
BoundField clientNameColumn = new BoundField();
clientNameColumn.HeaderText = "Client";
clientNameColumn.DataField = "LastName";
_grid.Columns.Add(clientNameColumn);
BoundField birthDayColumn = new BoundField();
birthDayColumn.HeaderText = "BirthDate";
birthDayColumn.DataField = "BirthDate";
_grid.Columns.Add(birthDayColumn);
}
public DataTable SelectData()
{
var dataGet = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (
var conn =
new SqlConnection(
"Data Source=localhost;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=True")
)
{
var adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("Select TOP 100 LastName,Birthdate FROM DimCustomer");
adapter.SelectCommand.Connection = conn;
conn.Open();
adapter.Fill(dataGet);
}
});
return dataGet;
}
}
}
Everything was working (except paging until I added this code:
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
After that I get an exception on the Render method here:
base.Render(writer);
StackTrace is:
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)\r\n at Microsoft.SharePoint.WebControls.Menu.FindControlByWalking(Control namingContainer, String id)\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.get_GridViewControl()\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.Render(HtmlTextWriter output)\r\n at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)\r\n at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)\r\n at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)\r\n at FirstSPGridView.VisualWebPart1.VisualWebPart1.Render(HtmlTextWriter writer)
How can I fix that error?
You must just set ID for _grid.
For example, _grid.ID = "_gridView";

LINQ to SQL in silverlight exception

This is a continution of my previous question: Could not find an implementation of the query pattern
Now I managed to query my database I can't seem to get the content on my webpage.
I try to return the code using the following code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Service1Client client = new Service1Client();
client.GetPersoonByIDCompleted += new EventHandler<GetPersoonByIDCompletedEventArgs>(client_GetPersoonByIDCompleted);
client.GetPersoonByIDAsync("1");
}
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
textBox1.Text = e.Error.ToString();
else
label1.Content = e.Result.Voornaam.ToString();
}
However when I press the button I get the following errors:
Object reference not set to an instance of an object.
at
SilverlightApplication1.MainPage.client_GetPersoonByIDCompleted(Object
sender, GetPersoonByIDCompletedEventArgs e) at
SilverlightApplication1.ServiceReference1.Service1Client.OnGetPersoonByIDCompleted(Object
state)
The weird thing is it works when I do not use LINQ, but normal SQL.
string sql = "SELECT ID, naam, voornaam, leeftijd FROM tblPersoon WHERE id=#pmID";
Persoon pers = null;
string connstr = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connstr))
{
SqlCommand com = new SqlCommand(sql, cn);
com.Parameters.AddWithValue("pmID", id);
cn.Open();
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
pers = new Persoon();
pers.ID = reader.GetString(0);
pers.Naam = reader.GetString(1);
pers.Voornaam = reader.GetString(2);
pers.Leeftijd = reader.GetInt32(3);
}
}
return pers;
}
LINQ result:
SQL result:
Thank you for helping me, I grealy appreciate it!
Thomas
You get that particular exception by trying to reference the "e.Result" property when it's not valid, i.e., when the method call returned an exception instead of a value. Before you reference e.Result, confirm that e.Error == null, and if it doesn't, indulge yourself in some error handling or messaging code, e.g.:
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("An error occurred: " + e.Error.ToString());
}
else
{
label1.Content = e.Result;
}
}
Or something of that sort.

Managing trace files on Sql Server 2005

I need to manage the trace files for a database on Sql Server 2005 Express Edition. The C2 audit logging is turned on for the database, and the files that it's creating are eating up a lot of space.
Can this be done from within Sql Server, or do I need to write a service to monitor these files and take the appropriate actions?
I found the [master].[sys].[trace] table with the trace file properties. Does anyone know the meaning of the fields in this table?
Here's what I came up with that is working pretty good from a console application:
static void Main(string[] args)
{
try
{
Console.WriteLine("CcmLogManager v1.0");
Console.WriteLine();
// How long should we keep the files around (in months) 12 is the PCI requirement?
var months = Convert.ToInt32(ConfigurationManager.AppSettings.Get("RemoveMonths") ?? "12");
var currentFilePath = GetCurrentAuditFilePath();
Console.WriteLine("Path: {0}", new FileInfo(currentFilePath).DirectoryName);
Console.WriteLine();
Console.WriteLine("------- Removing Files --------------------");
var fileInfo = new FileInfo(currentFilePath);
if (fileInfo.DirectoryName != null)
{
var purgeBefore = DateTime.Now.AddMonths(-months);
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc.zip");
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
if (PurgeLogFile(fi, purgeBefore))
{
Console.WriteLine("Deleting: {0}", fi.Name);
try
{
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Removed ---------------------");
Console.WriteLine();
Console.WriteLine("------- Compressing Files -----------------");
if (fileInfo.DirectoryName != null)
{
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc");
foreach (var file in files)
{
// Don't attempt to compress the current log file.
if (file.ToLower() == fileInfo.FullName.ToLower())
continue;
var zipFileName = file + ".zip";
var fi = new FileInfo(file);
var zipEntryName = fi.Name;
Console.WriteLine("Zipping: \"{0}\"", fi.Name);
try
{
using (var fileStream = File.Create(zipFileName))
{
var zipFile = new ZipOutputStream(fileStream);
zipFile.SetLevel(9);
var zipEntry = new ZipEntry(zipEntryName);
zipFile.PutNextEntry(zipEntry);
using (var ostream = File.OpenRead(file))
{
int bytesRead;
var obuffer = new byte[2048];
while ((bytesRead = ostream.Read(obuffer, 0, 2048)) > 0)
zipFile.Write(obuffer, 0, bytesRead);
}
zipFile.Finish();
zipFile.Close();
}
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Compressed ------------------");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
public static bool PurgeLogFile(FileInfo fi, DateTime purgeBefore)
{
try
{
var filename = fi.Name;
if (filename.StartsWith("audittrace"))
{
filename = filename.Substring(10, 8);
var year = Convert.ToInt32(filename.Substring(0, 4));
var month = Convert.ToInt32(filename.Substring(4, 2));
var day = Convert.ToInt32(filename.Substring(6, 2));
var logDate = new DateTime(year, month, day);
return logDate.Date <= purgeBefore.Date;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
public static string GetCurrentAuditFilePath()
{
const string connStr = "Data Source=.\\SERVER;Persist Security Info=True;User ID=;Password=";
var dt = new DataTable();
var adapter =
new SqlDataAdapter(
"SELECT path FROM [master].[sys].[traces] WHERE path like '%audittrace%'", connStr);
try
{
adapter.Fill(dt);
if (dt.Rows.Count >= 1)
{
if (dt.Rows.Count > 1)
Console.WriteLine("More than one audit trace file defined! Count: {0}", dt.Rows.Count);
var path = dt.Rows[0]["path"].ToString();
return path.StartsWith("\\\\?\\") ? path.Substring(4) : path;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
throw new Exception("No Audit Trace File in sys.traces!");
}
You can also set up SQL Trace to log to a SQL table. Then you can set up a SQL Agent task to auto-truncate records.
sys.traces has a record for every trace started on the server. Since SQL Express does not have Agent and cannot set up jobs, you'll need an external process or service to monitor these. You'll have to roll your own everything (monitoring, archiving, trace retention policy etc). If you have C2 audit in place, I assume you have policies in place that determine the duration audit has to be retained.