Service stops when connection is lost to the database - c#

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);
}

Related

How to use FireError for an SSIS task script?

The following SSIS task script is supposed to insert data into three tables, however the script is only working locally but not on the server. I want to use FireError() / FireInformation in order to debug and find out what the reason for that. My problem is that I don't know how to write an FireError for this script. Can you please provide me with a small exmaple/hint or whatever you want to call it, so that I can apply it to my code.
#region Namespaces
using System;
using System.Data;
using System.Text;
using System.Net.Http;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Security.Cryptography;
using System.IO;
using System.IO.Compression;
using System.Web.Script.Serialization;
using SC_2e3723d7849249a59fd8f421bff5cab1;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void PreExecute()
{
base.PreExecute();
/*
* Add your code here
*/
}
/// <summary>
/// This method is called after all the rows have passed through this component.
///
/// You can delete this method if you don't need to do anything here.
/// </summary>
public override void PostExecute()
{
base.PostExecute();
/*
* Add your code here
*/
}
public override void CreateNewOutputRows()
{
/*
Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
*/
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string path = "/jobs-sdk/jobs/job";
string props = "customerAddrCity%2CcustomerAddrCountry%2CcustomerAddrLine1%2CcustomerAddrLine2%2CcustomerAddrPostalCode%2CcustomerAddrState%2CcustomerContact%2CcustomerName%2CcustomerPhoneNumber%2CdeviceId%2Cduplex%2CframeSizeX%2CframeSizeY%2ChpTrackingId%2Cimpressions%2Cimpressions1Color%2Cimpressions2Colors%2CimpressionsType%2Cinks%2CinkUnits%2CjdfJobId%2CjdfJobPartId%2CjobCompleteTime%2CjobCondition%2CjobCopies%2CjobElapseTime%2CjobId%2CjobLastEventTime%2CjobName%2CjobPriority%2CjobPriorityEnum%2CjobProgress%2CjobSubmitTime%2CjobSubstrate%2CjobType%2CjobWorkTimeEstimate%2ClastPrintedTime%2Clocation%2ClocationType%2Cmarker%2CparentDevId%2CparentJobId%2CqueueOrderIndex%2Cresolution%2Csubstrates%2CsubstrateUnits%2CticketTemplate";
string baseurl = Convert.ToString(Variables.strHPBaseUrl);
string startMarker = Convert.ToString(Variables.intMaxMarker);
string secret = Convert.ToString(Variables.strHPSecret);
string key = Convert.ToString(Variables.strHPKey);
string limit = Convert.ToString(Variables.intLimit);
int maxLoopIterations = Variables.intMaxLoopIterations;
Boolean fireAgain = true;
int counter;
int LoopIteration = 0;
string fullurl;
string CurrentMaxMarker = startMarker;
Boolean IsEndReached = false;
do
{
counter = 0;
LoopIteration++;
#region InnerDo
fullurl = baseurl + path + "?limit=" + limit + "&properties=" + props + "&startMarker=" + CurrentMaxMarker + "&direction=forward";
ComponentMetaData.FireInformation(10, "CallwebApi", "Processing has started with Url: " + fullurl, "", 0, fireAgain);
ComponentMetaData.FireInformation(10, "CallwebApi", "StartDoLoop with Iteration: " + LoopIteration, "", 0, fireAgain);
using (var client = new HttpClient())
{
CreateHmacHeaders("GET", path, client, secret, key);
try
{
HttpResponseMessage response = client.GetAsync(fullurl).Result;
if (response.IsSuccessStatusCode)
{
Stream a = response.Content.ReadAsStreamAsync().Result;
//a = new GZipStream(a, CompressionMode.Decompress);
StreamReader Reader = new StreamReader(a, Encoding.Default);
string Html = Reader.ReadToEnd();
a.Close();
JavaScriptSerializer js = new JavaScriptSerializer();
List<JobContext> Jobs = new List<JobContext>();
Jobs = js.Deserialize<List<JobContext>>(Html);
//loops trough foreach (var j in Jobs) and set Attributes to ContextBuffer.AddRow();
foreach (var j in Jobs)
{
counter++;
#region Job
ContextBuffer.AddRow();
string JobId = "";
try
{
ContextBuffer.JobName = Convert.ToString(j.JobName);
}
catch (NullReferenceException)
{
ContextBuffer.JobName_IsNull = true;
}
try
{
ContextBuffer.DeviceId = Convert.ToString(j.DeviceId);
}
catch (NullReferenceException)
{
ContextBuffer.DeviceId_IsNull = true;
}
try
{
ContextBuffer.Duplex = Convert.ToString(j.Duplex);
}
catch (NullReferenceException)
{
ContextBuffer.Duplex_IsNull = true;
}
try
{
ContextBuffer.Impressions = Convert.ToInt32(j.Impressions);
}
catch (NullReferenceException)
{
ContextBuffer.Impressions_IsNull = true;
}
try
{
ContextBuffer.Impressions1Color = Convert.ToInt32(j.Impressions1Color);
}
catch (NullReferenceException)
{
ContextBuffer.Impressions1Color_IsNull = true;
}
try
{
ContextBuffer.Impressions2Colors = Convert.ToInt32(j.Impressions2Colors);
}
catch (NullReferenceException)
{
ContextBuffer.Impressions2Colors_IsNull = true;
}
try
{
ContextBuffer.ImpressionsType = Convert.ToString(j.ImpressionsType);
}
catch (NullReferenceException)
{
ContextBuffer.ImpressionsType_IsNull = true;
}
try
{
ContextBuffer.InkUnits = Convert.ToString(j.InkUnits);
}
catch (NullReferenceException)
{
ContextBuffer.InkUnits_IsNull = true;
}
try
{
ContextBuffer.JobCompleteTime = Convert.ToString(j.JobCompleteTime);
}
catch (NullReferenceException)
{
ContextBuffer.JobCompleteTime_IsNull = true;
}
try
{
ContextBuffer.JobCopies = Convert.ToInt32(j.JobCopies);
}
catch (NullReferenceException)
{
ContextBuffer.JobCopies_IsNull = true;
}
try
{
ContextBuffer.JobElapseTime = Convert.ToInt64(j.JobElapseTime);
}
catch (NullReferenceException)
{
ContextBuffer.JobElapseTime_IsNull = true;
}
try
{
ContextBuffer.JobId = Convert.ToString(j.JobId);
JobId = Convert.ToString(j.JobId);
}
catch (NullReferenceException)
{
ContextBuffer.JobId_IsNull = true;
}
try
{
ContextBuffer.JobLastEventTime = Convert.ToString(j.JobLastEventTime);
}
catch (NullReferenceException)
{
ContextBuffer.JobLastEventTime_IsNull = true;
}
try
{
ContextBuffer.JobProgress = Convert.ToString(j.JobProgress);
}
catch (NullReferenceException)
{
ContextBuffer.JobProgress_IsNull = true;
}
try
{
ContextBuffer.JobSubmitTime = Convert.ToString(j.JobSubmitTime);
}
catch (NullReferenceException)
{
ContextBuffer.JobSubmitTime_IsNull = true;
}
try
{
ContextBuffer.JobType = Convert.ToString(j.JobType);
}
catch (NullReferenceException)
{
ContextBuffer.JobType_IsNull = true;
}
try
{
ContextBuffer.Marker = Convert.ToInt64(j.Marker);
CurrentMaxMarker = Convert.ToString(j.Marker);
}
catch (NullReferenceException)
{
ContextBuffer.Marker_IsNull = true;
}
try
{
ContextBuffer.ParentJobId = Convert.ToString(j.ParentJobId);
}
catch (NullReferenceException)
{
ContextBuffer.ParentJobId_IsNull = true;
}
try
{
ContextBuffer.SubstrateUnits = Convert.ToString(j.SubstrateUnits);
}
catch (NullReferenceException)
{
ContextBuffer.SubstrateUnits_IsNull = true;
}
#endregion
#region Substrates
if (j.Substrates != null)
{
foreach (var i in j.Substrates.Counts)
{
SubstratesBuffer.AddRow();
try
{
SubstratesBuffer.Name = Convert.ToString(i.Name);
}
catch (NullReferenceException)
{
SubstratesBuffer.Name_IsNull = true;
}
try
{
SubstratesBuffer.AmountUsed = Convert.ToInt32(i.AmountUsed);
}
catch (NullReferenceException)
{
SubstratesBuffer.AmountUsed_IsNull = true;
}
try
{
SubstratesBuffer.JobId = JobId;
}
catch (NullReferenceException)
{
SubstratesBuffer.JobId_IsNull = true;
}
}
}
#endregion
#region inks
if (j.Inks != null)
{
foreach (var i in j.Inks.Counts)
{
InksBuffer.AddRow();
try
{
InksBuffer.Name = Convert.ToString(i.Name);
}
catch (NullReferenceException)
{
InksBuffer.Name_IsNull = true;
}
try
{
InksBuffer.AmountUsed = Convert.ToInt32(i.AmountUsed);
}
catch (NullReferenceException)
{
InksBuffer.AmountUsed_IsNull = true;
}
try
{
InksBuffer.JobId = JobId;
}
catch (NullReferenceException)
{
InksBuffer.JobId_IsNull = true;
}
}
}
#endregion
}
}
else //response.IsSuccessStatusCode
{
ErrorBuffer.AddRow();
ErrorBuffer.ErrorMessage = "Status code is unsuccessful";
ErrorBuffer.ErrorMessageStacktrace = SubstringStringByLength(response.ReasonPhrase, 4000);
}
}
catch (Exception e) // From make call to parse Objkect
{
ErrorBuffer.AddRow();
ErrorBuffer.ErrorMessage = SubstringStringByLength(e.Message.ToString(), 950);
ErrorBuffer.ErrorMessageStacktrace = SubstringStringByLength(e.StackTrace.ToString(), 4000);
}
}
#endregion
if (LoopIteration >= maxLoopIterations)
{
IsEndReached = true;
}
if (counter <= 0)
{
IsEndReached = true;
}
} while (IsEndReached == false);
}
private static void CreateHmacHeaders(string method, string path, HttpClient client, string secret, string key)
{
string timeStamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
string stringToSign = method + " " + path + timeStamp;
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
byte[] bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
string signature = BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower();
string auth = key + ":" + signature;
client.DefaultRequestHeaders.Add("x-hp-hmac-authentication", auth);
client.DefaultRequestHeaders.Add("x-hp-hmac-date", timeStamp);
client.DefaultRequestHeaders.Add("x-hp-hmac-algorithm", "SHA256");
}
private string SubstringStringByLength(string LongString, int maxLength)
{
int maxLengthInoutString = (LongString.Length > maxLength ? maxLength : LongString.Length);
String OutputString = (LongString != null)
? LongString.Substring(0, maxLengthInoutString)
: "";
return OutputString;
}
}
Books online provides the
FireError
FireInformation
Sample code from https://stackoverflow.com/a/28907522/181965 which demonstrates the differences between the Script Task vs Script Component (which you're using) method signatures
bool fireAgain = false;
this.Dts.Events.FireInformation(0, "my sub", "info", string.Empty, 0, ref fireAgain);
// Note, no cancel available
this.Dts.Events.FireError(0, "my sub", "error", string.Empty, 0);
As to where you'd plumb this into your existing code, I don't know what your design goals are but I'd assume it'd fit in where your ErrorBuffer calls are - although FireError will blow up processing so maybe not? Maybe you want to accumulate all the bad rows into a global variable and in the PostEvent section, enumerate through them so you can see all the bad rows. /shrug

Multithreading: Confusion between the publisher thread and the subscriber thread

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

Developp Web Service REST

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

Auto BrithdayMail send by using services

Hello I try to create auto emails send by service file but there is some problem.
this is BrithdayEmailService.cs file.
namespace BirthdayEmailSevice
{
partial class BirthdayEmailService : ServiceBase
{
private Timer scheduleTimer = null;
private DateTime lastRun;
private bool flag;
public BirthdayEmailService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailLog");
}
eventLogEmail.Source = "EmailSource";
eventLogEmail.Log = "EmailLog";
scheduleTimer = new Timer();
scheduleTimer.Interval = 1 * 5 * 60 * 1000;
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
flag = true;
lastRun = DateTime.Now;
scheduleTimer.Start();
eventLogEmail.WriteEntry("Started");
}
protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (flag == true)
{
ServiceEmailMethod();
lastRun = DateTime.Now;
flag = false;
}
else if (flag == false)
{
if (lastRun.Date < DateTime.Now.Date)
{
ServiceEmailMethod();
}
}
}
private void ServiceEmailMethod()
{
eventLogEmail.WriteEntry("In Sending Email Method");
EmailComponent.GetEmailIdsFromDB getEmails = new EmailComponent.GetEmailIdsFromDB();
getEmails.connectionString = ConfigurationManager.ConnectionStrings["CustomerDBConnectionString"].ConnectionString;
getEmails.storedProcName = "GetBirthdayBuddiesEmails";
System.Data.DataSet ds = getEmails.GetEmailIds();
EmailComponent.Email email = new EmailComponent.Email();
email.fromEmail = "example#gmail.com";
email.fromName = "example Name";
email.subject = "Birthday Wishes";
email.smtpServer = "smtp.gmail.com";
email.smtpCredentials = new System.Net.NetworkCredential("example1#gmail.com", "example1 password");
foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
{
email.messageBody = "<h4>Hello " + dr["CustomerName"].ToString() + "</h4><br/><h3>We Wish you a very Happy" +
"Birthday to You!!! Have a bash...</h3><br/><h4>Thank you.</h4>";
bool result = email.SendEmailAsync(dr["CustomerEmail"].ToString(), dr["CustomerName"].ToString());
if (result == true)
{
eventLogEmail.WriteEntry("Message Sent SUCCESS to - " + dr["CustomerEmail"].ToString() +
" - " + dr["CustomerName"].ToString());
}
else
{
eventLogEmail.WriteEntry("Message Sent FAILED to - " + dr["CustomerEmail"].ToString() +
" - " + dr["CustomerName"].ToString());
}
}
}
}
On scheduleTimer = new Timer(); got error
(This member is defined more than one)
Error:
Ambiguity between 'BirthdayEmailService.BirthdayEmailService.scheduleTimer' and 'BirthdayEmailService.BirthdayEmailService.scheduleTimer'
Also got error on BirthdayEmailService.Designer.cs this is file of design tool of service
error is :
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.eventLogEmail = new System.Diagnostics.EventLog();
**this.scheduleTimer = new System.Windows.Forms.Timer(this.components);**
((System.ComponentModel.ISupportInitialize)(this.eventLogEmail)).BeginInit();
//
// BirthdayEmailService
//
this.ServiceName = "BirthdayEmailService";
((System.ComponentModel.ISupportInitialize)(this.eventLogEmail)).EndInit();
}
those part is bold there is getting error as same as.
(This member is defined more than one)
Error:
Ambiguity between 'BirthdayEmailService.BirthdayEmailService.scheduleTimer' and 'BirthdayEmailService.BirthdayEmailService.scheduleTimer'
It could be because the name of the class and the namespace are the same one. See this post.

Windows service shuts off after running first record

I have a windows service that is supposed to check for a record, email a report for that record, delete the record and then repeat for the table. It checks for the record, emails a report for the first record then shuts off. Any ideas??
Service code:
namespace ReportSender
{
public partial class EmailReportService : ServiceBase
{
private EmailReportApp _app = new EmailReportApp();
public Timer serviceTimer = new Timer();
public EmailReportService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//Set interval (from App Settings) and enable timer
serviceTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_OnElapsed);
//Use Conversion utility to determine next start date/time based on properties, use DateTime.Subtract() to find milliseconds difference between Now and the next start time
//serviceTimer.Interval = Date.AddInterval(Properties.Settings.Default.IntervalType, Properties.Settings.Default.Interval).Subtract(DateTime.Now).TotalMilliseconds;
serviceTimer.Interval = 600000;
serviceTimer.Enabled = true;
}
protected override void OnStop()
{
//Stop and disable timer
serviceTimer.Enabled = false;
}
private void ServiceTimer_OnElapsed(object source, ElapsedEventArgs e)
{
try
{
//Stop the timer to prevent overlapping runs
serviceTimer.Stop();
//Start service
//Run your app.Start() code
_app = new EmailReportApp();
_app.Start();
}
catch (Exception ex)
{
}
finally
{
//Re-start the timer
serviceTimer.Start();
}
}
}
}
Code the service is supposed to execute:
namespace ReportSender
{
class EmailReportApp
{
// Private fields
private Thread _thread;
private EventLog _log;
private void Execute()
{
try
{
// Check for a new record
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
dc.reportsSent1s.DeleteOnSubmit(item);
dc.SubmitChanges();
}
}
catch (ThreadAbortException ex)
{
_log.WriteEntry(ex.StackTrace.ToString());
}
}
public void Start()
{
if (!EventLog.SourceExists("EventLoggerSource"))
EventLog.CreateEventSource("EventLoggerSource", "Event Logger");
_log = new EventLog("EventLoggerSource");
_log.Source = "EventLoggerSource";
_thread = new Thread(new ThreadStart(Execute));
_thread.Start();
}
public void Stop()
{
if (_thread != null)
{
_thread.Abort();
_thread.Join();
}
}
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("234#acmetaxabstracts.com", "georr#gmail.com", "Report for BRT # " + matchedAdd, "Attached if the Tax Information Certificate for the aboved captioned BRT Number");
MailAddress copy = new MailAddress("a123s#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.**.***.**");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
}
catch (Exception ex)
{
}
}
}
}
The 'ServiceBase' is losing scope once the OnStart method is called. A 'ManualResetEvent' will keep the service open for you.
Use member:
ManualResetEvent stop = new ManualResetEvent(false);
Try this in your main Start():
do
{
try
{
_app = new EmailReportApp();
_app.Start();
}
catch(Exception e)
{
... handle error or log however you want
}
}
while(!stop.WaitOne(0, false))
in Stop(), make sure to do stop.Set()

Categories