Points disappear in SMS source address - c#

I'm sending an SMS from my web application which is build in ASP.NET C# but for some reason when I add the SourceAddress with parameter.Add("SourceAddress", "BPD.co.uk"); the working BPD.co.uk comes through as BPDcouk.
How can I make the points appear?
Heres my C# code:
public void SendSms(string MobileNumber, string SMSContent)
{
Dictionary<string, string> parameter = new Dictionary<string, string>();
parameter.Add("Action", "Send");
parameter.Add("DestinationAddress", MobileNumber);
parameter.Add("SourceAddress", "BPD.co.uk");
parameter.Add("Body", SMSContent);
parameter.Add("ValidityPeriod", "86400");
string resultcode = api_connect("nsp04456", "pword", parameter);
}
Heres the call to the API_Connect
private string api_connect(string Username, string Password, Dictionary<string, string> ParametersDict)
{
string url = "http://api.sms.co.uk/api/api.php";
string poststring = "Username=" + Username + "&";
poststring = poststring + "Password=" + Password;
// Turn the parameter dictionary object into the variables
foreach (KeyValuePair<string, string> item in ParametersDict)
{
poststring = poststring + "&" + item.Key + "=" + item.Value;
}
MSXML2.ServerXMLHTTP60 xmlHttp = new MSXML2.ServerXMLHTTP60();// Server.CreateObject("MSXML2.ServerXMLHTTP.4.0");
xmlHttp.open("POST", url, false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(poststring);
return xmlHttp.responseText;
}

I guessing that the API you are using is sanitising your parameters and removing stuff it thinks shouldn't be there. You could try escaping the values for your parameters and adding slashes like BPD\.co\.uk and see what happens

Related

how to pass an additional parameter to an OnClick event, asp.net web form?

I have a function called "CreateReportForEachCompany" as following:
protected Dictionary<int, List<ReportObject>> CreateReportForEachCompany()
{
try
{
Dictionary<int, List<ReportObject>> dict = new Dictionary<int, List<ReportObject>>();
EnvironmentVariable.setEnvId((int)environmentEnum.mll);
//bakashot_tarif is a VIEW not a TABLE
DataTable dt = GeneralDbExecuterService.executeSqlSelectDataScript("select * from bakashot_tarif");
foreach (DataRow dr in dt.Rows)
{
var reportRow = FillObjectWithValues(dr);
int company_Id = dr.Field<int>("company_Id");
CreateDictionaryPairIfNotExist(dict, company_Id);
dict[company_Id].Add(reportRow);
}
return dict;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
now lets say I invoked it that way and got myself a dictionary with keys/values as needed.
var dictionary = CreateReportForEachCompany();
now.. I have another function named:
CreateCsvForEachCompany(Dictionary<int, List<ReportObject>> dict)
that TAKES the dictionary as parameter and creates few csvs based on the dictionary keys..
now those two functions above are executed on button click as following:
protected void ExecuteProgram(object sender, EventArgs e)
{
var dictionary = CreateReportForEachCompany();
CreateCsvForEachCompany(dictionary);
}
after that, I have a function named TransferSftpOnClick which meant to transfer file via SFTP (secure file transfer protocol ) into a designated location in the server:
void TransferSftpOnClick(Dictionary<int, List<ReportObject>> dict)
{
EnvironmentVariable.SetSubject(EnvironmentVariable.appSubjectEnum.btl);
string systemId = "MLL";
string fileType = "HIYUV-CHEVRA";
string chargeMonth = DateTime.Now.ToString("yyyyMM");
var fileCreationDate = DateTime.Now.ToString("yyyyMMdd");
string fileCreationTime = DateTime.Now.ToString("HHmmss");
string subject = EnvironmentVariable.appSubjectEnum.btl.ToString().ToUpper();
string location = EnvironmentVariable.getLocalFilePath() + #"\";
foreach (KeyValuePair<int, List<ReportObject>> entry in dict)
{
FtpUtil ftp = new FtpUtil();
int key = entry.Key;
string fileName = systemId + "-" + fileType + "-" + String.Format("{0:00000}", key) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV";
**ftp.saveFileToFtp(location, key.ToString(), fileName, subject);**
}
}
I want my function to recognize the dictionary that is executed in function "ExecuteProgram()"
And I want to trigger onClick on TransferSftpOnClick that will just transfer me the files to the designated location.
how can I achieve that? is it even worth doing?
or should I just do this:
FtpUtil ftp = new FtpUtil();
ftp.saveFileToFtp(location, key.ToString(), fileName, subject);
under the CreateCsvPerCompany to avoid that mess?
hope I was clear, thanks

Incorrect OAuth 1.0a signature generation in C#

After reviewing the OAuth 1.0 documentation for signing requests, I'm struggling getting my signature to match what Postman generates. I've checked things are capitalized / lowercased when necessary, parameters are sorted, encoding is done where appropriate, but I'm missing something.
public string SignRequest(string method, string url, string tokenSecret, Dictionary<string, string> parameters)
{
//, string consumerKey, string token, string timestamp, string nonce, string consumerSecret, string tokenSecret, string identityStatement
string baseString = method.ToUpper() + "&" + Uri.EscapeDataString(url) + "&";
string paramString = "";
var list = parameters.Keys.ToList<string>();
list.Sort();
foreach (string key in list)
{
paramString += key + "=" + Uri.EscapeDataString(parameters[key]) + "&";
}
paramString = paramString.Remove(paramString.Length - 1, 1);
baseString += Uri.EscapeDataString(paramString);
string signingKey = Uri.EscapeDataString(consumerSecret) + "&" + Uri.EscapeDataString(tokenSecret);
var signatureEncoding = new ASCIIEncoding();
var keyBytes = signatureEncoding.GetBytes(signingKey);
var signatureBaseBytes = signatureEncoding.GetBytes(baseString);
var hmacsha1 = new HMACSHA1(keyBytes);
var hashBytes = hmacsha1.ComputeHash(signatureBaseBytes);
var signatureString = Convert.ToBase64String(hashBytes);
return signatureString;
}
I've tried to simplify it down by all the parameters being "1", both secrets "1", the consumer key "1", and a dummy URL for both my implementation and Postman - still getting different signatures. An example of calling it with "1"s and a bogus URL:
postKeys.Add("oauth_consumer_key", "1");
postKeys.Add("oauth_token", "1");
postKeys.Add("oauth_signature_method", "HMAC-SHA1");
postKeys.Add("oauth_timestamp", "1");
postKeys.Add("oauth_nonce", "1");
postKeys.Add("oauth_version", "1");
string signature = SignRequest("GET", "http://hi.com", "1", postKeys);
When I use the same method for the initial retrieval of a token (no token secret yet), my signatures do match a Postman request.
I just can't figure out what I'm missing in here. This seems to match other implementations in other languages, but I can't figure out what I have wrong.

C# Find PHP Variable from URL Code

In C#, I want to find a PHP Variable from a URL Code.
Example: I want to find text out of www.domain.com/file.php?var=text
The main reason for this is that I want to parse the output of
youtube.com/get_video_info?video_id=, or System.IO.Path.GetTempPath() + #"\tempytinfo.txt", which is in the format of:
?var=value&var2=value&var3=value& ...
My efforts of trying to figure this out were sitting at Google, debugging other answers and either not working or just not what i'm looking for, and Here's my efforts so far (also with the help of the first awnser):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Paste A YouTube URL/URI to Download:");
string yturlstr = Console.ReadLine();
Uri yturl = new Uri(yturlstr);
Console.WriteLine("Finding ID in YouTube URL...");
string ytid = yturlstr.Split('?')[1];
ytid = ytid.Replace("v=", "");
Console.WriteLine("Found Watch ID.");
Console.WriteLine("The " + '"' + "Watch ID" + '"' + " is " + ytid);
Console.WriteLine("Getting Video Info...");
Download("http://youtube.com/get_video_info?video_id=" + ytid, System.IO.Path.GetTempPath() + #"\tempytinfo.txt");
Console.WriteLine("Got Info.");
Console.WriteLine("Reading Video Info...");
string viddata = System.IO.File.ReadAllText(System.IO.Path.GetTempPath() + #"\tempytinfo.txt");
Console.WriteLine("Parsing Video Info...");
Dictionary<string, string> videodata = new Dictionary<string, string>();
string vdt = viddata;
string[] vdata = vdt.Split('&');
foreach (char param in vdt)
{
string[] paramParts = char.ToString(param).Split('=');
videodata.Add(paramParts[0], paramParts[1]);
}
string uefsm = WebUtility.UrlDecode(videodata["url_encoded_fmt_stream_map"]);
Dictionary<string, string> videosubdata = new Dictionary<string, string>();
string[] vsdata = uefsm.Split('&');
foreach (char param2 in uefsm)
{
string[] paramParts2 = char.ToString(param2).Split('=');
videosubdata.Add(paramParts2[0], paramParts2[1]);
}
Uri downloadlink = new Uri(WebUtility.UrlDecode(videosubdata["url"]));
Console.WriteLine("Download Link: " + '"' + downloadlink + '"');
Console.ReadKey();
}
private static void Download(string URL, string WhereToDownload)
{
var client = new WebClient();
Uri downloadurl = new Uri(URL);
client.DownloadFile(downloadurl, WhereToDownload);
}
}
}
and my error is:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ConsoleApplication2.exe
Additional information: Index was outside the bounds of the array.
I would parse all the parameters and store them in a collection to access them easily. Suppose you have the URL in yturl like you do on your code, you can create the collection:
Dictionary<string, string> parameters = new Dictionary<string, string>();
string tmpStr = yturl.Split('?')[1];
string[] params = tmpStr.Split('&');
foreach (string param in params)
{
string[] paramParts = param.Split('=');
parameters.Add(paramParts[0], paramParts[1]);
}
And get, following your example, "text", with:
string var = parameters["var"];
// var == "text"
And any other parameter value by it's name:
string var1 = parameters["var1"];
string var2 = parameters["var2"];

Pick out value from Json

I have this code for working with GoogleMapsApi:
public void GoogleGeoCode(string address)
{
address = "Stockholm";
string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
//Code that lets me pick out values from googleresults
}
googleresults contains values (longitude/latitude) but how can i pich those out and use the for something else? I used this approach in a similar situation but it is not valid code in this case:
JObject o = JObject.Parse(googleresult);
string name = (string)o.SelectToken("longitude");
EDIT:
This seems to pick put the longitude and latitude:
public void GoogleGeoCode(string address)
{
address = "Stockholm";
string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
foreach (var result in googleResults.results)
{
double lng = result.geometry.location.lng;
double lat = result.geometry.location.lat;
}
//Do something else...
}
Your googleResults is not a string. It is a dynamic jason object. Try looking at this.
Code from here: Looking for a REST with JSON client library
public static void GoogleGeoCode(string address)
{
string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";
dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
foreach (var result in googleResults.results)
{
Console.WriteLine("[" + result.geometry.location.lat + "," +
result.geometry.location.lng + "] " +
result.formatted_address);
}
}

Problem adding to dictionary in c#

Alright so I've looked hard but I couldn't seem to find answer to my problem. There must be a problem in my code and it would be really helpful if someone could look at it for me.
Dictionary<string, string> keylist = new Dictionary<string, string>();
if (intext.Contains("addkey") && intext.Contains("def"))
{
string[] keywords = intext.Split(' ');
string key1 = keywords[1];
string def2 = keywords[3];
string fkey = key1.Replace("_", " ");
string fdef = def2.Replace("_", " ");
keylist.Add(fkey, fdef);
say("Phrase '" + fkey + "' added with response '" + fdef + "'");
say("Your Dictionary contains " + keylist.Count.ToString() + " word(s).");
//////////////////////////////
}
All I want it to do is take the input in the form of "addkey key_here def definition_here" and add it to the dictionary. I added the counting part for debugging purposes and it always says I only have 1 word in the dictionary no matter how many I have added. You can probably tell I'm new so please be gentle. Thanks
Dictionary<string, string> keylist = new Dictionary<string, string>();
I'm assuming that this function is called whenever the user enters some sort of command (e.g. from the command line, when they click a button, etc.). If this is the case, you need to have your keylist dictionary at a higher level (as an instance variable, for example). The way the code is now, every time the function is called a new dictionary is created and the key is added to it; this is why there's only one.
At the risk of misjudging or oversimplifying your problem, just moving the line I quoted above outside of the function body should help.
In the code as given you are recreating the dictionary every time you run it.
Dictionary<string, string> keylist = new Dictionary<string, string>();
Reinitializes the variable keylist to an empty dictionary.
Instead try moving that line outside of the function. Since you are using winforms, you can create a class level variable, something like this:
public partial class Form1 : Form
{
Dictionary<string, string> keylist = new Dictionary<string, string>();
public Form1()
{
InitializeComponent();
}
public void YourFunction(string intext)
{
if (intext.Contains("addkey") && intext.Contains("def"))
{
string[] keywords = intext.Split(' ');
string key1 = keywords[1];
string def2 = keywords[3];
string fkey = key1.Replace("_", " ");
string fdef = def2.Replace("_", " ");
keylist.Add(fkey, fdef);
say("Phrase '" + fkey + "' added with response '" + fdef + "'");
say("Your Dictionary contains " + keylist.Count.ToString() + " word(s).");
}
}
}
You need to loop through the if (intext.Contains...{} block or it only runs once. If you are looping through it and only getting one entry in the Dictionary, it's because you keep reassigning it within the scope in a scenario such as:
while(true) {
Dictionary<string, string> keylist = new Dictionary<string,string>();
//...
}
So you'll need to move it outside, if that's your case.
I'm not sure exactly what your input string is or how you need to use it, though I think you're looking to split the input string and loop through along this line...
private Dictionary<string, string> GetData(string intext)
{
Dictionary<string, string> keylist = new Dictionary<string, string>();
string[] keywords = intext.Split(' ');
foreach (string s in keywords)
{
if (s.Contains("addkey") && s.Contains("def"))
{
string fkey = key1.Replace("_", " ");
string fdef = def2.Replace("_", " ");
keylist.Add(fkey, fdef);
say("Phrase '" + fkey + "' added with response '" + fdef + "'");
say("Your Dictionary contains " + keylist.Count.ToString() + " word(s).");
}
}
return keylist;
}

Categories