I want to send SMS using way2sms. I have tried following code
login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnconnect_Click(object sender, EventArgs e)
{
Session["id"] = txtmobileno.Text;
Session["pw"] = txtpw.Text;
Response.Redirect("/send.aspx");
}
}
}
send.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace WebApplication1
{
public partial class send : System.Web.UI.Page
{
string mbno, mseg, ckuser, ckpass;
private HttpWebRequest req;
private CookieContainer cookieCntr;
private string strNewValue;
public static string responseee;
private HttpWebResponse response;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null && Session["pw"] == null)
{
Server.Transfer("login.aspx");
}
connect();
try
{
lblError.Text = "";
lblError.Visible = false;
if (!(IsPostBack))
{
btnSend.Attributes.Add("onclick", "return Validate('" + txtTo.ClientID + "','" + txtMessage.ClientID + "');");
txtMessage.Attributes.Add("onchange", "TextChange('" + txtMessage.ClientID + "','" + lblLeft.ClientID + "');");
txtMessage.Attributes.Add("onkeyup", "TextChange('" + txtMessage.ClientID + "','" + lblLeft.ClientID + "');");
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
mbno = txtTo.Text;
mseg = txtMessage.Text;
sendSms(mbno, mseg);
txtTo.Text = "";
txtMessage.Text = "";
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
public void connect()
{
ckuser = Session["id"].ToString();
ckpass = Session["pw"].ToString();
try
{
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com/auth.cl");
this.req.CookieContainer = new CookieContainer();
this.req.AllowAutoRedirect = false;
this.req.Method = "POST";
this.req.ContentType = "application/x-www-form-urlencoded";
this.strNewValue = "username=" + ckuser + "&password=" + ckpass;
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
this.cookieCntr = this.req.CookieContainer;
this.response.Close();
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com//jsp/InstantSMS.jsp?val=0");
this.req.CookieContainer = this.cookieCntr;
this.req.Method = "GET";
this.response = (HttpWebResponse)this.req.GetResponse();
responseee = new StreamReader(this.response.GetResponseStream()).ReadToEnd();
int index = Regex.Match(responseee, "custf").Index;
responseee = responseee.Substring(index, 0x12);
responseee = responseee.Replace("\"", "").Replace(">", "").Trim();
this.response.Close();
pnlsend.Visible = true;
lblErrormsg.Text = "connected";
}
catch (Exception ex)
{
lblErrormsg.Text = "Error connecting to the server...";
Session["error"] = "Error connecting to the server...";
lblError.Text = ex.ToString();
lblError.Text= ex.ToString();
//Server.Transfer("login.aspx");
}
}
public void sendSms(string mbno, string mseg)
{
if ((mbno != "") && (mseg != ""))
{
try
{
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com//FirstServletsms?custid=");
this.req.AllowAutoRedirect = false;
this.req.CookieContainer = this.cookieCntr;
this.req.Method = "POST";
this.req.ContentType = "application/x-www-form-urlencoded";
this.strNewValue = "custid=undefined&HiddenAction=instantsms&Action=" + responseee + "&login=&pass=&MobNo=" + this.mbno + "&textArea=" + this.mseg;
string msg = this.mseg;
string mbeno = this.mbno;
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
this.response.Close();
lblErrormsg.Text = "Message Sent..... " + mbeno + ": " + msg;
}
catch (Exception)
{
lblErrormsg.Text = "Error Sending msg....check your connection...";
}
}
else
{
lblErrormsg.Text = "Mob no or msg missing";
}
}
protected void btnLogOut_Click(object sender, EventArgs e)
{
Session["id"] = null;
Session["pw"] = null;
Session["error"] = null;
Server.Transfer("login.aspx");
}
}
}
But it doesn't work. Is there any changes in this code that I have to do?
Please tell me any other way to send sms from desktop application or web application
I dont know way2sms but the easiest SMS API I have found is http://cp.bulksmsportal.co.za/sms_default.aspx
Code is really simple as well
public static void sendSMS(string Recepient, string Message)
{
//Recepient is the cellno in string format
StringBuilder sb = new StringBuilder();
sb.Append("http://www.mymobileapi.com/api5/http5.aspx?");
sb.Append("Type=sendparam");
sb.Append("&username={yourusername}");//add your username here
sb.Append("&password={yourpassword}");//add your password here
sb.AppendFormat("&numto={0}", Recepient);
string message = HttpUtility.UrlEncode(Message, ASCIIEncoding.ASCII);
sb.AppendFormat("&data1={0}", message);
try
{
////Create the request and send data to the SMS Gateway Server by HTTP connection
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(sb.ToString());
//Get response from the SMS Gateway Server and read the answer
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
}
catch (Exception ex)
{
}
}
I used this : GSM Communication Library (GSMComm)
Related
Ok, so i want to make a loader, that injects a dll into a process based on hwid checked from a MySQL database, by modifing a sourcecode on the internet, however even though i type correct login creditentials it gives me an error that the username or password is invalid even though they are both correct
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ManualMapInjection.Injection;
using System.Net;
using System.IO;
using System.Diagnostics;
using MySql.Data.MySqlClient;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private MySqlConnection conn;
string HWID;
public Form1()
{
HWID = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
string connString;
connString = $"SERVER=sql7.freemysqlhosting.net;PORT=3306;DATABASE=sql2345678;UID=loader;PASSWORD=password1234";
conn = new MySqlConnection(connString);
InitializeComponent();
}
public bool IsLogin()
{
string trruu = "TRUE";
string query = $"SELECT * FROM loader WHERE hwid='{HWID}' AND active_subscription='{trruu}';";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Logged In");
reader.Close();
conn.Close();
return true;
}
else
{
MessageBox.Show("Error Logging In");
reader.Close();
conn.Close();
return false;
}
}
else
{
MessageBox.Show("Error Logging In");
conn.Close();
return false;
}
}
catch (Exception ex)
{
MessageBox.Show("Error");
conn.Close();
return false;
}
}
private bool OpenConnection()
{
try
{
conn.Open();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show("Server username or password is incorrect! " + ex.Number);
return false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
HWID = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
textBox1.Text = HWID;
textBox1.ReadOnly = true;
checkonline();
}
private void button1_Click(object sender, EventArgs e)
{
checkonline();
WebClient wb = new WebClient();
if (IsLogin())
{
string mainpath = "C:\\Windows\\random.dll";
wb.DownloadFile("MY DIRECT DOWNLOADLINK URL", mainpath);
var name = "process";
var target = Process.GetProcessesByName(name).FirstOrDefault();
var path = mainpath;
var file = File.ReadAllBytes(path);
//Checking if the DLL isn't found
if (!File.Exists(path))
{
MessageBox.Show("Error: DLL not found");
return;
}
//Injection
var injector = new ManualMapInjector(target) { AsyncInjection = true };
label2.Text = $"hmodule = 0x{injector.Inject(file).ToInt64():x8}";
if (System.IO.File.Exists(mainpath))
{
System.IO.File.Delete(mainpath);
}
}
else
{
MessageBox.Show("HWID Incorrect");
}
}
I'm sending the contents of a few textboxes to my website using the HttpClient. My PHP script inserts the data in a database.
But after clicking the btnSubmit-button, it runs the code but nothing is added to my database and no exceptions are thrown. What's wrong with my code?
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Net.Http;
namespace PhoneApp2
{
public partial class Submit2 : PhoneApplicationPage
{
public Submit2()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("barcode", out parameter))
{
Barcode.Text = parameter;
}
}
public static int typeConnection()
{
switch (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType)
{
default:
return 0;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
return 2;
}
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
try
{
if (typeConnection() < 2)
{
string URI = "http://cocktailpws.net23.net/requests/add_contribution.php";
string myParameters = "barcode=" + Barcode.Text + "&booze=" + Name.Text + "&email=" + Email.Text;
sendData(URI, myParameters);
}
else
{
MessageBox.Show("No database connection could be established. Please check your internet connection and try again.");
}
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
public async void sendData(string URI, string myParameters)
{
using (HttpClient hc = new HttpClient())
{
var response = await hc.PostAsync(URI, new StringContent(myParameters));
}
}
}
}
PHP:
if(isset($_POST['barcode']) && isset($_POST['booze']) && isset($_POST['email'])){
include_once "../inc/inc_db.php";
$booze = sqlesc($_POST['booze']);
$barcode = sqlesc($_POST['barcode']);
$email = sqlesc($_POST['email']);
date_default_timezone_set('Europe/Amsterdam');
$date = date("Y-m-d H:i:s");
$query = "INSERT INTO contr_barcode(booze,barcode,email,datum) VALUES ('$booze','$barcode','$email',$date')";
if(mysqli_query($con,$query)){
echo "1";
}else{
echo "0";
}
}
You are sending the values formatted as if you are sending application/x-www-form-urlencoded however, by default StringContent will declare the content-type as text/plain. It is possible that the PHP framework is not parsing the content correctly because it thinks you are just sending unformatted plain text.
You could either change the content-type of the StringContent object, or you could use the UrlEncodedFormContent class. e.g.
var content = new StringContent(myParameters);
content.Headers.Content-Type = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await hc.PostAsync(URI, content);
I am new to AT commands. I am using Nokia E71 to send and receive SMS. I am designing an application for sending SMS, but my code is not working.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace AT_commands
{
public partial class Form1 : Form
{
SerialPort serialPort;
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
this.serialPort = new SerialPort();
this.serialPort.PortName = "COM23";
this.serialPort.BaudRate = 9600;
this.serialPort.Parity = Parity.None;
this.serialPort.DataBits = 8;
this.serialPort.StopBits = StopBits.One;
this.serialPort.Handshake = Handshake.RequestToSend;
this.serialPort.DtrEnable = true;
this.serialPort.RtsEnable = true;
this.serialPort.NewLine = System.Environment.NewLine;
send_sms();
}
public bool send_sms()
{
label1.Text = "Loaded Successfuly";
String SMSMessage = "Message to send";
String CellNumber = "+923333333333";
String messageToSend = null;
if (SMSMessage.Length <= 160)
{
messageToSend = SMSMessage;
}
else
{
messageToSend = SMSMessage.Substring(0, 160);
}
if (this.IsOpen == true)
{
this.serialPort.WriteLine(#"AT" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(#"AT+CMGS=""" + CellNumber + #"""" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(SMSMessage + (char)(26));
return true;
}
return false;
}
public void Open()
{
if (this.IsOpen == false)
{
this.serialPort.Open();
}
}
public void Close()
{
if (this.IsOpen == true)
{
this.serialPort.Close();
}
}
public bool IsOpen
{
get
{
return this.serialPort.IsOpen;
}
}
public void Dispose()
{
if (this.IsOpen)
this.Close();
}
}
}
Please help me with this code!
Here's my code
using System;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
namespace CSharp_SMS
{
public partial class Form_SMS_Sender : Form
{
private SerialPort _serialPort;
public Form_SMS_Sender()
{
InitializeComponent();
}
private void buttonSend_Click(object sender, EventArgs e)
{
string number = textBoxNumber.Text;
string message = textBoxMessage.Text;
//Replace "COM7"withcorresponding port name
_serialPort = new SerialPort("COM7", 115200);
Thread.Sleep(1000);
_serialPort.Open();
Thread.Sleep(1000);
_serialPort.Write("AT+CMGF=1\r");
Thread.Sleep(1000);
_serialPort.Write("AT+CMGS=\"" + number + "\"\r\n");
Thread.Sleep(1000);
_serialPort.Write(message + "\x1A");
Thread.Sleep(1000);
labelStatus.Text = "Status: Message sent";
_serialPort.Close();
}
}
}
Here's a link http://circuitfreak.blogspot.com/2013/03/c-programming-sending-sms-using-at.html
Why dont you open the port connection in the form_load() itself, later you can close it at the end as you did.
And do these too in Form_Load():
string cmd = "AT";
port.WriteLine(cmd + "\r");
port.Write(cmd + "\r");
port.WriteLine("AT+CMGF=1");
And simplifying the sms sending code:
port.WriteLine("AT+CMGS=\"" + PhNumber + "\"");
port.Write(Message + char.ConvertFromUtf32(26));
Try it this way.. You are not opening the connection to the serial port. I have tried it and it is working fine for me.
private void button1_Click(object sender, EventArgs e)
{
this.serialPort = new SerialPort();
this.serialPort.PortName = "COM5";
this.serialPort.BaudRate = 9600;
this.serialPort.Parity = Parity.None;
this.serialPort.DataBits = 8;
this.serialPort.StopBits = StopBits.One;
this.serialPort.Handshake = Handshake.RequestToSend;
this.serialPort.DtrEnable = true;
this.serialPort.RtsEnable = true;
this.serialPort.NewLine = System.Environment.NewLine;
serialPort.Open();
send_sms();
}
public bool send_sms()
{
String SMSMessage = "gsm MESSAGE FROM .NET C#";
String CellNumber = "+9233333333333";
String messageToSend = null;
if (SMSMessage.Length <= 160)
{
messageToSend = SMSMessage;
}
else
{
messageToSend = SMSMessage.Substring(0, 160);
}
if (serialPort.IsOpen)
{
this.serialPort.WriteLine(#"AT" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(#"AT+CMGS=""" + CellNumber + #"""" + (char)(13));
Thread.Sleep(200);
this.serialPort.WriteLine(SMSMessage + (char)(26));
return true;
}
return false;
}
I am unable to upload large files to Sharepoint 2010. I am using Visual Studio 2010 and Language C#. I have tried multiple ways from content I have found online but nothing has worked. I have changed the settings and config files to the maximum allowed upload limits and still nothing. I am using the copy.asmx for small files which works fine and am trying UploadDataAsync when the file is too large and an exception is thrown but this is not working. Please take a look at the code below...
Any/all assistance is greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace ListsService
{
public class UploadDocumentcs
{
public string UploadResult { get; set; }
public string Errors { get; set; }
public UploadDataCompletedEventHandler WebClient_UploadDataCompleted { get; set; }
public byte[] content { get; set; }
public void UploadDocumentToSP(string localFile, string remoteFile)
{
string result = string.Empty;
SPCopyService.CopySoapClient client = new SPCopyService.CopySoapClient();
string sUser = "user";
string sPwd = "pwd";
string sDomain = "dmn";
System.Net.NetworkCredential NC = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential = NC;
try
{
client.Open();
string url = "http://SP/TestLibrary/";
string fileName = localFile.Substring(localFile.LastIndexOf('\\'), (localFile.Length - localFile.LastIndexOf('\\')));
fileName = fileName.Remove(0, 1);
string[] destinationUrl = { url + fileName };
System.IO.FileStream fileStream = new System.IO.FileStream(localFile, System.IO.FileMode.Open);
byte[] content = new byte[(int)fileStream.Length];
fileStream.Read(content, 0, (int)fileStream.Length);
fileStream.Close();
// Description Information Field
SPCopyService.FieldInformation descInfo = new SPCopyService.FieldInformation
{
DisplayName = "Description",
Type = SPCopyService.FieldType.File,
Value = "Test file for upload"
};
SPCopyService.FieldInformation[] fileInfoArray = { descInfo };
SPCopyService.CopyResult[] arrayOfResults;
uint result2 = client.CopyIntoItems(fileName, destinationUrl, fileInfoArray, content, out arrayOfResults);
// Check for Errors
foreach (SPCopyService.CopyResult copyResult in arrayOfResults)
{
string msg = "====================================" +
"SharePoint Error:" +
"\nUrl: " + copyResult.DestinationUrl +
"\nError Code: " + copyResult.ErrorCode +
"\nMessage: " + copyResult.ErrorMessage +
"====================================";
Errors = string.Format("{0};{1}", Errors, msg);
}
UploadResult = "File uploaded successfully";
}
catch (OutOfMemoryException)
{
System.Uri uri = new Uri("http://bis-dev-srv2:300/DNATestLibrary/");
(new System.Net.WebClient()).UploadDataCompleted += new UploadDataCompletedEventHandler(WebClient_UploadDataCompleted);
(new System.Net.WebClient()).UploadDataAsync(uri, content);
}
finally
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
{
client.Abort();
UploadResult = "Upload aborted due to error";
}
if (client.State != System.ServiceModel.CommunicationState.Closed)
{
client.Close();
}
}
}
void WcUpload_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
if (e != null)
{
UploadResult = "Upload Unuccessful";
}
else
{
UploadResult = "Upload Successful";
//throw new NotImplementedException();
}
}
}
}
Shaun
In order to get this to work, you will have to make changes to the SharePoint configuration to increase the upload limit and the time out. The link below shows the necessary steps to get large file uploads to work.
http://blogs.technet.com/b/sharepointcomic/archive/2010/02/14/sharepoint-large-file-upload-configuration.aspx
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
namespace UploadTester
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnSelectFile_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
byte[] content = GetByteArray();
string filename = Path.GetFileName(openFileDialog1.FileName);
System.Net.WebClient webClient = new System.Net.WebClient();
System.Uri uri = new Uri("http://SP/DNATestLibrary/" + filename);
webClient.Credentials = new NetworkCredential("username", "pwd", "domain");
webClient.UploadData(uri, "PUT", content);
MessageBox.Show("Upload Successful");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
byte[] GetByteArray()
{
FileStream fileStream = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
byte[] content = new byte[(int)fileStream.Length];
fileStream.Read(content, 0, (int)fileStream.Length);
fileStream.Close();
return content;
}
private void btnUploadAsync_Click(object sender, EventArgs e)
{
try
{
byte[] content = GetByteArray();
string filename = Path.GetFileName(openFileDialog1.FileName);
System.Net.WebClient webClient = new System.Net.WebClient();
System.Uri uri = new Uri("http://SP/DNATestLibrary/" + filename);
webClient.UploadDataCompleted += new UploadDataCompletedEventHandler(webClient_UploadDataCompleted);
webClient.Credentials = new NetworkCredential("username", "pwd", "domain");
webClient.UploadDataAsync(uri, "PUT", content);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
void webClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("Upload Successful");
}
else
{
MessageBox.Show(e.ToString());
}
}
}
}
I have a c# app (Windows Service) that fires a timer event that reads files in a directory and sends out SMS using the data in the files. Next time the event fires, it tries to move the processed files in the "Processed" directory to a "Completed" directory before processing the new files. I keep getting a "File in use by another process" exception, although I am pretty sure that I dispose of everything that uses the files. If I stop the service and start it again, the files is released. Any ideas?
//Code that fires the timer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace SmsWindowsService
{
public partial class SmsWindowsService : ServiceBase
{
private static System.Timers.Timer aTimer;
public SmsWindowsService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MatterCentreSMSSource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MatterCentreSMSSource", "MatterCentreSMSLog");
}
elMatterCentreSMS.Source = "MatterCentreSMSSource";
elMatterCentreSMS.Log = "MatterCentreSMSLog";
}
protected override void OnStart(string[] args)
{
string logText = string.Empty;
logText = "MatterCentreSMS Service started successfully on " + DateTime.Now;
WriteEventLog(logText);
//Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
//Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
//Set the Interval to 5 minutes.
//aTimer.Interval = 300000;
aTimer.Interval = 60000;
aTimer.Enabled = true;
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
GC.Collect();
}
protected override void OnStop()
{
string logText = string.Empty;
logText = "MatterCentreSMS Service stopped on " + DateTime.Now;
WriteEventLog(logText);
}
private void WriteEventLog(string logText)
{
elMatterCentreSMS.WriteEntry(logText);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
string ex = string.Empty;
SendSms s = new SendSms();
ex = s.ProcessSms();
if (ex.Length > 1)
WriteEventLog(ex);
//ex = RestartService("SmsWindowsService", 60000);
//WriteEventLog(ex);
}
public string RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
return "MatterCentreSMS Service successfully restarted on " + DateTime.Now;
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
}
}
//Code that reads the file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
namespace SmsWindowsService
{
class Message
{
private string filePath;
public Message(string filePath)
{
this.filePath = filePath;
}
public string readSMS(string filePath)
{
const string searchmessage = "[B-->]";
StreamReader smsmessage = new StreamReader(filePath);
try
{
FileInfo filenameinfo = new FileInfo(filePath);
if (filenameinfo.Exists == false)
throw new SMSReaderException(String.Format("SMS Message {0} cannot be found ...", filePath), filePath);
smsmessage = filenameinfo.OpenText();
string smsoutput = smsmessage.ReadToEnd();
int endpos = smsoutput.IndexOf(searchmessage);
smsoutput = smsoutput.Substring(endpos + searchmessage.Length);
smsoutput = smsoutput.Replace("&", "&");
smsoutput = smsoutput.Replace("\"", """);
smsoutput = smsoutput.Replace("'", "'");
filenameinfo = null;
smsmessage.Close();
smsmessage.Dispose();
return smsoutput;
}
catch(Exception e)
{
throw new Exception("Help", e.InnerException);
}
finally
{
smsmessage.Close();
smsmessage.Dispose();
}
}
}
public class SMSReaderException : System.IO.FileNotFoundException
{
public SMSReaderException(string message, string filename)
: base(message, filename)
{
}
}
}
//Code that connects to web service and send sms
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Net;
using System.Configuration;
using SmsWindowsService.EsendexSendSmsService;
namespace SmsWindowsService
{
class SendSms
{
string filePath = string.Empty;
string directoryPath = string.Empty;
string directoryPathProcessing = string.Empty;
string directoryPathCompleted = string.Empty;
string smsLogfileDirectory = string.Empty;
string smsLogfilePath = string.Empty;
string mattercentreSMS = string.Empty;
string messageBody = string.Empty;
string messageId = string.Empty;
string messageStatus = string.Empty;
string dateTodayString = string.Empty;
long mobileNumber;
EsendexSendSmsService.SendService send;
public SendSms()
{
directoryPath = ConfigurationSettings.AppSettings[#"directoryPath"];
directoryPathProcessing = ConfigurationSettings.AppSettings[#"directoryPathProcessing"];
directoryPathCompleted = ConfigurationSettings.AppSettings[#"directoryPathCompleted"];
smsLogfileDirectory = ConfigurationSettings.AppSettings[#"smsLogfileDirectory"];
dateTodayString = DateTime.Now.ToString("yyyy/MM/dd");
smsLogfilePath = smsLogfileDirectory + dateTodayString.Replace(#"/", "_") + ".txt";
send = new EsendexSendSmsService.SendService();
}
public string ProcessSms()
{
string ex = string.Empty;
try
{
DirectoryInfo di = new DirectoryInfo(directoryPathProcessing);
ex = MoveFilesToCompleted(directoryPathProcessing, directoryPathCompleted);
if (ex.Length > 1)
return ex;
ex = MoveFilesToProcessing(directoryPath, directoryPathProcessing);
if (ex.Length > 1)
return ex;
FileInfo[] subFilesProcessing = di.GetFiles();
foreach (FileInfo subFile in subFilesProcessing)
{
filePath = directoryPathProcessing + subFile.Name;
Message sms = new Message(filePath);
mattercentreSMS = sms.readSMS(filePath);
MessageDetails d = new MessageDetails(mattercentreSMS);
mobileNumber = d.GetMobileNumber();
messageBody = d.GetMessageBody();
ex = SetHeader();
if (ex.Length > 1)
return ex;
ex = SetProxy();
if (ex.Length > 1)
return ex;
//Send the message and get the returned messageID and send status
messageId = send.SendMessage(Convert.ToString(mobileNumber), messageBody, EsendexSendSmsService.MessageType.Text);
messageStatus = Convert.ToString(send.GetMessageStatus(messageId));
ex = WriteLogFile(messageId, subFile.Name, messageStatus);
if (ex.Length > 1)
return ex;
send.Dispose();
}
di = null;
subFilesProcessing = null;
return ex;
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
private string MoveFilesToCompleted(string directoryPathProcessing, string directoryPathCompleted)
{
DirectoryInfo din = new DirectoryInfo(directoryPathProcessing);
try
{
FileInfo[] subFiles = din.GetFiles();
foreach (FileInfo subFile in subFiles)
{
subFile.MoveTo(directoryPathCompleted + subFile.Name);
}
subFiles = null;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
finally
{
din = null;
}
}
private string MoveFilesToProcessing(string directoryPath, string directoryPathProcessing)
{
DirectoryInfo din = new DirectoryInfo(directoryPath);
try
{
FileInfo[] subFiles = din.GetFiles();
foreach (FileInfo subFile in subFiles)
{
subFile.MoveTo(directoryPathProcessing + subFile.Name);
}
subFiles = null;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
finally
{
din = null;
}
}
private string SetHeader()
{
try
{
//Setup account details in the header
EsendexSendSmsService.MessengerHeader header = new EsendexSendSmsService.MessengerHeader();
header.Account = ConfigurationSettings.AppSettings[#"smsServiceUrl"];
header.Username = ConfigurationSettings.AppSettings[#"smsServiceUsername"];
header.Password = ConfigurationSettings.AppSettings[#"smsServicePassword"];
// set the SOAP header Authentication values
send.MessengerHeaderValue = header;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
private string SetProxy()
{
try
{
//Create a web proxy object as the proxy server block direct request to esendex
WebProxy myProxy = new WebProxy(ConfigurationSettings.AppSettings[#"proxyaddress"], true);
myProxy.Credentials = new NetworkCredential(ConfigurationSettings.AppSettings[#"username"], ConfigurationSettings.AppSettings[#"password"]);
WebRequest.DefaultWebProxy = myProxy;
send.Proxy = myProxy;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
private string WriteLogFile(string messageId, string smsFileName, string messageStatus)
{
try
{
if (File.Exists(smsLogfilePath))
{
//file is not empty - append log entry to file
using (StreamWriter writeSmsLog = File.AppendText(smsLogfilePath))
{
writeSmsLog.WriteLine(messageId + " " + smsFileName + " " + DateTime.Now + " " + messageStatus);
writeSmsLog.Close();
}
}
else
{
FileStream fs = File.OpenWrite(smsLogfilePath);
fs.Flush();
fs.Close();
fs.Dispose();
using (StreamWriter writeSmsLog = new StreamWriter(smsLogfilePath, true))
{
writeSmsLog.WriteLine("Message_ID File_Name Date_Sent Status");
writeSmsLog.WriteLine("======================================================================================================================================");
writeSmsLog.WriteLine(messageId + " " + smsFileName + " " + DateTime.Now + " " + messageStatus);
writeSmsLog.Close();
}
}
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
}
}
Any ideas?
You're running a virus checker in an entirely different process. It is detecting that the file has changed and is locking it momentarily in order to check it to see if the edit you just performed to the file introduced a virus. It'll unlock it in a couple of milliseconds.
Disabling your virus checker is a bad idea. Instead, you're just going to have to live with it; write your code to be robust in a world where there are lots of processes vying for locks on files.
StreamReader smsmessage = new StreamReader(filePath);
try
{
FileInfo filenameinfo = new FileInfo(filePath);
....
smsmessage = filenameinfo.OpenText();
...
You are initializing smsmessage twice, but only disposing one of those instances. The first line constructs a StreamReader, and then you overwrite your reference to that instance with the instance created by filenameinfo.OpenText(). That leaves you with an instance that no longer has any references and hasn't been disposed. That instance might be holding a lock on the file and you have no guarantees on when it will be disposed. Even if it isn't holding a lock, you should still fix this.