I have few connections like this:
try
{
OleDbConnection con1;
using (con1 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db1:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con1.Open();
v1 = 1;
con1.Close();
}
}
catch (Exception ex)
{
v1 = 0;
}
try
{
OleDbConnection con2;
using (con2 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db2:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con2.Open();
v2 = 1;
con2.Close();
}
}
catch (Exception ex)
{
v2 = 0;
}
In page_load and working in order. I need parallel run this connections. How can I do that?
With C# 6 and .NET 4.5 you can use the TPL with async and the code looks even cleaner:
static void Main()
{
var v1Task = Connect();
var v2Task = Connect();
var results = Task.WhenAll(v1Task, v2Task);
var v1 = results.Result[0];
var v2 = results.Result[1];
}
static async Task<int> Connect()
{
int v;
try
{
using (var con2 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db2:1521;Persist Security Info=True;Password=password;User ID=username"))
{
await con2.OpenAsync();
v = 1;
con2.Close();
}
}
catch (Exception)
{
v = 0;
}
return v;
}
Start con1 and con2 asynchronously and wait until both tasks are finished
var task1 = Task.Run(() =>
{
try
{
using (OleDbConnection con1 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db1:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con1.Open();
v1 = 1;
con1.Close();
}
}
catch (Exception ex)
{
v1 = 0;
}
});
var task2 = Task.Run(() =>
{
try
{
using (OleDbConnection con2 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db2:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con2.Open();
v2 = 1;
con2.Close();
}
}
catch (Exception ex)
{
v2 = 0;
}
});
// If you need to wait until task1 and task2 finished, then use this:
List<Task> tasks = new List<Task>();
tasks.Add(task1);
tasks.Add(task2);
Task.WaitAll(tasks.ToArray());
Using parallel.for:
static void Main(string[] args)
{
ConcurrentDictionary<string, int> results = new ConcurrentDictionary<string, int>();
string[] connStrings = new string[]{"connstring1", "connstring2"};
Parallel.For(0, connStrings.Length, (i) => {
results[connStrings[i]] = TryToConnectToDatabase(connStrings[i]);
});
}
static int TryToConnectToDatabase(string connstr)
{
try
{
OleDbConnection con1;
using (con1 = new OleDbConnection(connstr))
{
con1.Open();
con1.Close();
return 1;
}
}
catch (Exception ex)
{
return 0;
}
}
Related
I have created a Windows forms application which able to publish OPC tags into an MQTT broker, Now I'm trying to do the reverse, write MQTT tags into an OPC server. when I have started both the agent (the publisher) and the transfer (the subscriber) the two threads do the same work which is publishing I don't know what is the problem.
The start method is below :
public byte Start()
{
try
{
byte connectResult;
if (IsLWT == false)
{
connectResult = this._MqttClient.Connect(ClientID, Username, Password, IsCleanSession, KeepAlivePeriode);
}
else
{
connectResult = this._MqttClient.Connect(ClientID, Username, Password, willRetain, willQos, true, willTopic, willMessage, IsCleanSession, KeepAlivePeriode);
}
// 0 means that the connection suceeded
if (connectResult == 0)
{
this.Rate = GetRateFromOPCGroups();
this._publisherThread = new Thread(() => Publish());
this._publisherThread.IsBackground = true;
this._publisherThread.Start();
IsStarted = true;
}
if (connectResult == 0)
{
//this.Rate = GetRateFromOPCGroups();
this._SubscriberThread = new Thread(() => Subscribe(topics));
this._SubscriberThread.IsBackground = true;
this._SubscriberThread.Start();
IsStarted = true;
}
return connectResult;
}
catch (IntegrationObjects.Networking.M2Mqtt.Exceptions.MqttClientException ex)
{
MQTTServiceLogger.TraceLog(MessageType.Error, MQTTServiceMessages.startAgentFailed(this.Name,ex.Message));
return 11;
}
catch (IntegrationObjects.Networking.M2Mqtt.Exceptions.MqttCommunicationException ex)
{
MQTTServiceLogger.TraceLog(MessageType.Error, MQTTServiceMessages.startAgentFailed(this.Name, ex.Message));
return 11;
}
catch (Exception ex)
{
MQTTServiceLogger.TraceLog(MessageType.Error, MQTTServiceMessages.startAgentFailed(this.Name, ex.Message));
return 11;
}
}
1.This is the publish code:
private void Publish()
{
while (true)
{
if (IsStarted)
{
try
{
if (_MqttClient.IsConnected)
{
isConnected = true;
if (this.OPCItems.Count != 0)
{
JsonMQTTMessage JsonMessage = new JsonMQTTMessage();
JsonMessage.Timestamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff");
JsonMessage.ListofValues = new List<UpdatedOPCItem>();
lock (lockOPCItems)
{
foreach (OPCItem Item in OPCItems.ToList())
{
if (Item != null)
{
UpdatedOPCItem upItem = new UpdatedOPCItem();
upItem.ID = Item.ItemID;
upItem.value = Item.ItemCurrentValue;
upItem.quality = Item.ItemQuality;
upItem.timestamp = Item.ItemTimeStamp.ToString("yyyy/MM/dd HH:mm:ss.fff");
upItem.DataType = Item.ItemDataType;
JsonMessage.ListofValues.Add(upItem);
}
}
}
var messageTopublish = Newtonsoft.Json.JsonConvert.SerializeObject(JsonMessage);
ushort res = _MqttClient.Publish(Topic, Encoding.UTF8.GetBytes(messageTopublish), Qos, Retain);
ResetValues();
Thread.Sleep(Rate);
This is the Subscribe code:
public void Subscribe(List topics)
{
while (true)
{
if (IsStarted)
{
try
{
if (_MqttClient.IsConnected)
{
isConnected = true;
foreach (string topic in topics)
{
ushort msggId = _MqttClient.Subscribe(new string[] { $"{ topic }" },
new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
}
Thread.Sleep(Rate);
}
else
I want to develop a Web Service restful CRUD between a data base PostgreSQL and a web application in asp. I look many examples and tutorials but I've not find solution. I'am here :
I have a service "Service191" that I can call by Mozilla or by WCF Test Client :
public class Service191 : IService191
{
public string data;
public static NpgsqlConnection conn;
/*
* Connection à la base de donnée
*/
public void connection()
{
try
{
Mails mail = new Mails();
string strConnString = #"Server=194.206.X.XXX; Port=5432; Database=XXXXX; User Id=XXXX; Password=XXXXX";
DAL.DAL dal = new DAL.DAL(strConnString);
//TestSelectCommand(mail, dal);
//TestXMLSerialization();
GenerateGetRequest();
//GeneratePostRequest();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
For test this I call the function GenerateGetRequest() :
private static void GenerateGetRequest()
{
string url = "http://localhost:49761/Service191.svc/mails?id=14";
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = WebRequestMethods.Http.Get;
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
Stream GetResponseStream = GETResponse.GetResponseStream();
StreamReader sr = new StreamReader(GetResponseStream);
MessageBox.Show(sr.ReadToEnd());
}
Url is what my web application send later. "Mails" is the table where the web service will do the request.
I've got too a Handler :
public class Handler : IHttpHandler
{
private DAL.DAL dal;
private string connString;
private Mails mail;
private ErrorHandler.ErrorHandler errHandler;
#region HANDLER
public bool IsReusable
{
get
{
throw new NotImplementedException();
}
}
public void ProcessRequest(HttpContext context)
{
try
{
string url = Convert.ToString(context.Request.Url);
connString = "Server = 194.206.X.XXX; Port = 5432; Database = XXXX; User Id = XXXX; Password = XXXXX";
dal = new DAL.DAL(connString);
errHandler = new ErrorHandler.ErrorHandler();
switch (context.Request.HttpMethod)
{
case "GET":
READ(context);
break;
case "POST":
CREATE(context);
break;
case "PUT":
UPDATE(context);
break;
case "DELETE":
DELETE(context);
break;
default:
break;
}
}
catch (Exception ex)
{
errHandler.ErrorMessage = ex.Message.ToString();
context.Response.Write(errHandler.ErrorMessage);
//MessageBox.Show(ex.ToString());
}
}
#endregion
#region CRUD
private void READ(HttpContext context)
{
try
{
int id = Convert.ToInt16(context.Request["id"]);
mail = dal.GetMail(id);
if (mail == null)
context.Response.Write(id + "No mail found");
string serialized = Serialize(mail);
context.Response.ContentType = "text/xml";
WriteResponse(serialized);
MessageBox.Show("mail READ");
}
catch (Exception ex)
{
errHandler.ErrorMessage = dal.GetException();
errHandler.ErrorMessage = ex.Message.ToString();
//MessageBox.Show(ex.ToString());
}
}
private void CREATE(HttpContext context)
{
try
{
byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength);
string str = Encoding.UTF8.GetString(PostData);
Mails mail = Deserialize(PostData);
dal.AddMail(mail);
MessageBox.Show("mail CREATE");
}
catch (Exception ex)
{
errHandler.ErrorMessage = dal.GetException();
errHandler.ErrorMessage = ex.Message.ToString();
//MessageBox.Show(ex.ToString());
}
}
private void UPDATE(HttpContext context)
{
try
{
byte[] PUTRequestByte = context.Request.BinaryRead(context.Request.ContentLength);
context.Response.Write(PUTRequestByte);
Mails mail = Deserialize(PUTRequestByte);
dal.UpdateMail(mail);
MessageBox.Show("mail UPDATE");
}
catch (Exception ex)
{
errHandler.ErrorMessage = dal.GetException();
errHandler.ErrorMessage = ex.Message.ToString();
//MessageBox.Show(ex.ToString());
}
}
private void DELETE(HttpContext context)
{
try
{
int id = Convert.ToInt16(context.Request["id"]);
dal.DeleteMail(id);
MessageBox.Show("mail DELETE");
}
catch (Exception ex)
{
errHandler.ErrorMessage = dal.GetException();
errHandler.ErrorMessage = ex.Message.ToString();
}
}
#endregion
private Mails Deserialize (byte[] xmlByteData)
{
try
{
XmlSerializer ds = new XmlSerializer(typeof(Mails));
MemoryStream memoryStream = new MemoryStream(xmlByteData);
Mails mail = new Mails();
mail = (Mails)ds.Deserialize(memoryStream);
return mail;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
}
private static void WriteResponse(string strMessage)
{
HttpContext.Current.Response.Write(strMessage);
}
private String Serialize(Mails mail)
{
try
{
String XmlizedString = null;
XmlSerializer xs = new XmlSerializer(typeof(Mails));
MemoryStream memoryStream = new MemoryStream();
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, mail);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
}
private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}
}
But I don't understand why my handler is never call. So I have always a 400 error.
I've got too a DAL class who permiss the connection et request to the database :
public class DAL
{
private NpgsqlConnection conn;
private NpgsqlCommand command;
private static string connString;
private static List<Mails> mailList;
private ErrorHandler.ErrorHandler err;
public DAL(string _connString)
{
err = new ErrorHandler.ErrorHandler();
connString = _connString;
}
public void AddMail (Mails mail)
{
try
{
using (conn)
{
string npgsqlInsertString = "INSERT INTO mails (id_entete, emmetteur, destinataires, objet, contenu, date_envoi, heure_envoi) VALUES (#id_entete, #emmetteur, #destinataires, #objet, #contenu, #date_envoi, #heure_envoi)";
conn = new NpgsqlConnection(connString);
command = new NpgsqlCommand();
command.Connection = conn;
command.Connection.Open();
command.CommandText = npgsqlInsertString;
NpgsqlParameter idParam = new NpgsqlParameter("#id_entete", mail.Id_entete);
NpgsqlParameter emmParam = new NpgsqlParameter("#id_entete", mail.Emmetteur);
NpgsqlParameter destParam = new NpgsqlParameter("#id_entete", mail.Destinataires);
NpgsqlParameter objParam = new NpgsqlParameter("#id_entete", mail.Objet);
NpgsqlParameter contParam = new NpgsqlParameter("#id_entete", mail.Contenu);
NpgsqlParameter dateParam = new NpgsqlParameter("#id_entete", mail.Date_envoi);
NpgsqlParameter heureParam = new NpgsqlParameter("#id_entete", mail.Heure_envoi);
command.Parameters.AddRange(new NpgsqlParameter[] { idParam, emmParam, destParam, objParam, contParam, dateParam, heureParam });
command.ExecuteNonQuery();
command.Connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void UpdateMail (Mails mail)
{
try
{
using (conn)
{
string npgsqlUpdateString = "UPDATE mails SET id_entete=#id_entete, emmetteur=#emmetteur, destinataires=#destinataires, objet=#objet, contenu=#contenu, date_envoi=#date_envoi, heure_envoi=#heure_envoi WHERE id=#id";
conn = new NpgsqlConnection(connString);
command = new NpgsqlCommand();
command.Connection = conn;
command.Connection.Open();
command.CommandText = npgsqlUpdateString;
NpgsqlParameter idParam = new NpgsqlParameter("#id_entete", mail.Id_entete);
NpgsqlParameter emmParam = new NpgsqlParameter("#id_entete", mail.Emmetteur);
NpgsqlParameter destParam = new NpgsqlParameter("#id_entete", mail.Destinataires);
NpgsqlParameter objParam = new NpgsqlParameter("#id_entete", mail.Objet);
NpgsqlParameter contParam = new NpgsqlParameter("#id_entete", mail.Contenu);
NpgsqlParameter dateParam = new NpgsqlParameter("#id_entete", mail.Date_envoi);
NpgsqlParameter heureParam = new NpgsqlParameter("#id_entete", mail.Heure_envoi);
command.Parameters.AddRange(new NpgsqlParameter[] { idParam, emmParam, destParam, objParam, contParam, dateParam, heureParam });
command.ExecuteNonQuery();
command.Connection.Close();
}
}
catch (Exception ex)
{
err.ErrorMessage = ex.Message.ToString();
throw;
}
}
public void DeleteMail (int id)
{
try
{
using (conn)
{
string npgsqlDeleteString = "DELETE FROM mails WHERE id=#id";
conn = new NpgsqlConnection(connString);
command = new NpgsqlCommand();
command.Connection = conn;
command.Connection.Open();
command.CommandText = npgsqlDeleteString;
NpgsqlParameter idParam = new NpgsqlParameter("#id", id);
command.Parameters.Add(idParam);
command.ExecuteNonQuery();
command.Connection.Close();
}
}
catch (Exception ex)
{
err.ErrorMessage = ex.Message.ToString();
throw;
}
}
public Mails GetMail(int ID)
{
try
{
if (mailList == null)
{
mailList = GetMails();
}
foreach (Mails mail in mailList)
{
if (mail.Id == ID)
{
return mail;
}
}
return null;
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
err.ErrorMessage = ex.Message.ToString();
throw;
}
}
private List<Mails> GetMails()
{
try
{
using (conn)
{
mailList = new List<Mails>();
conn = new NpgsqlConnection(connString);
string npgsqlSelectString = "SELECT * FROM mails";
command = new NpgsqlCommand(npgsqlSelectString, conn);
command.Connection.Open();
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Mails mail = new Mails();
mail.Id = (int)reader[0];
mail.Id_entete = (int)reader[1];
mail.Emmetteur = reader[2].ToString().Replace(" ", "");
mail.Destinataires = reader[3].ToString().Replace(" ", "");
mail.Objet = reader[4].ToString().Replace(" ", "");
mail.Contenu = reader[5].ToString().Replace(" ", "");
mail.Date_envoi = reader[6].ToString().Replace(" ", "");
mail.Heure_envoi = reader[7].ToString().Replace(" ", "");
mailList.Add(mail);
}
command.Connection.Close();
return mailList;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
err.ErrorMessage = ex.Message.ToString();
throw;
}
}
public string GetException()
{
return err.ErrorMessage.ToString();
}
}
So, who can I do for call the function ProcessRequest(HttpContext context) ? Thank you for your help and sorry for my bad english ... ! :)
I've used a lot this page for work : http://www.codeproject.com/Articles/112470/Developing-a-REST-Web-Service-using-C-A-walkthroug
I have coded a service in C# which runs and updates a CRM solution. I am trying to get the service to re-establish a connection to the database if it has to drop for some reason. So far when I detach the database and then reattach it, the service stops by itself.. Another thing is that then I detach the database, there is no exception logged by my synch app - it just stops dead.
My partial class where I call my synch from:
namespace Vessel_Schedule_Synch
{
[DisplayName("CRM Vessel Synch")]
partial class startVessel : ServiceBase
{
System.Threading.Timer t;
VesselUpdater v;
protected override void OnStart(string[] args)
{
//System.Threading.Thread.Sleep(20000);
v = new VesselUpdater();
t = new System.Threading.Timer(new System.Threading.TimerCallback(t_TimerCallback), null, 0, 300000);
//InfoLogger.Info("Starting service " + this.ServiceName, true);
}
private void t_TimerCallback(object state)
{
t.Change(Timeout.Infinite, Timeout.Infinite);
lock (v)
{
InfoLogger.Info("Timer fired... updating vessels");
try
{
v.Process();
v.updateCRM();
}
catch (Exception e)
{
if (v == null)
{ throw e; }
else
{
InfoLogger.Exception(e);
}
}
finally
{
InfoLogger.Info("End of Timer Trigger... Restarting Timer.");
t.Change(30000, 30000);
}
}
}
protected override void OnStop()
{
InfoLogger.Info("Service Stopped " + this.ServiceName, true);
}
}
}
My synch class where I have tried to use a bool to test the connection:
namespace Vessel_Schedule_Synch
{
class VesselUpdater
{
private OrganizationServiceProxy _serviceProxy;
private IOrganizationService _service;
private Logger logger = LogManager.GetLogger("VesselUpdater");
public string ConnectionString { get; set; }
public string ServiceUrl { get; set; }
int i = 0;
private bool InitialiseCRMConnection;
public VesselUpdater()
{
InitialiseCRMConnection = true;
Console.WriteLine("Starting the service");
LogMessage("Starting service");
ServiceUrl = ConfigurationManager.AppSettings["CRMUrl"];
LogMessage(ConnectionString);
ConnectionString = ConfigurationManager.ConnectionStrings["iRoot"].ConnectionString;
LogMessage(ServiceUrl);
Console.WriteLine(ServiceUrl);
}
public void Process()
{
if (!InitialiseCRMConnection)
return;
LogMessage("Process Starting");
ClientCredentials UserCredentials = new ClientCredentials();
string UserName = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
UserCredentials.UserName.UserName = UserName;
UserCredentials.UserName.Password = Password;
ClientCredentials DivCredentials = null;
Uri HomeRealmURI = null;
Uri serviceurl = new Uri(ServiceUrl);
_serviceProxy = new OrganizationServiceProxy(serviceurl, HomeRealmURI, UserCredentials, DivCredentials);
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
_serviceProxy.EnableProxyTypes();
LogMessage("CRM Connection Initiated");
InitialiseCRMConnection = false;
}
public void updateCRM()
{
try
{
ProcessVesselSchedule("Insert");
ProcessVesselSchedule("Modification");
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
private void ProcessVesselSchedule(string Type)
{
if (InitialiseCRMConnection)
return;
try
{
LogMessage(string.Format("Processing Vessesl Schedules {0}", Type));
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("VesselScheduleInformation", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Type", Type);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
LogMessage("Processing Record");
LogMessage(dr["new_Name"].ToString());
string Name = dr["new_Name"].ToString() + " " + dr["new_VoyageNo"].ToString();
string Vesselname = dr["new_Name"].ToString();
int LineNo = (int)dr["Line Number"];
string NAVVesselScheduleCode = dr["new_NAVVesselScheduleCode"].ToString();
string CarrierService = dr["new_CarrierService"].ToString();
string ETA = dr["new_ETA"].ToString();
string ETD = dr["new_ETD"].ToString();
string VesselCode = dr["new_Vessel"].ToString();//Vessel Code
string VoyageNo = dr["new_VoyageNo"].ToString();
string TranshipmentVessel = dr["new_TranshipmentVessel"].ToString();
string TranshipmentVoyageNo = dr["new_TranshipmentVoyageNo"].ToString();
string Port = dr["new_Port"].ToString();
string PortOfDis = dr["new_DischargePort"].ToString();
string PortOfLoad = dr["new_LoadPort"].ToString();
//string StackStart = dr["new_StackStart"].ToString();
//string StackEnd = dr["new_StackEnd"].ToString();
bool Create = false;
LogMessage("Assigned all variables");
Console.WriteLine("Assigned all variables");
new_vesselschedule VesselS = FindVessleSchedule(NAVVesselScheduleCode, LineNo, out Create);
//if (DateTime.Parse(StackStart).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackstart"] = DateTime.Parse(StackStart).ToUniversalTime();
//}
//if (DateTime.Parse(StackEnd).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackend"] = DateTime.Parse(StackEnd).ToUniversalTime();
//}
VesselS.new_name = Name;
VesselS.new_navvesselschedulecode = NAVVesselScheduleCode;
VesselS.new_CarrierService = CarrierService;
if (DateTime.Parse(ETA).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETA = DateTime.Parse(ETA).ToUniversalTime();
}
if (DateTime.Parse(ETD).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETD = DateTime.Parse(ETD).ToUniversalTime();
}
VesselS.new_vesselcodeimport = VesselCode;
VesselS.new_vesselnameimport = Vesselname;
VesselS.new_VoyageNo = VoyageNo;
VesselS.new_TransshipmentVessel = TranshipmentVessel;
VesselS.new_TransshipmentVoyageNo = TranshipmentVoyageNo;
VesselS.new_dischargeportimport = PortOfDis;
VesselS.new_loadportimport = PortOfLoad;
if (Create)
{
LogMessage(string.Format("Created {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Create(VesselS);
}
else
{
LogMessage(string.Format("Updated {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Update(VesselS);
}
using (SqlCommand cmdUpdateMates = new SqlCommand())
{
SqlConnection con2 = new SqlConnection(ConnectionString);
con2.Open();
cmdUpdateMates.Connection = con2;
cmdUpdateMates.CommandText = "ProcessedVessSched";
cmdUpdateMates.CommandType = CommandType.StoredProcedure;
cmdUpdateMates.Parameters.AddWithValue("#VesselSched", NAVVesselScheduleCode);
cmdUpdateMates.Parameters.AddWithValue("#LineNo", LineNo);
cmdUpdateMates.ExecuteNonQuery();
i++;
Console.WriteLine("Created/Updated" + " " + i);
}
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
}
}
catch (SqlException e)
{
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
public void LogMessage(string Message)
{
LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", Message);
myEvent.LoggerName = logger.Name;
logger.Log(myEvent);
}
private new_vesselschedule FindVessleSchedule(string NAVVesselScheduleCode, int LineNo, out bool Create)
{
QueryExpression query = new QueryExpression(new_vesselschedule.EntityLogicalName);
query.ColumnSet.AllColumns = true;
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("new_navvesselschedulecode", ConditionOperator.Equal, NAVVesselScheduleCode);
query.Criteria.AddCondition("new_lineno", ConditionOperator.Equal, LineNo);
EntityCollection entitycollection = _serviceProxy.RetrieveMultiple(query);
if (entitycollection.Entities.Count == 0)
{
new_vesselschedule n = new new_vesselschedule();
n.new_navvesselschedulecode = NAVVesselScheduleCode;
n.new_lineno = LineNo;
Create = true;
return n;
}
Create = false;
return (new_vesselschedule)entitycollection.Entities[0];
}
}
}
Am I missing something here?
I found the issue in my code, I had forgotten to sent InitialiseCRMConnection = true; in my SQL Exception thus it could never go through the motions of reInitialising the connection as it would always return;
Fix:
catch (SqlException e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
I adapted the following code from one I found online. Works ok but is not running continuously and pulling in new tweets. What do I need to change? Help appreciated.
private static void Stream_FilteredStreamExample()
{
SqlConnection conn = new SqlConnection(#"Data Source=********************");
conn.Open();
for (; ; )
{
try
{
var stream = Stream.CreateFilteredStream();
//stream.AddLocation(Geo.GenerateLocation(-180, -90, 180, 90));
stream.AddTweetLanguageFilter(Language.English);
stream.AddTrack("#TubeStrike");
var timer = Stopwatch.StartNew();
stream.MatchingTweetReceived += (sender, args) =>
{
var tweet = args.Tweet;
if (timer.ElapsedMilliseconds > 1000)
{
Console.WriteLine("{0}, {1}", tweet.IdStr, tweet.Text);
timer.Restart();
}
};
stream.StartStreamMatchingAllConditions();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
}
You want to use the following code:
stream.StreamStopped += (sender, args) =>
{
stream.StartStreamMatchingAllConditions();
};
Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?
Example:
protected void btnSave_Click(object sender, EventArgs e)
{
int ixTest= SaveTest("123");
CreateTest(ixTest);
}
protected int SaveTest(int ixTestID)
{
SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
null,
ixTestID);
sp.Execute();
int ixTest= (int)sp.OutputValues[0];
return ixTest;
}
private long CreateTest(int ixTest)
{
long ixTestCustomer = CreateTestCustomer();
TestCustomer testCustomer= new TestCustomer();
try
{
testCustomer.TestCustomerId = ixTest;
testCustomer.InteractionId = ixTestCustomer ;
testCustomer.Save();
}
catch
{
Response.Redirect("pgCallSaveFailure.aspx");
}
m_saleDetail = new TestSaleDetail();
try
{
m_saleDetail.SaleId = sale.SaleId;
m_saleDetail.Save();
}
catch
{
Response.Redirect("pgCallSaveFailure.aspx");
}
return ixTestCustomer ;
}
I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?
Use the TransactionScope class
Code performs exact is given below. Hope you can get the idea.
public void SaveData()
{
SqlConnection connDB = new SqlConnection();
SqlCommand cmdExecuting = new SqlCommand();
try {
connDB = new SqlConnection(connection_string);
cmdExecuting.Connection = connDB;
connDB.Open();
cmdExecuting.Transaction = connDB.BeginTransaction();
int result = 0;
result = Method1(cmdExecuting);
if (result != 0) {
cmdExecuting.Transaction.Rollback();
return;
}
result = Method2(cmdExecuting);
if (result != 0) {
cmdExecuting.Transaction.Rollback();
return;
}
cmdExecuting.Transaction.Commit();
} catch (Exception ex) {
cmdExecuting.Transaction.Rollback();
} finally {
cmdExecuting.Dispose();
cmdExecuting = null;
connDB.Close();
connDB = null;
}
}
public int Method1(SqlCommand cmdExecuting)
{
cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 01";
cmdExecuting.CommandType = CommandType.StoredProcedure;
cmdExecuting.Parameters.Add("#para1", SqlDbType.Int);
cmdExecuting.Parameters("#para1").Value = value;
return cmdExecuting.ExecuteScalar();
}
public int Method2(SqlCommand cmdExecuting)
{
cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 02";
cmdExecuting.CommandType = CommandType.StoredProcedure;
cmdExecuting.Parameters.Add("#para1", SqlDbType.Int);
cmdExecuting.Parameters("#para1").Value = value;
return cmdExecuting.ExecuteScalar();
}