Developp Web Service REST - c#

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

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

How can I use parallel for in page load?

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

Service stops when connection is lost to the database

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

Send image as stream from WP8 to WCF with REST, without "header"

I have the connection working between my WP8 and WFC, I can send a picture as stream(byte-array)
Service side
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "FileUpload/{fileName}")]
string SendImageToDB(string fileName, Stream fileStream);
SendImageToDB
public void SendSteamToDB(byte[] stream)
{
MySqlConnection connection = new MySqlConnection(MyconSQL);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE PIC SET pic_link=#image WHERE id = '1';";
cmd.Parameters.Add("#image", MySqlDbType.Blob).Value = stream;
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
Console.Write("Error: {0}", ex.ToString());
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
The windows phone side
private void Upload_Click(object sender, EventArgs e)
{
string imageID = "test";
var client = new RestClient("http://192.168.1.130:53715//Service1.svc");
var request = new RestRequest("FileUpload/{imageName}", Method.POST);
request.AddUrlSegment("imageName", imageID);
request.AddFile("image/jpeg", myImage, imageID);
client.ExecuteAsync(request, response =>
{
});
try
{
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
MessageBox.Show("Upload succes!");
}
else
{
MessageBox.Show(response.StatusCode.ToString());
MessageBox.Show("Upload error!");
}
});
}
catch (Exception error)
{
MessageBox.Show("error" + error);
}
}
All this is working fine, there is just one problem the byte-array I put into the database have some kind of 'header'
did put the byte array in a .txt
What is the best way to avoid this?

From C# to Android via Socket. Can't find my mistake

The problem - I can't get this functions working. I see in LogCat that socket is connected to c# server, but I don't see received data. What I'm doing wrong?
Here is c# function with MessageBoxes for checking:
private void receiveConnection(){
Socket myHandler = null;
bool isConnected = false;
while (true)
{
if (!isConnected)
{
myHandler = wSocket.Accept();
isConnected = true;
MessageBox.Show("We have client!");
}
if (sendDataToAndroid)
{
try
{
sendDataToAndroid = false;
NetworkStream stream = new NetworkStream(myHandler);
StreamWriter sw = new StreamWriter(stream);
string myMsg = "";
myMsg += temp_F.Length + " ";
temp_F[0] = 3.151F;
temp_F[1] = 1.415F;
temp_F[2] = 5.572F;
temp_F[3] = 6.320F;
for (int i = 0; i < temp_F.Length; i++)
{
myMsg += temp_F[i] + " ";
}
byte[] msg = Encoding.ASCII.GetBytes(myMsg);
MessageBox.Show("Data to send: " + myMsg);
try
{
myHandler.Send(msg);
MessageBox.Show("Data has been sent!");
}
catch (Exception e) {
MessageBox.Show("Error while sending data!");
}
}
catch (Exception e)
{
isConnected = false;
myHandler.Close();
myHandler = null;
MessageBox.Show("Error while sending data...");
}
}
}
}
And here is Android function which is always trying to receive data:
public class SendThread implements Runnable {
public void run()
{
Socket socket = null;
BufferedReader in = null;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
}
}
// Get from the server
try {
Log.d("Connection: ", "connected");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = line.split(" ");
int currTempSize = Integer.parseInt(tokens[0]);
currentTemp = new double[currTempSize];
for (int i = 0; i < currTempSize; i++)
currentTemp[i] = (Double) nf.parse(tokens[i+1]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currTempSize; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
}
}
catch (Exception e) {
socket = null;
in = null;
Log.d("Connection: ", "lost.");
}
}
}
}
Your Java code reads a line at a time but you never sent a line terminator from C#.
You could append one to myMsg manually, or you could use the sw.WriteLine() method on your StreamWriter (which don't otherwise seem to be using). After calling sw.WriteLine() you will probably have to call sw.Flush().

Categories