I am trying to get all messages id from my email,but it doesn't work. I get this answer:
$ BAD [CLIENTBUG] Unrecognised command\r\n\0\0\0\0.
How do I get the correct response?
string uids1 = ReceiveResponse("$ SELECT INBOX\r\n");
string uids = ReceiveResponse("$ UID SEARCH ALL" + "\r\n");//query to server
private string ReceiveResponse(string command)
{
_sb = new StringBuilder();
try
{
if (command != "")
{
if (_tcpClient.Connected)
{
_dummy = Encoding.ASCII.GetBytes(command);
_ssl.Write(_dummy, 0, _dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
_ssl.Flush();
_buffer = new byte[2048];
_tcpClient.ReceiveTimeout = 20000;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
do
{
try
{
bytes = _ssl.Read(_buffer, 0, 2048);
var msg = Encoding.UTF8.GetString(_buffer);
_sb.Append(msg);
Thread.Sleep(3);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
} while (_tcpClient.Available > 0);
string text = _sb.ToString().Replace("\0", string.Empty);
return _sb.ToString();
}
catch (Exception ex)//if we have some problem show message
{
throw new ApplicationException(ex.Message);
}
}
Related
public class GSMModemConnection
{
I made a windows service for receiving SMS I'm using Wavecom Gsm modem 1306B. But after some second I got an
Exception: No data received from phone. I have searched in StackOverflow I found this link Exception: No data received from phone
someone pointed about to create a retry mechanism but I don't know how to implement it.
static void Main(string[] args)
{
GSMModemConnection gsm = new GSMModemConnection();
var result = gsm.OpenPort();
Console.WriteLine(result.PortName);
while (true)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
ShortMessage execResult = gsm.ReadSMS(result, "AT+CMGL=\"ALL\"");
Console.WriteLine(execResult.Message);
Console.WriteLine(execResult.Status);
}
}
public class GSMModemConnection
{
public AutoResetEvent receiveNow;
//string strPortName, string strBaudRate
public SerialPort OpenPort()
{
receiveNow = new AutoResetEvent(false);
SerialPort port = new SerialPort();
port.PortName = "COM3";
port.BaudRate = 115200 /*Convert.ToInt32(strBaudRate)*/; //updated by Anila (9600)
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Parity = Parity.None;
port.ReadTimeout = 300;
port.WriteTimeout = 300;
port.Encoding = Encoding.GetEncoding("iso-8859-1");
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.DtrEnable = true;
port.RtsEnable = true;
return port;
}
//Close Port
public void ClosePort(SerialPort port)
{
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
port = null;
}
//Execute AT Command
public string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
{
try
{
//receiveNow = new AutoResetEvent();
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
//Thread.Sleep(3000); //3 seconds
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
}
catch (Exception ex)
{
throw new ApplicationException(errorMessage, ex);
}
}
//Receive data from port
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
receiveNow.Set();
}
public string ReadResponse(SerialPort port, int timeout)
{
string buffer = string.Empty;
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
return buffer;
}
public ShortMessage ReadSMS(SerialPort port, string p_strCommand)
{
// Set up the phone and read the messages
ShortMessage messages = null;
try
{
#region Execute Command
// Check connection
var a = ExecCommand(port, "AT", 300, "No phone connected");
// Use message format "Text mode"
var b = ExecCommand(port, "AT+CMGF=1\r", 300, "Failed to set message format.");
// Use character set "PCCP437"
//var c = ExecCommand(port, "AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
// Select SIM storage
//var d = ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
// Read the messages
string input = ExecCommand(port, p_strCommand, 5000, "Failed to read the messages.");
#endregion
#region Parse messages
messages = ParseMessages(input);
#endregion
}
catch (Exception ex)
{
throw ex;
}
if (messages != null)
return messages;
else
return null;
}
public ShortMessage ParseMessages(string input)
{
ShortMessage msg = new ShortMessage();
//ShortMessageCollection messages = new ShortMessageCollection();
try
{
Regex r = new Regex(#"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
Match m = r.Match(input);
while (m.Success)
{
//msg.Index = int.Parse(m.Groups[1].Value);
msg.Index = int.Parse(m.Groups[1].Value);
msg.Status = m.Groups[2].Value;
msg.Sender = m.Groups[3].Value;
msg.Alphabet = m.Groups[4].Value;
msg.Sent = m.Groups[5].Value;
msg.Message = m.Groups[6].Value;
//messages.Add(msg);
m = m.NextMatch();
}
}
catch (Exception ex)
{
throw ex;
}
return msg;
}
}
You DO have a retry mechanism in place with the DO-WHILE loop from the following expression:
public string ReadResponse(SerialPort port, int timeout)
{
string buffer = string.Empty;
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
return buffer;
}
What you can do is reduce the granularity of the error report mechanism.
In this case, for example, the line throw new ApplicationException() will break the loop and get captured in the Exec() function, then thrown again. If you just want to wait for the loop to close and the DO-WHILE loop to get executed, I would replace the following part of the code:
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
With:
else
{
if (buffer.Length > 0)
bufferError += "Response received is incomplete.\n";
else
bufferError += "No data received from phone.\n";
}
Why?
After the DO-WHILE loop, the buffer will either return string.Empty or some value.
Up in the code, you have:
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
Basically, if the returned buffer is string.Empty an Exception will be thrown again.
By returning the buffer Error, you can decide later how you want to handle it but the DO-WHILE loop will run at least once up until the condition from the WHILE expression is met.
Rest of the code should look like this:
//Thread.Sleep(3000); //3 seconds
string bufferErrors = string.Empty;
string input = ReadResponse(port, responseTimeout, bufferErrors);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
if (!string.IsNullOrWhiteSpace(bufferErrors))
{
//Handle bufferErrors
}
return input;
Remember to declare the out parameter in ReadResponse
public string ReadResponse(SerialPort port, int timeout, out string bufferError)
{
string buffer = string.Empty;
bufferError = string.Empty;
I'm using this code to modify a pdf tmeplate to add specific details to it,
private static byte[] GeneratePdfFromPdfFile(byte[] file, string landingPage, string code)
{
try
{
using (var ms = new MemoryStream())
{
using (var reader = new PdfReader(file))
{
using (var stamper = new PdfStamper(reader, ms))
{
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + code + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
stamper.Writer.SetOpenAction(act);
stamper.Close();
reader.Close();
return ms.ToArray();
}
}
}
}
catch(Exception ex)
{
File.WriteAllText(HttpRuntime.AppDomainAppPath + #"AttachmentException.txt", ex.Message + ex.StackTrace);
return null;
}
}
this Method is being called from this Method:
public static byte[] GenerateAttachment(AttachmentExtenstion type, string Contents, string FileName, string code, string landingPage, bool zipped, byte[] File = null)
{
byte[] finalVal = null;
try
{
switch (type)
{
case AttachmentExtenstion.PDF:
finalVal = GeneratePdfFromPdfFile(File, landingPage, code);
break;
case AttachmentExtenstion.WordX:
case AttachmentExtenstion.Word:
finalVal = GenerateWordFromDocFile(File, code, landingPage);
break;
case AttachmentExtenstion.HTML:
finalVal = GenerateHtmlFile(Contents, code, landingPage);
break;
}
return zipped ? _getZippedFile(finalVal, FileName) : finalVal;
}
catch(Exception ex)
{
return null;
}
}
and here is the main caller,
foreach (var item in Recipients)
{
//...
//....
item.EmailAttachment = AttachmentGeneratorEngine.GenerateAttachment(_type, "", item.AttachmentName, item.CMPRCode, _cmpTmp.LandingDomain, _cmpTmp.AttachmentZip.Value, _cmpTmp.getFirstAttachment(item.Language, item.DefaultLanguage));
}
The AttachmentGeneratorEngine.GenerateAttachment method is being called approx. 4k times, because I'm adding a specific PDF file from a PDF template for every element in my List.
recently I started having this exception:
Exception of type 'System.OutOfMemoryException' was thrown. at System.IO.MemoryStream.ToArray()
I already implemented IDisposible in the classes and and I made sure that all of them are being released.
Note: it was running before very smoothely and also I double checked the system's resources - 9 GB is used out of 16 GB, so I had enough memory available.
==========================================
Update:
Here is the code that loops through the list
public static bool ProcessGroupLaunch(string groupCode, int customerId, string UilangCode)
{
CampaignGroup cmpGList = GetCampaignGroup(groupCode, customerId, UilangCode)[0];
_campaigns = GetCampaigns(groupCode, customerId);
List<CampaignRecipientLib> Recipients = GetGroupRcipientsToLaunch(cmpGList.ID, customerId);
try
{
foreach (var item in _campaigns)
item.Details = GetCampaignDetails(item.CampaignId.Value, UilangCode);
Stopwatch stopWatch = new Stopwatch();
#region single-threaded ForEach
foreach (var item in Recipients)
{
CampaignLib _cmpTmp = _campaigns.FirstOrDefault(x => x.CampaignId.Value == item.CampaignId);
bool IncludeAttachment = _cmpTmp.IncludeAttachment ?? false;
bool IncludeAttachmentDoubleBarrel = _cmpTmp.IncludeAttachmentDoubleBarrel ?? false;
if (IncludeAttachment)
{
if (_cmpTmp.AttachmentExtension.ToLower().Equals("doc") || (_cmpTmp.AttachmentExtension.ToLower().Equals("docx")))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.Word;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("ppt") || (_cmpTmp.AttachmentExtension.ToLower().Equals("pptx")))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.PowePoint;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("xls") || (_cmpTmp.AttachmentExtension.ToLower().Equals("xlsx")))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.Excel;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("pdf"))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.PDF;
else if (_cmpTmp.AttachmentExtension.ToLower().Equals("html"))
_type = AttachmentGeneratorEngine.AttachmentExtenstion.HTML;
}
//set "recpient" details
item.EmailFrom = _cmpTmp.EmailFromPrefix + "#" + _cmpTmp.EmailFromDomain;
item.EmailBody = GetChangedPlaceHolders((_cmpTmp.getBodybyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage)), item.ID, _cmpTmp.CustomerId.Value, _cmpTmp.CampaignId.Value);
if (item.EmailBody.Contains("[T-LandingPageLink]"))
{
//..
}
if (item.EmailBody.Contains("[T-FeedbackLink]"))
{
//..
}
if (item.EmailBody.Contains("src=\".."))
{
//..
}
//set flags to be used by the SMTP Queue and Scheduler
item.ReadyTobeSent = true;
item.PickupReady = false;
//add attachment to the recipient, if any.
if (IncludeAttachment)
{
item.AttachmentName = _cmpTmp.getAttachmentSubjectbyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage) + "." + _cmpTmp.AttachmentExtension.ToLower();
try
{
if (_type == AttachmentGeneratorEngine.AttachmentExtenstion.PDF || _type == AttachmentGeneratorEngine.AttachmentExtenstion.WordX || _type == AttachmentGeneratorEngine.AttachmentExtenstion.Word)
item.EmailAttachment = AttachmentGeneratorEngine.GenerateAttachment(_type, "", item.AttachmentName, item.CMPRCode, _cmpTmp.LandingDomain, _cmpTmp.AttachmentZip.Value, _cmpTmp.getFirstAttachment(item.Language, item.DefaultLanguage));
else item.EmailAttachment = AttachmentGeneratorEngine.GenerateAttachment(_type, value, item.AttachmentName, item.CMPRCode, _cmpTmp.LandingDomain, _cmpTmp.AttachmentZip.Value);
item.AttachmentName = _cmpTmp.AttachmentZip.Value ? (_cmpTmp.getAttachmentSubjectbyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage) + ".zip") :
_cmpTmp.getAttachmentSubjectbyLangCode(string.IsNullOrEmpty(item.Language) ? item.DefaultLanguage : item.Language, item.DefaultLanguage) + "." + _cmpTmp.AttachmentExtension.ToLower();
}
catch (Exception ex)
{
}
}
else
{
item.EmailAttachment = null;
item.AttachmentName = null;
}
}
#endregion
stopWatch.Stop();
bool res = WriteCampaignRecipientsLaunch(ref Recipients);
return res;
}
catch (Exception ex)
{
Recipients.ForEach(i => i.Dispose());
cmpGList.Dispose();
Recipients = null;
cmpGList = null;
return false;
}
finally
{
Recipients.ForEach(i => i.Dispose());
cmpGList.Dispose();
Recipients = null;
cmpGList = null;
}
}
Anyone of you know what is the type of service to check the credit balance for the modem using *[number]# ?
I am trying to check balance by using this code.
public AutoResetEvent receiveNow;
public string CheckBalance(SerialPort port)
{
string balance = string.Empty;
try
{
#region Execute Command
//string recievedData = SendATCommand(port, "AT", 300, "No phone connected at ");
string recievedData = SendATCommand(port, "AT", 300, "No phone connected at ");
recievedData = SendATCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
String command = #"AT+CUSD=1,""*121#"",15";
recievedData = SendATCommand(port, command, 5000, "Failed to count SMS message");
balance = recievedData;
#endregion
}
catch (Exception ex)
{
ErrorLog(ex.Message);
}
return balance;
}
public string SendATCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
{
string input = string.Empty;
try
{
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
ErrorLog("No success message was received.");
}
catch (Exception ex)
{
ErrorLog(ex.Message);
}
return input;
}
public string ReadResponse(SerialPort port, int timeout)
{
string serialPortData = string.Empty;
try
{
do
{
if (receiveNow.WaitOne(timeout, false))
{
string data = port.ReadExisting();
serialPortData += data;
}
else
{
if (serialPortData.Length > 0)
ErrorLog("Response received is incomplete.");
else
ErrorLog("No data received from phone.");
}
}
while (!serialPortData.EndsWith("\r\nOK\r\n") && !serialPortData.EndsWith("\r\n> ") && !serialPortData.EndsWith("\r\nERROR\r\n"));
}
catch (Exception ex)
{
ErrorLog(ex.Message);
}
return serialPortData;
}
first two exec command returns ok,but the third exec command returns error.
USSD code is working from providers mobile partner application,
what sets of AT command do i need to send to handle ussd application properly?
I am running a loop in C# that reads a file and make updates to the MySQL database with MySQL ODBC 5.1 driver in a Windows 8 64-bit environment.
The operations is simple
Count +1
See if file exists
Load XML file(XDocument)
Fetch data from XDocument
Open ODBCConnection
Run a couple of Stored Procedures against the MySQL database to store data
Close ODBCConnection
The problem is that after a while it will hang on for example a OdbcCommand.ExecuteNonQuery. It is not always the same SP that it will hang on?
This is a real problem, I need to loop 60 000 files but it only last around 1000 at a time.
Edit 1:
The problem seemse to accure here hever time :
public bool addPublisherToGame(int inPublisherId, int inGameId)
{
string sqlStr;
OdbcCommand commandObj;
try
{
sqlStr = "INSERT INTO games_publisher_binder (gameId, publisherId) VALUE(?,?)";
commandObj = new OdbcCommand(sqlStr, mainConnection);
commandObj.Parameters.Add("#gameId", OdbcType.Int).Value = inGameId;
commandObj.Parameters.Add("#publisherId", OdbcType.Int).Value = inPublisherId;
if (Convert.ToInt32(executeNonQuery(commandObj)) > 0)
return true;
else
return false;
}
catch (Exception ex)
{
throw (loggErrorMessage(this.ToString(), "addPublisherToGame", ex, -1, "", ""));
}
finally
{
}
}
protected object executeNonQuery(OdbcCommand inCommandObj)
{
try
{
//FileStream file = new FileStream("d:\\test.txt", FileMode.Append, FileAccess.Write);
//System.IO.StreamWriter stream = new System.IO.StreamWriter(file);
//stream.WriteLine(DateTime.Now.ToString() + " - " + inCommandObj.CommandText);
//stream.Close();
//file.Close();
//mainConnection.Open();
return inCommandObj.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (ex);
}
}
I can see that the in parameters is correct
The open and close of the connection is done in a top method for ever loop (with finally).
Edit 2:
This is the method that will extract the information and save to database :
public Boolean addBoardgameToDatabase(XElement boardgame, GameFactory gameFactory)
{
int incomingGameId = -1;
XElement tmpElement;
string primaryName = string.Empty;
List<string> names = new List<string>();
GameStorage externalGameStorage;
int retry = 3;
try
{
if (boardgame.FirstAttribute != null &&
boardgame.FirstAttribute.Value != null)
{
while (retry > -1)
{
try
{
incomingGameId = int.Parse(boardgame.FirstAttribute.Value);
#region Find primary name
tmpElement = boardgame.Elements("name").Where(c => c.Attribute("primary") != null).FirstOrDefault(a => a.Attribute("primary").Value.Equals("true"));
if (tmpElement != null)
primaryName = tmpElement.Value;
else
return false;
#endregion
externalGameStorage = new GameStorage(incomingGameId,
primaryName,
string.Empty,
getDateTime("1/1/" + boardgame.Element("yearpublished").Value),
getInteger(boardgame.Element("minplayers").Value),
getInteger(boardgame.Element("maxplayers").Value),
boardgame.Element("playingtime").Value,
0, 0, false);
gameFactory.updateGame(externalGameStorage);
gameFactory.updateGameGrade(incomingGameId);
gameFactory.removeDesignersFromGame(externalGameStorage.id);
foreach (XElement designer in boardgame.Elements("boardgamedesigner"))
{
gameFactory.updateDesigner(int.Parse(designer.FirstAttribute.Value), designer.Value);
gameFactory.addDesignerToGame(int.Parse(designer.FirstAttribute.Value), externalGameStorage.id);
}
gameFactory.removePublishersFromGame(externalGameStorage.id);
foreach (XElement publisher in boardgame.Elements("boardgamepublisher"))
{
gameFactory.updatePublisher(int.Parse(publisher.FirstAttribute.Value), publisher.Value, string.Empty);
gameFactory.addPublisherToGame(int.Parse(publisher.FirstAttribute.Value), externalGameStorage.id);
}
foreach (XElement element in boardgame.Elements("name").Where(c => c.Attribute("primary") == null))
names.Add(element.Value);
gameFactory.removeGameNames(incomingGameId);
foreach (string name in names)
if (name != null && name.Length > 0)
gameFactory.addGameName(incomingGameId, name);
return true;
}
catch (Exception)
{
retry--;
if (retry < 0)
return false;
}
}
}
return false;
}
catch (Exception ex)
{
throw (new Exception(this.ToString() + ".addBoardgameToDatabase : " + ex.Message, ex));
}
}
And then we got one step higher, the method that will trigger addBoardgameToDatabase :
private void StartThreadToHandleXmlFile(int gameId)
{
FileInfo fileInfo;
XDocument xmlDoc;
Boolean gameAdded = false;
GameFactory gameFactory = new GameFactory();
try
{
fileInfo = new FileInfo(_directory + "\\" + gameId.ToString() + ".xml");
if (fileInfo.Exists)
{
xmlDoc = XDocument.Load(fileInfo.FullName);
if (addBoardgameToDatabase(xmlDoc.Element("boardgames").Element("boardgame"), gameFactory))
{
gameAdded = true;
fileInfo.Delete();
}
else
return;
}
if (!gameAdded)
{
gameFactory.InactivateGame(gameId);
fileInfo.Delete();
}
}
catch (Exception)
{ throw; }
finally
{
if(gameFactory != null)
gameFactory.CloseConnection();
}
}
And then finally the top level :
public void UpdateGames(string directory)
{
DirectoryInfo dirInfo;
FileInfo fileInfo;
Thread thread;
int gameIdToStartOn = 1;
dirInfo = new DirectoryInfo(directory);
if(dirInfo.Exists)
{
_directory = directory;
fileInfo = dirInfo.GetFiles("*.xml").OrderBy(c=> int.Parse(c.Name.Replace(".xml",""))).FirstOrDefault();
gameIdToStartOn = int.Parse(fileInfo.Name.Replace(".xml", ""));
for (int gameId = gameIdToStartOn; gameId < 500000; gameId++)
{
try
{ StartThreadToHandleXmlFile(gameId); }
catch(Exception){}
}
}
}
Use SQL connection pooling by adding "Pooling=true" to your connectionstring.
Make sure you properly close the connection AND the file.
You can create one large query and execute it only once, I think it is a lot faster then 60.000 loose queries!
Can you show a bit of your code?
I have seen references on how to cast to a proxy such as:
((IContextChannel)client.InnerChannel).OperationTimeout = new TimeSpan(0,0,240);
to set an operationtimeout but I am using client = channelFactory.CreateChannel();
How do I cast the channel to IContextChannel? I hope this makes sense. I don't have a complete grasp on channels in WCF.
Thanks
Alexei,
Not sure how to implement your suggestion.
In this code how would I set an operationtimeout?
try
{
Binding multipleTokensBinding = MultiAuthenticationFactorBinding.CreateMultiFactorAuthenticationBinding();
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
EndpointAddress endpointaddress = new EndpointAddress(new Uri("https://justsomeservice"), EndpointIdentity.CreateDnsIdentity("someone.com"));
ChannelFactory<TransActionSvc.TransactionPortType> channelFactory = null;
TransActionSvc.TransactionPortType client = null;
channelFactory = new ChannelFactory<TransActionSvc.TransactionPortType>(multipleTokensBinding, endpointaddress);
BindingElementCollection elements = channelFactory.Endpoint.Binding.CreateBindingElements();
elements.Find<SecurityBindingElement>().IncludeTimestamp = true;
channelFactory.Endpoint.Binding = new CustomBinding(elements);
channelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.Root, X509FindType.FindBySerialNumber, "xxx");
channelFactory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.Root, X509FindType.FindBySerialNumber, "xxx");
channelFactory.Credentials.UserName.UserName = Properties.Settings.Default.UserName;
channelFactory.Credentials.UserName.Password = Properties.Settings.Default.Password;
TransActionSvc.fetchTranDataAsAttachmentRequest req = new WF_Prod_Svc.TransActionSvc.fetchTranDataAsAttachmentRequest();
TransActionSvc.fetchTranDataAsAttachmentResponse res = new WF_Prod_Svc.TransActionSvc.fetchTranDataAsAttachmentResponse();
TransActionSvc.FetchTranDataAsAttachmentRq_Type reqtype = new WF_Prod_Svc.TransActionSvc.FetchTranDataAsAttachmentRq_Type();
TransActionSvc.FetchTranDataAsAttachmentRs_Type restype = new WF_Prod_Svc.TransActionSvc.FetchTranDataAsAttachmentRs_Type();
TransActionSvc.EndpointReferenceType endpntref = new WF_Prod_Svc.TransActionSvc.EndpointReferenceType();
XmlAttribute actionAttrib1 = doc.CreateAttribute("soapenv", "mustUnderstand", "http://schemas.xmlsoap.org/soap/envelope/");
actionAttrib1.Value = "0";
XmlAttribute actionAttrib2 = doc.CreateAttribute("xmlns");
actionAttrib2.Value = "http://schemas.xmlsoap.org/ws/2003/03/addressing";
XmlAttribute[] objAcctionAtrb = new XmlAttribute[2];
objAcctionAtrb.SetValue(actionAttrib1, 0);
objAcctionAtrb.SetValue(actionAttrib2, 1);
TransActionSvc.AttributedURI action = new WF_Prod_Svc.TransActionSvc.AttributedURI();
action.AnyAttr = objAcctionAtrb;
action.Value = "Transaction";
TransActionSvc.AttributedURI messageid = new WF_Prod_Svc.TransActionSvc.AttributedURI();
messageid.AnyAttr = objAcctionAtrb;
messageid.Value = System.Guid.NewGuid().ToString();
TransActionSvc.AttributedURI to = new WF_Prod_Svc.TransActionSvc.AttributedURI();
to.AnyAttr = objAcctionAtrb;
to.Value = "XGI";
TransActionSvc.EndpointReferenceType endpointreference = new WF_Prod_Svc.TransActionSvc.EndpointReferenceType();
TransActionSvc.ReferencePropertiesType referenceproperties = new WF_Prod_Svc.TransActionSvc.ReferencePropertiesType();
if (Svc_Division.Parsed) { reqtype.division = Svc_Division.StringValue; }
try{reqtype.startDate = Convert.ToDateTime(Svc_StartDate.StringValue);}
catch (FormatException ex){LogMessageToFile("Invalid Start date. " + ex.Message);}
try{reqtype.endDate = Convert.ToDateTime(Svc_EndDate.StringValue);}
catch (FormatException ex){LogMessageToFile("Invalid End date. " + ex.Message);}
if (Svc_DateType.StringValue == "T")
{
reqtype.transactionDateType = TransActionSvc.TransactionDateType_Enum.TransactionDate;
}
else
{
reqtype.transactionDateType = TransActionSvc.TransactionDateType_Enum.PostingDate;
}
switch (Svc_TransType.StringValue)
{
case "OOP":
reqtype.transactionType = TransActionSvc.TransactionType_Enum.OOP;
break;
case "CHARGES":
reqtype.transactionType = TransActionSvc.TransactionType_Enum.CHARGES;
break;
default:
reqtype.transactionType = TransActionSvc.TransactionType_Enum.ALL;
break;
}
System.Xml.XmlElement companyid = doc.CreateElement("companyId");
companyid.InnerText = Properties.Settings.Default.CompanyID;
System.Xml.XmlElement[] objectarray = new System.Xml.XmlElement[1];
objectarray.SetValue(companyid, 0);
referenceproperties.Any = objectarray;
endpointreference.ReferenceProperties = referenceproperties;
req.Action = action;
req.MessageID = messageid;
req.To = to;
req.ReplyTo = endpointreference;
req.fetchTranDataAsAttachment = reqtype;
try
{
client = channelFactory.CreateChannel();
//THIS DOES NOT WORK
client.OperationTimeout = new TimeSpan(0,10,0);
res = client.fetchTranDataAsAttachment(req);
if (res.fetchTranDataAsAttachmentResponse1.WFFaultList != null)
{
LogLine = string.Format("FaultCode({0});FaultType({1});FaultReason({2});Severity({3})",
res.fetchTranDataAsAttachmentResponse1.WFFaultList[0].faultCode,
res.fetchTranDataAsAttachmentResponse1.WFFaultList[0].faultType,
res.fetchTranDataAsAttachmentResponse1.WFFaultList[0].faultReasonText,
res.fetchTranDataAsAttachmentResponse1.WFFaultList[0].severity);
}
if (res.fetchTranDataAsAttachmentResponse1.attachment != null)
{
string attachFileName = res.fetchTranDataAsAttachmentResponse1.attachment.fileName;
byte[] filebytes = res.fetchTranDataAsAttachmentResponse1.attachment.binaryData.Value;
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\" + res.fetchTranDataAsAttachmentResponse1.attachment.fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
fs.Write(filebytes, 0, filebytes.Length);
fs.Close();
DateTime EndReceive = DateTime.Now;
TimeSpan elapsed = EndReceive.Subtract(BeginReceive);
LogLine = string.Format("Arguments: [{0}]; FileName: {1}; FileSize: {2} bytes; ElapsedTime: {3} seconds", arguments.Trim(), attachFileName, filebytes.Length.ToString(), elapsed.TotalSeconds.ToString());
LogMessageToFile(LogLine);
}
}
catch (CommunicationException ex1)
{
Abort((IChannel)client, channelFactory);
FaultException fe = null;
Exception tmp = ex1;
while (tmp != null)
{
fe = tmp as FaultException;
if (fe != null)
{
break;
}
tmp = tmp.InnerException;
}
if (fe != null)
{
string errmsg = string.Format("The server sent back a fault: {0}", fe.CreateMessageFault().Reason.GetMatchingTranslation().Text);
LogMessageToFile(errmsg);
}
else
{
string errmsg = string.Format("The request failed with exception: {0}", ex1.Message.ToString());
LogMessageToFile(errmsg);
}
}
catch (TimeoutException)
{
Abort((IChannel)client, channelFactory);
string errmsg = string.Format("The request timed out ");
DateTime EndReceive = DateTime.Now;
TimeSpan elapsed = EndReceive.Subtract(BeginReceive);
LogLine = string.Format("Arguments: [{0}]; Exception: {1}; ElapsedTime: {2} seconds", arguments.Trim(), errmsg, elapsed.TotalSeconds.ToString());
LogMessageToFile(LogLine);
}
catch (Exception ex)
{
Abort((IChannel)client, channelFactory);
string errmsg = string.Format("The request failed with unexpected exception: {0}", ex.Message.ToString());
LogMessageToFile(errmsg);
}
finally
{
((IChannel)client).Close();
channelFactory.Close();
}
}
You will not get any usefuls (non-null/non-exception) result by casting channel factory to channel interface since there is no point for factory to implement any of channel interfaces.
You can cast channel to some other channel interface and likely get useful result if you know what type of channel is used like in the code your refer to.
EDIT: I think ((IContextChannel)channel).OperationTimeout = new TimeSpan(0,10,0); should work.
Note: title of your post does not match your code...