I'm trying to develop a sms sending system using asp.net mvc 4 where I'm using HUAWEI USB 3G modem to send sms. Problem is, when I receive sms, most often the text are coming like this,
AT+CMGF=1 AT+CMGS="+8801671234567" Name: Sample Name Amount1: 1000.....
Here are my codes,
public ActionResult SendSms(int RentId=0)
{
AmountInfo BillTable = db.AmountInfoes.Find(RentId);
var GetName = db.AmountInfoes.Where(a => a.serial.Equals(BillTable.serial)).FirstOrDefault();
string getName = GetName.name;
int getAmount1 = GetName.amount1;
int getAmount2 = GetName.amount2;
int getAmount3 = GetName.amount3;
int getAmount4 = GetName.amount4;
int getAmount5 = GetName.amount5;
int getAmount6 = GetName.amount6;
string getNumber = GetName.phone;
try
{
SP.PortName = "COM8";
SP.Close();
SP.Open();
string ph_no;
string the_no = getNumber;
string txt_msg = "Name: " + getName + " Amount1: " + getAmount1 + " Amount2: " + getAmount2 + " Amount3: " + getAmount3 + " Amount4: " + getAmount4 + " Amount5: " + getAmount5 + " Amount6: " + getAmount6;
ph_no = Char.ConvertFromUtf32(34) + the_no + char.ConvertFromUtf32(34);
SP.Write("AT+CMGF=1" + Char.ConvertFromUtf32(13));
SP.Write("AT+CMGS=" + ph_no + Char.ConvertFromUtf32(13));
SP.Write(txt_msg + Char.ConvertFromUtf32(26) + Char.ConvertFromUtf32(13));
SP.Close();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("RentManager");
}
Is there something wrong in my code? How can I fix this problem where AT commands will not appear in my sms? Need this help badly. Thanks.
Related
First, I apologize for the length of this, but it's all I knew when I started. Now I'm experimenting with the foreach, List<t> and TreeView classes to avoid repetition as recmomended by SO community.
The form will collect information via text boxes, allow attachments of files with file dialogs and collate all info into a neat HTML bodied email. We sell slabs.. and my original code looked a little like this:
private void PrepareReturnEmailTwoSlabs()
{
LoadSettings();
string Fname = Properties.Settings.Default.FabricatorName;
string Facc = Properties.Settings.Default.FabricatorAccountNo;
string Fadd1 = Properties.Settings.Default.FabricatorAddress1;
string Fadd2 = Properties.Settings.Default.FabricatorAddress2;
string Ftown = Properties.Settings.Default.FabricatorTown;
string Fcounty = Properties.Settings.Default.FabricatorCounty;
string Fpostcode = Properties.Settings.Default.FabricatorPostcode;
string Fphoneno = Properties.Settings.Default.FabricatorPhone;
string Femail = Properties.Settings.Default.FabricatorEmail;
string Fclient = Properties.Settings.Default.ClientManagerEmail;
string Fcentre = Properties.Settings.Default.CentreEmail;
string FQt = Properties.Settings.Default.QTEmail;
string Dateofinv = dateTimePicker1.Value.ToShortDateString();
string Inv = textBox13.Text;
string Material1 = textBox14.Text;
string Thick1 = comboBox8.SelectedValue.ToString();
string Batch1 = textBox44.Text;
string Reason1 = comboBox1.SelectedValue.ToString();
string Notes = textBox18.Text;
string Thick2 = comboBox7.SelectedValue.ToString();
string Material2 = textBox15.Text;
string Batch2 = textBox45.Text;
string Reason2 = comboBox2.SelectedValue.ToString();
if (Thick2 == null)
{
Thick2 = "not selected";
}
if (Material2 == null)
{
Material2 = "not selected ";
}
if (Batch2 == null)
{
Batch2 = "not selected ";
}
if (Reason2 == null)
{
Reason2 = "not selected ";
}
GenerateUniqueRefReturn();
//construct email
var message = new MimeMessage();
message.From.Add(new MailboxAddress("************", "***************"));
message.To.Add(new MailboxAddress("**********", "********"));
message.Subject = "Return" + " " + Returnid;
//different message bodies dependant on how many slabs are chosen
TextPart body2 = new TextPart("html")
{
Text = #"Please See Below Information" + "<br/>" +
"<h4>Return ID: " + " " + Returnid + "</h4>" + "<br/>" +
"<b>Fabricator Name:</b>" + " " + Fname + "<br/>" + Environment.NewLine +
"<b>Account Number:</b>" + " " + Facc + "<br/>" + Environment.NewLine +
"<b>Address Line 1:</b>" + " " + Fadd1 + "<br/>" + Environment.NewLine +
"<b>Address Line 2:</b>" + " " + Fadd2 + "<br/>" + Environment.NewLine +
"<b>Town:</b>" + " " + Ftown + "<br/> " + Environment.NewLine +
"<b>County:</b>" + " " + Fcounty + "<br/>" + Environment.NewLine +
"<b>Postcode:</b>" + " " + Fpostcode + "<br/>" + Environment.NewLine +
"<b>Phone:</b>" + " " + Fphoneno + "<br/>" + Environment.NewLine +
"<b>Email:</b>" + " " + Femail + "<br/>" + Environment.NewLine + "<br/>" +
"<br/>" +
"<b>Date Of Invoice: </b>" + " " + DoI + "<br/>" +
"<b>Invoice: </b>" + " " + Inv + "<br/>" +
"<b>Material Information:</b>" + "<br/>" +
//slab 1
"<b>Thickness: </b>" + " " + Thick1 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material1 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch1 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason1 + "<br/>" + "<br/>" +
//slab 2
"<b>Thickness: </b>" + " " + Thick2 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material2 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch2 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason2 + "<br/>" + "<br/>" +
"<br/>" +
"<b>Notes:" + " " + Notes
};
var builder = new BodyBuilder();
//check for return attachment and if found, assign attachment to message via bodybuilder
if (checkBox5.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
message.Body = builder.ToMessageBody();
}
if (checkBox7.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
message.Body = builder.ToMessageBody();
}
if (checkBox6.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
builder.Attachments.Add(ReturnAttachment3);
message.Body = builder.ToMessageBody();
}
else
{
message.Body = body2;
}
//Connection to SMTP and Criteria to Send
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.gmail.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate("***************#********.com", "*********");
client.Send(message);
client.Disconnect(true);
This code was repeated all the way up to five slabs. So now, I have a class:
{
public string Thickness { get; set; }
public string Material { get; set; }
public string Batch { get; set; }
public Slab(string Thick, string Mat, string Batchno)
{
Thickness = Thick;
Material = Mat;
Batch = Batchno;
}
}
A List that holds this object:
private void button1_Click(object sender, EventArgs e)
{
string t = comboBox1.SelectedValue.ToString();
string m = comboBox2.SelectedValue.ToString();
string b = textBox6.Text;
Slab S = new Slab(t, m, b);
allSlabs.Add(S);
PaintTree();
}
public void PaintTree()
{
int ParentIndex;
TreeSlabs.Nodes.Clear();
foreach (Slab slab in allSlabs)
{
TreeSlabs.BeginUpdate();
TreeSlabs.Nodes.Add("Slab" + " " + (allSlabs.IndexOf(slab) + 1).ToString());
ParentIndex = allSlabs.IndexOf(slab);
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Thickness: " + $"{slab.Thickness}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Material: " + $"{slab.Material}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Batch: " + $"{slab.Batch}");
TreeSlabs.EndUpdate();
}
}
Now i want to create a foreach.. that iterates through each node.. and collects the info from the parent and its children foreach node, and somehow instantiate new HTML methods for each node..
Foreach Node:
Compose HTML Line - new HTML
Slab 1:
Thickness:
Material
Batch
Slab 2:... etc
If theres 8 nodes, it generates 8 of those bodies. i can think of ways.. but i KNOW they're defintely not the correct ways to go about it based on what ive read and seen out there.
Many Thanks
You don't need to iterate through the tree and try to reclaim the data you put into it from the List of Slabs; it would be simpler to enumerate the List:
By the way, some other tips:
don't beginupdate/endupdate inside the loop, do it outside
the Add method that adds a node to a tree returns the node it added; you don't have to find it again by index, just capture it var justAdded = rootnode.Add("parent node"); and then add your thickness etc to it justAdded.Nodes.Add("thickness..."). The only add command that doesn't return the added mode is the one that takes a treenode type object; it doesn't need to return it because you already have it
consider adding a method to your slab to return some html, to simplify things
you can tidy all that html up with some string interpolation like you did with your $"{slab.thickness}" etc
I am calling following method inside thread. inside method i have written logs which writes some variable values in notepad file.
Problem : Sometime last log of method do not log anything. ie last line not exucuting sometime. i am not able to understand problem. please guide me if there are issue somewhere.
This is web application hosted in iis server.
Function :
public bool ResetEmployeeAssignedCoursesByRole()
{
bool bReturn = false;
DbTransactionHelper dbTransactionHelper = new DbTransactionHelper();
dbTransactionHelper.BeginTransaction();
try
{
// this line execuete fine
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Started " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
StringBuilder sbQueryEmployeeCourse = new StringBuilder();
sbQueryEmployeeCourse.Append(" set #roleID = " + roleID + "; ");
sbQueryEmployeeCourse.Append(" set #courseID = " + courseID + "; ");
sbQueryEmployeeCourse.Append(" set #inActiveReason = " + inActiveReason + "; ");
sbQueryEmployeeCourse.Append(" set #lastRecordUpdateSource = " + lastRecordUpdateSource + "; ");
sbQueryEmployeeCourse.Append(" call sp_Reset_EmpAssignedCoursesByRole (#roleID, #courseID, #inActiveReason, #lastRecordUpdateSource); ");
DataTable dtEmployeeCourse = dbTransactionHelper.GetDataTable(BusinessUtility.GetString(sbQueryEmployeeCourse), CommandType.Text, null
);
dbTransactionHelper.CommitTransaction();
bReturn = true;
// this line not execuete sometime.
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
}
catch (Exception ex)
{
ErrorLog.createRoleLog("Add Role ID " + BusinessUtility.GetString(roleID));
dbTransactionHelper.RollBackTransaction();
ErrorLog.createRoleLog("Add Course ID " + BusinessUtility.GetString(courseID));
ErrorLog.createRoleLog(ex.ToString());
}
return bReturn;
}
Calls method like below :
Thread t = new Thread(ResetEmployeeAssignedCoursesByRole);
t.Start();
FUNCTION createRoleLog :
public static void createRoleLog(string errorMessage, int empHdrID = 0)
{
try
{
//string path = BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogsDiractory")) + "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string path = BusinessUtility.GetString(ErrorLog.ErrorLogPath) + "RoleLog" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogError")).ToString().ToUpper() == "TRUE")
{
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
//using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
//{
// sw.WriteLine("-------- " + DateTime.Now + " --------");
// sw.WriteLine(errorMessage);
// sw.WriteLine("------------------------");
// sw.Close();
//}
if (!IsFileLocked(new FileInfo(path)))
{
using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (System.IO.StreamWriter sw = new StreamWriter(stream))
{
if (empHdrID != 0)
{
sw.WriteLine("-------- [empHdrID: " + empHdrID + "] " + DateTime.Now + " --------");
}
else
{
sw.WriteLine("-------- " + DateTime.Now + " --------");
}
sw.WriteLine(errorMessage);
sw.WriteLine("------------------------");
sw.Close();
}
}
}
else
{
}
}
}
catch (Exception ex)
{
//throw ex;
}
}
Last line of function which not execution sometime is :
** this line not execuete sometime.**
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
I do simple app like database management and because from server to client. Here is my method below:
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new
{
try
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
List<string> pracownicy = new List<string>();
foreach (var ps in query)
{
Console.WriteLine(ps.Title);
Console.WriteLine(ps.FirstName);
Console.WriteLine(ps.LastName);
Console.WriteLine(ps.Address);
}
}
catch (System.InvalidOperationException)
{
string blad="It's an error";
}
}
return pracownikDane;
}
And it's shows my this data in server Console like this:
And here is my code in a client:
string pdane = Console.ReadLine();
PracownikDane data = proxy.GetPracownik(pdane);
Console.WriteLine(" ");
Console.WriteLine("Zawód:" + " " + data.Tytul);
Console.WriteLine("Imie:" + " " + data.Imie);
Console.WriteLine("Nazwisko:" + " " + data.Nazwisko);
Console.WriteLine("Kraj Pochodzenia:" + " " + data.Kraj);
Console.WriteLine("Miasto:" + " " + data.Miasto);
Console.WriteLine("Adres:" + " " + data.Adres);
Console.WriteLine("Telefon:" + " " + data.Telefon);
Console.WriteLine("Strona WWW:" + " " + data.WWW);
Console.ReadLine();
I would like to know how to put this data in Client.
I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.
I'm new in google analytic. I go through some regarding this. I found that there is no direct method to hit a windows application in google analytic. But i found some solutions in stackoverflow. I tried that, but didn't work for me. Below is the code that I'm using.
private void analyticsmethod4(string trackingId, string pagename)
{
Random rnd = new Random();
long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;
// Get the first run time
timestampFirstRun = DateTime.Now.Ticks;
timestampLastRun = DateTime.Now.Ticks - 5;
timestampCurrentRun = 45;
numberOfRuns = 2;
// Some values we need
string domainHash = "123456789"; // This can be calcualted for your domain online
int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
string source = "Shop";
string medium = "medium123";
string sessionNumber = "1";
string campaignNumber = "1";
string culture = Thread.CurrentThread.CurrentCulture.Name;
string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;
string statsRequest = "http://www.google-analytics.com/__utm.gif" +
"?utmwv=4.6.5" +
"&utmn=" + rnd.Next(100000000, 999999999) +
// "&utmhn=hostname.mydomain.com" +
"&utmcs=-" +
"&utmsr=" + screenRes +
"&utmsc=-" +
"&utmul=" + culture +
"&utmje=-" +
"&utmfl=-" +
"&utmdt=" + pagename + // Here i passed my profile name "MyWindowsApp"
"&utmhid=1943799692" +
"&utmr=0" +
"&utmp=" + pagename +
"&utmac=" + trackingId + //Tracking id : ie "UA-XXXXXXXX-X"
"&utmcc=" +
"__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
"%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";
try
{
using (var client = new WebClient())
{
//byte[] bt = client.DownloadData(statsRequest);
Stream data = client.OpenRead(statsRequest);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
MessageBox.Show(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This example is also got from this site itself. I don't know where was the problem. Please direct me, how can i make it. This is the output i'm getting "GIF89a".
Thanks
Bobbin Paulose
So it's working. The Google Analytics call loads a tiny GIF image, and the querystring parameters provided in the request trigger all the Google Analytics goodness. If you're getting a response back, you have registered your event successfully with Google.