I have an ASP.NET MVC application that sends SMS from the web, problem is it doesn't send some special characters such as ~!##$&, when I send something like &&&&, it doesn't send SMS, if I send something like dan&dan it will send the first dan and remove remaining character and word.
Hare is my code:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + mess + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
Hope someone can assist.
Because you use Get method to call SMS web service, illegal characters automatically removed from your SMS. You need to use HttpUtility.UrlEncode to encode characters before sending.
Thanks so much for the light, i manage to find a solution using HttpUtility.UrlEncode:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string message = HttpUtility.UrlEncode(mess, System.Text.Encoding.GetEncoding("ISO-8859-1"));
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + message + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
Related
I've published my app and it is now running from IIS. the problem is that the email function in my controller no longer works when running on IIS (the email function does not send email)
I have an email function on my mvc application and when I run it, it does send an email. The problem starts after I've published my app, Its running on IIS now but the email function does not send the email anymore. How do I go about fixing this?
[HttpPost]
public JsonResult SendMailToUser(string lt, string reason, string name, string fr, string ed)
{
bool result = false;
result = SendMail("ntulisakhile8#gmail.com", "Leave Reaquest", "Hi Sensei,<br />I would like to take a " + lt + " leave<br/><strong>From:</strong> " + fr + " <strong>To:</strong> " + ed + " <br/>Reason: " + reason + "<br/>Regards<br/>" + name + "<br/><a href=~/Response.html>Respond</a>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendMail(string toEmail, string subject, string emailBody)
{
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
a third party service says my service is miss configures
how can I get the plain text of a request on a servlet? I need to show what my service is well configured
any idea?
[Edit] here code:
System.out.println(request.getMethod() + " " + request.getPathInfo() + "" + request.getProtocol());
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println(headerName + ": " + request.getHeader(headerName));
}
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.print(paramName+"="+request.getParameter(paramName));
if(params.hasMoreElements()){
System.out.print("&");
}
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);
To be sure, nothing beats a packet sniffer such as Wireshark. Take the time to install it and learn how to use it - it will save you a lot of time when doing web development.
currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?
As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.
I am trying to create a folder in Alfresco using XMSI below is the code i am using .
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
String host = "127.0.0.1";
int port = 9080;
String username = "admin";
String password = "admin";
String parentFolder = "Company%20Home";
String folderName = "sales3";
String description = "sales space3";
RulesRequest request = new RulesRequest();
//request.setRemediationProfileObj(remediationProfile);
Gson gs = new Gson();
String json = gs.toJson(request);
DefaultHttpClient client = new DefaultHttpClient();
RestClient rstClnt = new RestClient();
String ticket = rstClnt.restClientPost(json, "http://127.0.0.10:9080/alfresco/service/api/login?u=admin&pw=admin", client);
//String url = "http://" + host + ":" + port + "/alfresco/service/api/path/workspace/SpacesStore/" + parentFolder + "/children";
String url = "http://localhost:9080/alfresco/service/cmis/s/workspace:SpacesStore/i/078b05c6-14bd-439c-a1ae-db032c5d98fc/children?alf_ticket="+ticket;
String contentType = "application/atom+xml;type=entry";
String xml =
"<?xml version='1.0' encoding='utf-8'?>\n" +
"<entry xmlns='http://www.w3.org/2005/Atom' xmlns:cmis='http://www.cmis.org/2008/05'>\n" +
"<title>" + folderName + "</title>\n" +
"<summary>" + description + "</summary>\n" +
"<cmis:object>\n"+
"<cmis:properties>\n" +
"<cmis:propertyString cmis:name='cmis:objectTypeId'>\n" +
"<cmis:value>cmis:folder</cmis:value>\n" +
"</cmis:propertyString>\n" +
"</cmis:properties>\n" +
"</cmis:object>\n" +
"</entry>\n";
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", contentType);
StringEntity requestEntity = new StringEntity(xml, "UTF-8");
httppost.setEntity(requestEntity);
System.out.println("executing request" + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content type: " + entity.getContentType());
long contentLength = entity.getContentLength();
System.out.println("Response content length: "
+ entity.getContentLength());
if (contentLength > 0) {
byte [] b = new byte[(int) contentLength];
entity.getContent().read(b);
System.out.println("Response content: " + new String(b));
}
entity.writeTo(System.out);
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
long end = System.currentTimeMillis();
System.out.println("Time spend: " + (end-start) + "ms");
}
Instead of creating a folder it is creating a file of size 0.
Thanks
Garvit
Your property is of the wrong type. You are incorrectly using cmis:propertyString instead of cmis:propertyId Try the following
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">
<cmis:value>cmis:folder</cmis:value>
</cmis:propertyId>
As #Gagravarr says, problems like this are easily avoided if you can use well-known client libraries. If you are constructing the HTTP requests yourself you'd better have a good reason for that.
I am working with the paypal using express checkout to get a billing agreement id.
I was following this guide:
https://www.x.com/developers/paypal/documentation-tools/how-authorize-and-run-reference-transaction-express-checkout
In the first step when i do "SetExpressCheckout":
The following is the code
public string SetExpressCheckout(string Amount)
{
string returnURL = "http://localhost:50325/ReviewOrder.aspx" + "?amount=" + Amount + "&PAYMENTREQUEST_0_CURRENCYCODE=USD";
string cancelURL = returnURL.Replace("ReviewOrder", "ExpCheckOut");
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
string strNVP = strCredentials;
strNVP += "&PAYMENTREQUEST_0_PAYMENTACTION=AUTHORIZATION&&PAYMENTREQUEST_0_AMT=25" + "&L_BILLINGTYPE0=MerchantInitiatedBilling" + "&RETURNURL=" + returnURL;
strNVP += "&CANCELURL=" + cancelURL;
strNVP += "&METHOD=SetExpressCheckout&VERSION=" + strAPIVersion + "&DESC=test EC payment" +"&NOSHIPPING=0" ;
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
//Set WebRequest Properties
wrWebRequest.Method = "POST";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
// and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
The response is:
TOKEN=EC-09082530FY878870B&
TIMESTAMP=2013-03-25T00:45:56Z&
CORRELATIONID=3d33037174d55&
ACK=SuccessWithWarning&
VERSION=86&
BUILD=5479129&
L_ERRORCODE0=11452&
L_SHORTMESSAGE0=Merchant not enabled for reference transactions&
L_LONGMESSAGE0=Merchant not enabled for reference transactions&
L_SEVERITYCODE0=Warning
How to to get a BillingAgreeentd in Step 3:
Code for step 3 is:
public string GetBillingAgreementID()
{
string returnURL = "http://localhost:50325/ReviewOrder.aspx" + "?amount=" + Amount + "¤cy=USD";
string cancelURL = returnURL.Replace("ReviewOrder", "ExpCheckOut");
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
string strNVP = strCredentials;
strNVP += "&RETURNURL=" + returnURL;
strNVP += "&CANCELURL=" + cancelURL;
strNVP += "&METHOD=CreateBillingAgreement&VERSION=" + strAPIVersion + "&TOKEN=" + Session["Token"];
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
//Set WebRequest Properties
wrWebRequest.Method = "POST";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
// and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
Response is:
TIMESTAMP=2013-03-25T00:51:34Z&
CORRELATIONID=854e6beed1e82&
ACK=Failure&
VERSION=86&
BUILD=5479129&
L_ERRORCODE0=11455&
L_SHORTMESSAGE0=Buyer did not accept billing agreement&
L_LONGMESSAGE0=Buyer did not accept billing agreement&
L_SEVERITYCODE0=Error
How to get a BillingAgreemntId?
Is that because of "L_SHORTMESSAGE0=Merchant not enabled for reference transactions" this message from "SetExpressCheckout" am i not able to get BillingAgreementID?
Please help me on this. Thanks.
You would need to contact PayPal and request this to be enabled on the account, if this is for a live account. If you are needing it enabled on the sandbox, you would need to contact PayPal MTS and have this enabled on your sandbox account.