wpf webbrowser uri containing other language such as Korean - c#

i have a trouble when i use MyWebBrowser.Source = new Uri(uri);
i want to add Korean to uri. but when i do it, i can see broken characters which was from Korean. i searched for solution, but i couldn't understand the way. someone instructs the way using encode/decode.. but, i don't know how to apply it to my code.
please help me
.
<Grid Background="White"><WebBrowser Name="MyWebBrowser" /></Grid>
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
change_room();
}
private void change_room()
{
string room_name = "example";
string nick = "한글";// 한글 means Korean.
string uri = "http://" + room_name + ".com/chat?nick=" + nick ;
try
{
MyWebBrowser.Source = new Uri(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
string uri = "http://" + room_name + ".server.ohcs.uu.gl/chat?nick=" + HttpUtility.UrlEncode(nick,System.Text.Encoding.GetEncoding("euc-kr")`) + "&text=&sessid=" + room_name;
above code can't make Korean correct.

You should use the HttpUtility.UrlEncode method on strings that are from user input and strings that contain characters that'd break the URL/not get through correctly (ampersand, foreign chars, etc). This way, it'll be safe for use in a URL.
string uri = "http://" + HttpUtility.UrlEncode(room_name) + ".com/chat?nick=" + HttpUtility.UrlEncode(nick, System.Text.Encoding.GetEncoding("euc-kr"));
The HttpUtility class can be found in the assembly System.Web.dll. If there's an error relating to the namespace not being found, make sure to add the reference to System.Web.dll using the Add References dialog.

i add more explanations about solution i found.
this is xaml code <.WebBrowser x:Name="webBrowser" /.>
below is cs code
public room1()
{
string nick = "한글";
webBrowser.Navigate("http:/freechat.esy.es/minichat?chat=room1&nick=" + nick );
}
above codes are inappropriate because "한글" is not a regular letter i think.
UriBuilder builder = new UriBuilder("http://freechat.esy.es/minichat?chat=room1&nick=한글");
string url = builder.ToString();
WebBrowser web = new WebBrowser();
web.Navigate(url);
UriBuilder convert unregualr letters containing "한글"[string url] to regualr letters which can be accepted to web.
input letters : [http://freechat.esy.es/minichat?chat=room1&nick=한글]
translated letters by UriBuilder :
[http:/freechat.esy.es/minichat?chat=room1&nick=%ED%95%9C%EA%B8%80]
I found the answer. I'm currently using the following code and it now works fine.
string make_uri(string uri)
{
UriBuilder ub = new UriBuilder(uri);
string ubS = ub.ToString();
return ubS;
}
string send_uri { get; set; }
private void NavigateTo()
{
int cs = combo1.SelectedIndex;
if (DN == "Your Nick")
{
if (cs == 0) send_uri = ("http://freechat.esy.es/minichat?chat=room1" + mode + key);
else if (cs == 1) send_uri = ("http://freechat.esy.es/minichat?chat=chataa" + mode + key);
else if (cs == 2) send_uri = ("http://freechat.esy.es/minichat?chat=room2" + mode + key);
}
else
{
if (cs == 0) send_uri = (make_uri("http://freechat.esy.es/minichat?chat=room1&nick=" + DN + mode + key));
else if (cs == 1) send_uri = (make_uri("http://freechat.esy.es/minichat?chat=chataa&nick=" + DN + mode + key));
else if (cs == 2) send_uri = (make_uri("http://freechat.esy.es/minichat?chat=room2&nick=" + DN + mode + key));
}
webBrowser.Navigate(send_uri);
}

Related

C# HttpWebRequest removing any encoding on an URL

I'm trying to send percent-encoded ASCII characters using HttpWebRequest, for example https://example.com/%74%65%73%74
Using POSTMAN I'm able to send a request and see in charles that it's still encoded, however, regardless of what I do, any C# library will simplify this to https://example.com/test.
Is there any workaround or async compatible library to work around this?
Thanks in advance
Example Code
string newURL = "";
string path = "test";
foreach (char character in path)
{
string charac = "";
string finished = "";
if (character != '-' || character != '/')
{
if (random.Next(1, 10) >= 5)
{
charac = "%" + Convert.ToInt32(character).ToString("X");
}
else
{
charac = character.ToString();
}
}
newURL = newURL + charac;
}
string main = "http://www.example.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(main + "/en/" + newURL);

Get Set for a phone number

In my database, I store phone numbers like this "7279884545". One solid string with no spaces.
In my class that stores the phone number info, I have a function that will add the correct punctuation.
public static String beautifyPhoneNumber(String number, String extension)
{
String beautifulNumber = "";
if (!String.IsNullOrEmpty(number))
{
beautifulNumber = "(" + number.Substring(0, 3) + ") " +
number.Substring(3, 3) + "-" +
number.Substring(6, 4);
}
if (!String.IsNullOrEmpty(extension))
{
beautifulNumber += " x" + extension;
}
return beautifulNumber;
}
And here is how I have the variable in the class itself.
private string _PhonePrimary;
[DisplayName("Phone Primary")]
public string PhonePrimary
{
get
{
if(this._PhonePrimary != null)
{
this._PhonePrimary = beautifyPhoneNumber(this._PhonePrimary, this.Extension);
}
return this._PhonePrimary;
}
set
{
this._PhonePrimary = value;
}
}
This works fine most of the time. The numbers are outputted to the screen in a "(727) 988-4545" or "(727) 988-4545 x12" if there is an extension for that record in the database.
The problem comes when I do a HttpPost request. The model information that is inside of the post request looks like this.
_PhonePrimary = "(727) 988-4545"
PhonePrimary = "(((7) 2) -7) -"
As noted, it looks like you're calling beautifyPhoneNumber on a number you've already beautified.
Here's an implementation using regular expressions that should get you started:
public static String BeautifyPhoneNumber(string numberToBeautify)
{
//The below gives us capture groups for each
//individual piece of the number.
var regularExpression = new Regex(#"(\d{3})(\d{3})(\d{4})(x\d*)?");
//This matches a number that's already been beautified,
//so we can guard against beautifying twice.
var alreadyBeautifulExpression = new Regex(#"(\(\d{3}\)) (\d{3})-(\d{4}) ?(x\d*)?");
var beautifulNumber = string.Empty;
var separator = "-";
var space = " ";
//This prevents us from accidentally beautifying
//something more than once
//You could also guard against this in your getter using a
//IsBeautified extension, using the alreadyBeautifulExpression above
if (alreadyBeautifulExpression.IsMatch(numberToBeautify))
{
return numberToBeautify;
}
//Trying to protect against invalid input... May be insufficient,
//Or unnecessary
if (string.IsNullOrEmpty(numberToBeautify)
|| regularExpression.Matches(numberToBeautify).Count <= 0)
{
return beautifulNumber;
}
GroupCollection groups = regularExpression.Matches(
numberToBeautify)[0].Groups;
//More protection against invalid input
if (groups.Count < 3)
{
return beautifulNumber;
}
//Given "7689131234",
beautifulNumber += "(" + groups[1] + ")" + space; //gives us "(768) "
beautifulNumber += groups[2] + separator; //gives us "(768) 913-"
beautifulNumber += groups[3]; //gives us "(768) 913-1234"
//If we have an extension, we add it.
if (groups[4] != null)
{
beautifulNumber += space + groups[4];
}
return beautifulNumber;
}
Given inputs of:
7279884545
7279884545x12
(727) 988-4545
This returns:
(727) 988-4545
(727) 988-4545 x12
(727) 988-4545

How to use Google Adsense with MVC C# Razor

I am trying to add Google Adsense to my MVC mobile web application. I'd like to implement the Google Adsense Mobile content ad code. The Scripting Language they have is asp 3.0. Is there an MVC helper I can use to display these ads on a MVC C# Razor page? I can't find anything about MVC and displaying web ads online at all. Would love some help, I am totally stuck.
If I use regular Adsense Javascript code. The code doesn't load when I click around the site. Only when I click refresh on the page.
A simple HtmlHelper translated from Adsense ASP sample :
public static class AdsenseHelper
{
public static MvcHtmlString Adsense(this HtmlHelper htmlHelper, string clientKey, string adSlot)
{
var context = htmlHelper.ViewContext.HttpContext;
var request = context.Request;
int googleTime = (DateTime.Now - new DateTime(1970, 1, 1)).Days;
var googleDt = (1000 * googleTime) + Math.Round(1000d * (DateTime.Now - DateTime.Today).Milliseconds);
var googleUserAgent = context.Server.UrlEncode(request.ServerVariables["HTTP_USER_AGENT"]);
var googleScheme = (string.Compare(request.ServerVariables["HTTPS"], "on") == 0) ? "https://" : "http://";
var googleAdUrl =
"http://pagead2.googlesyndication.com/pagead/ads?" +
"client=" + clientKey + // ca-mb-pub-0000000000000000
"&dt=" + googleDt +
"&ip=" + context.Server.UrlEncode(request.ServerVariables["REMOTE_ADDR"]) +
"&markup=xhtml" +
"&output=xhtml" +
"&ref=" + context.Server.UrlEncode(request.ServerVariables["HTTP_REFERER"]) +
"&slotname=" + adSlot + // 0000000000
"&url=" + context.Server.UrlEncode(googleScheme + request.ServerVariables["HTTP_HOST"] + request.ServerVariables["URL"]) +
"&useragent=" + googleUserAgent +
GoogleScreenRes(context.Request) +
GoogleMuid(context.Request) +
GoogleViaAndAccept(context, googleUserAgent);
using (var client = new System.Net.WebClient())
{
string result = client.DownloadString(googleAdUrl);
return new MvcHtmlString(result);
}
}
private static string GoogleColor(string value, int random)
{
var colorArray = value.Split(',');
return colorArray[random % (colorArray.Length)];
}
private static string GoogleScreenRes(HttpRequestBase request)
{
var screenRes = request.ServerVariables["HTTP_UA_PIXELS"];
char delimiter = 'x';
if (string.IsNullOrEmpty(screenRes))
{
screenRes = request.ServerVariables["HTTP_X_UP_DEVCAP_SCREENPIXELS"];
delimiter = ',';
}
if (string.IsNullOrEmpty(screenRes))
{
screenRes = request.ServerVariables["HTTP_X_JPHONE_DISPLAY"];
delimiter = '*';
}
if (screenRes != null)
{
string[] resArray = screenRes.Split(new[] { delimiter }, 2);
if (resArray.Length == 2)
{
return "&u_w=" + resArray[0] + "&u_h=" + resArray[1];
}
}
return string.Empty;
}
private static string GoogleMuid(HttpRequestBase request)
{
var muid = request.ServerVariables["HTTP_X_DCMGUID"];
if (!string.IsNullOrEmpty(muid))
{
return "&muid=" + muid;
}
muid = request.ServerVariables["HTTP_X_UP_SUBNO"];
if (!string.IsNullOrEmpty(muid))
{
return "&muid=" + muid;
}
muid = request.ServerVariables["HTTP_X_JPHONE_UID"];
if (!string.IsNullOrEmpty(muid))
{
return "&muid=" + muid;
}
muid = request.ServerVariables["HTTP_X_EM_UID"];
if (!string.IsNullOrEmpty(muid))
{
return "&muid=" + muid;
}
return string.Empty;
}
private static string GoogleViaAndAccept(HttpContextBase context, string googleUserAgent)
{
if (string.IsNullOrEmpty(googleUserAgent))
return string.Empty;
string googleViaAndAccept = string.Empty;
var via = context.Server.UrlEncode(context.Request.ServerVariables["HTTP_VIA"]);
if (!string.IsNullOrEmpty(via))
{
googleViaAndAccept = "&via=" + via;
}
var accept = context.Server.UrlEncode(context.Request.ServerVariables["HTTP_ACCEPT"]);
if (!string.IsNullOrEmpty(accept))
{
googleViaAndAccept = googleViaAndAccept + "&accept=" + accept;
}
return googleViaAndAccept;
}
}
This helper does not work with desktop browsers. But can be bypassed by changing the useragent as Opera Mini.
Like Google says :
AdSense for Mobile Content is only for use on websites designed with older feature phones in mind. As fully web-capable smartphones become more and more common, we recommend that you use AdSense for Content for all of your Content Ads needs.

401 Error when trying to get Request Token

resp = (HttpWebResponse)request.GetResponse();Right I know this is probably some stupid mistake or just me not being well versed in Oauth stuff but I have come to a grinding halt and have no idea where to go from here, after many searches and attempts I humbly ask for some help.
I am attempting to get a request token from Twitter to try and get a users twitter feeds, I cannot use a library for other business reasons...
Here is the code so far:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("oauth_callback", "www.url.com/redirect.aspx");
parameters.Add("oauth_consumer_key", <Consumer_KEY>);
parameters.Add("oauth_nonce", generateNonce());
parameters.Add("oauth_signature_method", "HMAC-SHA1");
parameters.Add("oauth_timestamp", CurrentUNIXTimestamp.Get());
parameters.Add("oauth_version", "1.0");
parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value);
string concat = "";
string OAuthHeader = "OAuth ";
foreach (string k in parameters.Keys)
{
if (k == "oauth_callback")
{
concat += k + "%3D" + EncodeToUpper(parameters[k]) + "%26";
OAuthHeader += k + "=" + "\"" + EncodeToUpper(parameters[k]) + "\", ";
}
else
{
concat += k + "%3D" + parameters[k] + "%26";
OAuthHeader += k + "=" + "\"" + parameters[k] + "\", ";
}
}
concat = concat.Remove(concat.Length - 3, 3);
concat = "POST&" + EncodeToUpper("https://api.twitter.com/oauth/request_token" ) + "&" + concat;
//byte[] content = Encoding.UTF8.GetBytes(concat);
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", EncodeToUpper(<CONSUMER SECRET>, ""));
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(concat);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
string hash = Convert.ToBase64String(hashBytes);
OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\"";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth/request_token");
request.Method = "POST";
request.Headers["Authorization"] = OAuthHeader;
StringBuilder responding = new StringBuilder();
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)request.GetResponse();
}
catch (WebException exc)
{
lblError.Text = "Error Connecting to Social Network " + exc.Message;
}
if (resp != null)
{
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
responding.Append(reader.ReadToEnd());
}
}
An Example of the Nonce is "ne8ehvVr0pW2EUxNHdxdyqbi8Fwphatt3SW1yerTyXH" and the CurrentUNIXTimestamp is generated by
public static class CurrentUNIXTimestamp
{
public static string Get()
{
return Convert.ToString((int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds);
}
}
I have tried as many things as I can think of, there is no longer a client/browser issue (which was many other answers), the server time is correct to British Summer Time (I don't know whether that would be an issue but I tried adding an hour to the unix time stamp still a 401.), and i have defined the callback url on the twitter app page
I have got the same app working with facebook (I know its different oauth but may help)
The actual error comes at resp = (HttpWebResponse)request.GetResponse();, which comes up with a 401 error. I couldn't get any further details from the exc.response object, could anyone say how to get something useful out of the error in VS2008?
Thanks for any answers
The hardest problem I had implementing OAuth was dealing with character encoding. It's very particular.
Here is the code I ended up writing for it.
private static string UrlEncode(IEnumerable<KeyValuePair<string, object>> parameters)
{
StringBuilder parameterString = new StringBuilder();
var paramsSorted = from p in parameters
orderby p.Key, p.Value
select p;
foreach (var item in paramsSorted)
{
if (parameterString.Length > 0)
{
parameterString.Append("&");
}
if(item.Value.GetType() == typeof(string) )
parameterString.Append(
string.Format(
CultureInfo.InvariantCulture,
"{0}={1}",
UrlEncode(item.Key),
UrlEncode(item.Value as string)));
}
return UrlEncode(parameterString.ToString());
}
public static string UrlEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
value = Uri.EscapeDataString(value);
// UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F
value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
// these characters are not escaped by UrlEncode() but needed to be escaped
value = value
.Replace("(", "%28")
.Replace(")", "%29")
.Replace("$", "%24")
.Replace("!", "%21")
.Replace("*", "%2A")
.Replace("'", "%27");
// these characters are escaped by UrlEncode() but will fail if unescaped!
value = value.Replace("%7E", "~");
return value;
}
If you really get fed up, you can use the WebRequestBuilder class from my library to do all the OAuth stuff for you: http://www.twitterizer.net/

Payment succeeds, and our data matches querystring data, but falls thru to INVALID anyway!

Why does my ipn script I wrote always fail? It always goes to INVALID even though it matches everything in the query string that paypal sends to me?
notification.cshtml?tx=b78v54b5b55rby92S&st=Completed&amt=3.04&cc=USD&cm=&item_number=&merchant_return_link=Return+to+web+site+name&form_charset=UTF-8
And the part that checks it is:
string LiveURL = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LiveURL);
// Set request back values.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] parameters = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string RequestString = System.Text.Encoding.ASCII.GetString(parameters);
RequestString += "&cmd=_notify-validate";
request.ContentLength = RequestString.Length;
// Send request to PP and get response.
StreamWriter Sout = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
Sout.Write(RequestString);
Sout.Close();
StreamReader Sin = new StreamReader(request.GetResponse().GetResponseStream());
string response = Sin.ReadToEnd();
Sin.Close();
if(result != null && result.OrderStatus == "Confirmed")
{
switch(response)
{
case "VERIFIED":
if(Request["st"] == "Completed")
{
var PPQuery = "SELECT TransactionId, OrderTotal FROM Orders WHERE OrderId = '" + Session["OSFOID"] + "' AND UserId = '" + WebSecurity.CurrentUserId + "'";
var ppQueryResult = database.Query(PPQuery);
foreach(var item in ppQueryResult)
{
decimal fff = 3.04M;
if(item["TransactionId"] != Request["tx"])
{
if(item["OrderTotal"] == TotalPrice)
{
// Payment was a success. Convey that to the user.
output = "Thanks. Order complete.";
}
else
{
// Possible fraud. Log it.
}
}
else
{
// This is a duplicate transaction. Log it and Redirect to homepage.
}
}
}
break;
case "INVALID":
output = "Invalid was returned. Investigate further.";
break;
default:
output = "Other exception has occured. Investigate further and log.";
break;
}
}
The code looks fine. The problem must be with response not matching "VERIFIED".
You're not in Turkey by chance, and changing response to uppercase prior to the comparison? *
*) If the locale is Turkey, uppercasing a string turns i into İ, not I (just one of the many traps with string manipulation)
Within the "VERIFIED" block, check:
if (Request.Params["payment_status"] == "Completed")
{
...
}
Request["st"] is incorrect.
Be sure to set IPN URL in one place in PayPal admin and do not use the other form of return URL checking (can't remember the name of it offhand) and IPN at the same time.
There is no "merchant_return_link" parameter; I think it should be "notify_url"... the URL string and the list of params doesn't look right to me; for example: &cm=&item_number
I know your list of params will be unique for your situation, but here's some sample code where I construct the URL to be passed to PayPal:
protected string GetPayPalURL(string SERVER_URL, string business, string[] itemNames,
int[] quantities, decimal[] amounts, double[] weight, string invoiceID, string transID, string NOTIFY_URL)
{
// Customer will be required to specify delivery address to PayPal - VERY IMPORTANT
const string NO_SHIPPING = "2";
StringBuilder url = new StringBuilder();
url.Append(SERVER_URL + "?cmd=_cart&upload=1");
url.Append("&business=" + HttpUtility.UrlEncode(business));
for (int i = 0; i < itemNames.Length; i++)
{
url.Append("&item_name" + "_" + (i + 1).ToString() + "=" + HttpUtility.UrlEncode(itemNames[i]));
url.Append("&quantity" + "_" + (i + 1).ToString() + "=" + quantities[i].ToString().Replace(",", "."));
url.Append("&amount" + "_" + (i + 1).ToString() + "=" + amounts[i].ToString().Replace(",", "."));
url.Append("&weight" + "_" + (i + 1).ToString() + "=" + weight[i].ToString().Replace(",", "."));
}
url.Append("&no_shipping=" + HttpUtility.UrlEncode(NO_SHIPPING));
url.Append("&custom=" + HttpUtility.UrlEncode(invoiceID));
url.Append("&txn_id=" + HttpUtility.UrlEncode(transID));
url.Append("&notify_url=" + HttpUtility.UrlEncode(NOTIFY_URL));
return url.ToString();
}
I think the Paypal method you are trying to do is as follows on code project
and if you get payment_status = INVALID, then check the reason in payment_reason
i dont see in the code where you are defining result which is checked in the if, also in the switch you are checking against request, surely this should be against response?

Categories

Resources