How to connect to Mailman mailing list using .Net - c#

I have to develop a .Net application in which i have to add or remove a user from Mailman mailing list.My Question is whether there is any .Net connector or Dll to connect to mailman mailing list using .Net.

Edit (9/21/14): I have just released a NuGet package for manipulating most aspects of a Mailman v2 list via HTTP calls. https://www.nuget.org/packages/MailmanSharp/
I'm not aware of any existing component to do this, but since the Mailman interface is all on the web, you can "control" it with HttpWebRequest; I recently wrote a small app which can retrieve the subscriber list, subscribe/unsubscribe people, and set individual flags like moderate/nomail/etc. It takes a little poking around in the source of the Mailman pages to see what variables need to be set in the POST, and some trial and error. I suggest setting up a temp Mailman list just to play with.
In order to do most of this, you'll need a persistent CookieContainer that you can hook up to your different HttpWebRequests; the first call is a POST to the admin page with the admin password to set the session cookie that gives you access to the other pages.
Some of the POSTs are regular application/x-www-form-urlencoded types, but some are also multipart/form-data. For the latter, I found some very helpful code at http://www.briangrinstead.com/blog/multipart-form-post-in-c I had to make a couple of changes so that I could pass in my CookieContainer
Here's some sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Threading;
namespace UpdateListserv
{
class Program
{
static void Main(string[] args)
{
try
{
File.Delete(_logFilename);
Log(String.Format("Starting: {0}", DateTime.Now));
Login();
var roster = GetSubscribers();
Unsubscribe(roster);
string members = GetMemberEmails();
Subscribe(members);
Unmoderate("foo#example.com");
Log("Done");
}
catch(Exception e)
{
Log(e.Message);
}
}
private static void Unmoderate(string email)
{
Log("Unmoderating " + email);
email = email.Replace("#", "%40");
_vars.Clear();
_vars["user"] = email;
_vars[email + "_nomail"] = "off";
_vars[email + "_nodupes"] = "on";
_vars[email + "_plain"] = "on";
_vars[email + "_language"] = "en";
_vars["setmemberopts_btn"] = "Submit Your Changes";
FormUpload.MultipartFormDataPost(_adminUrl + _membersPage, "foobar", _vars, _cookies);
}
private static CookieContainer _cookies = new CookieContainer();
private static string _adminUrl = "http://mylist.com/admin.cgi/listname";
private static string _rosterUrl = "http://mylist.com/roster.cgi/listname";
private static string _pw = "myPassword";
private static string _adminEmail = "foo#example.com";
private static Dictionary<string, object> _vars = new Dictionary<string, object>();
private static string _addPage = "/members/add";
private static string _removePage = "/members/remove";
private static string _membersPage = "/members";
private static string _logFilename = "Update Listserv.log";
private static void Log(string message)
{
Console.WriteLine(message);
using (var log = File.AppendText(_logFilename))
log.WriteLine(message);
}
private static void Subscribe(string members)
{
// members is a list of email addresses separated by \n
Log("Subscribing everyone");
_vars.Clear();
_vars["subscribees"] = members;
_vars["subscribe_or_invite"] = 0;
_vars["send_welcome_msg_to_this_batch"] = 0;
_vars["send_notifications_to_list_owner"] = 0;
FormUpload.MultipartFormDataPost(_adminUrl + _addPage, "foobar", _vars, _cookies);
}
private static string GetMemberEmails()
{
// This method retrieves a list of emails to be
// subscribed from an external source
// and returns them as a string with \n in between.
}
private static void Unsubscribe(string roster)
{
// roster is a list of email addresses separated by \n
Log("Unsubscribing everybody");
_vars.Clear();
_vars["unsubscribees"] = roster;
_vars["send_unsub_ack_to_this_batch"] = 0;
_vars["send_unsub_notifications_to_list_owner"] = 0;
FormUpload.MultipartFormDataPost(_adminUrl + _removePage, "foobar", _vars, _cookies);
}
private static string GetSubscribers()
{
// returns a list of email addresses subscribed to the list,
// separated by \n
Log("Getting subscriber list");
var req = GetWebRequest(_rosterUrl);
req.Method = "post";
_vars.Clear();
_vars["roster-email"] = _adminEmail;
_vars["roster-pw"] = _pw;
var rosterLines = GetResponseString(req).Split('\n').Where(l => l.StartsWith("<li>"));
Log(String.Format("Got {0} subscribers", rosterLines.Count()));
var roster = new List<string>();
var regex = new Regex("<a.*>(.*)</a>");
foreach (var line in rosterLines)
{
roster.Add(regex.Match(line).Groups[1].Value.Replace(" at ", "#"));
}
return String.Join("\n", roster);
}
private static void Login()
{
Log("Logging in to list admin panel");
var req = GetWebRequest(_adminUrl);
req.Method = "post";
_vars["adminpw"] = _pw;
SetPostVars(req);
req.GetResponse();
}
private static HttpWebRequest GetWebRequest(string url)
{
var result = HttpWebRequest.Create(url) as HttpWebRequest;
result.AllowAutoRedirect = true;
result.CookieContainer = _cookies;
result.ContentType = "application/x-www-form-urlencoded";
return result;
}
private static string GetResponseString(HttpWebRequest req)
{
using (var res = req.GetResponse())
using (var stream = res.GetResponseStream())
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
private static void SetPostVars(HttpWebRequest req)
{
var list = _vars.Select(v => String.Format("{0}={1}", v.Key, v.Value));
using (var stream = req.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(String.Join("&", list));
}
}
}
}

Related

Bing Maps REST Services Toolkit - Access Value Outside of Delegate

This sample code for the Bing Maps REST Services Toolkit uses a delegate to get the response and then outputs a message from within the delegate method. However, it does not demonstrate how to access the response from outside of the invocation of GetResponse. I cannot figure out how to return a value from this delegate. In other words, let us say I want to use the value of the longitude variable right before the line Console.ReadLine(); How do I access that variable in that scope?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BingMapsRESTToolkit;
using System.Configuration;
using System.Net;
using System.Runtime.Serialization.Json;
namespace RESTToolkitTestConsoleApp
{
class Program
{
static private string _ApiKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey");
static void Main(string[] args)
{
string query = "1 Microsoft Way, Redmond, WA";
Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, _ApiKey));
GetResponse(geocodeRequest, (x) =>
{
Console.WriteLine(x.ResourceSets[0].Resources.Length + " result(s) found.");
decimal latitude = (decimal)((Location)x.ResourceSets[0].Resources[0]).Point.Coordinates[0];
decimal longitude = (decimal)((Location)x.ResourceSets[0].Resources[0]).Point.Coordinates[1];
Console.WriteLine("Latitude: " + latitude);
Console.WriteLine("Longitude: " + longitude);
});
Console.ReadLine();
}
private static void GetResponse(Uri uri, Action<Response> callback)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += (o, a) =>
{
if (callback != null)
{
// Requires a reference to System.Runtime.Serialization
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
callback(ser.ReadObject(a.Result) as Response);
}
};
wc.OpenReadAsync(uri);
}
}
}
For the provided example AutoResetEvent class could be utilized to control the flow, in particular to wait asynchronous WebClient.OpenReadCompleted Event is completed like this:
class Program
{
private static readonly string ApiKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey");
private static readonly AutoResetEvent StopWaitHandle = new AutoResetEvent(false);
public static void Main()
{
var query = "1 Microsoft Way, Redmond, WA";
BingMapsRESTToolkit.Location result = null;
Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}",
query, ApiKey));
GetResponse(geocodeRequest, (x) =>
{
if (response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
}
});
StopWaitHandle.WaitOne(); //wait for callback
Console.WriteLine(result.Point); //<-access result
Console.ReadLine();
}
private static void GetResponse(Uri uri, Action<Response> callback)
{
var wc = new WebClient();
wc.OpenReadCompleted += (o, a) =>
{
if (callback != null)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
callback(ser.ReadObject(a.Result) as Response);
}
StopWaitHandle.Set(); //signal the wait handle
};
wc.OpenReadAsync(uri);
}
}
Option 2
Or to switch to ServiceManager class that makes it easy when working via asynchronous programming model:
public static void Main()
{
var task = ExecuteQuery("1 Microsoft Way, Redmond, WA");
task.Wait();
Console.WriteLine(task.Result);
Console.ReadLine();
}
where
public static async Task<BingMapsRESTToolkit.Location> ExecuteQuery(string queryText)
{
//Create a request.
var request = new GeocodeRequest()
{
Query = queryText,
MaxResults = 1,
BingMapsKey = ApiKey
};
//Process the request by using the ServiceManager.
var response = await request.Execute();
if (response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
return response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
}
return null;
}

How can I make this c# method multithreaded? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this c# class that I am trying to make multi-threaded, or able to run 100 threads (requests?) at once.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("C:\\checker/in.txt");
var accCount = File.ReadLines(#"C:\checker/in.txt").Count();
Console.Write("Accounts loaded: " + accCount);
Console.WriteLine();
foreach (string line in lines)
{
string[] account = line.Split(new char[] { ':' });
string user = account[0];
string pass = account[1];
addThreads(user, pass);
Threads.ForEach(t => t.Start());
Console.WriteLine();
}
// Suspend the screen.
Console.ReadLine();
}
public static List<Thread> Threads = new List<Thread>();
public static void addThreads(string user, string pass)
{
var checker = new Checker();
Threads.Clear();
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
}
}
public class Checker
{
//declare vars
string getUsername;
string getMember;
string getAuth;
string check;
public void checkAccount(string username, string password)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
byte[] data = Encoding.ASCII.GetBytes(
$"username={username}&password={password}&mod=www&ssl=1&dest=account_settings.ws");
WebRequest request = WebRequest.Create("https://secure.runescape.com/m=weblogin/login.ws");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
//parse captcha
string patternCaptcha = #"Please\s*complete\s*the\s*reCAPTCHA\s*box";
string inputCaptcha = responseContent;
Match matchCaptcha = Regex.Match(inputCaptcha, patternCaptcha);
string captcha = matchCaptcha.Value;
if (captcha == "Please complete the reCAPTCHA box")
{
captcha = "true";
Console.Write("captcha,captcha,captcha,captcha");
Console.WriteLine();
//return "captcha,captcha,captcha,captcha";
}
else
{
//parse valid/invalid
string patternCheck = #"Your\s*login\s*or\s*password\s*was\s*incorrect";
string inputCheck = responseContent;
Match matchCheck = Regex.Match(inputCheck, patternCheck);
check = matchCheck.Value;
if (check == "Your login or password was incorrect")
{
check = "Invalid";
}
else
{
check = "Valid";
//parse display name
string pattern = #"(<span.*class=.header-top__name.>(.*?)</span>)";
string input = responseContent;
Match match = Regex.Match(input, pattern);
getUsername = match.Groups[2].Value;
byte[] bytes = Encoding.Default.GetBytes(getUsername);
getUsername = Encoding.UTF8.GetString(bytes);
getUsername = getUsername.Replace("?", " ");
//parse member status
string patternMember = #"(Currently\s*Not\s*a\s*Member)";
string inputMember = responseContent;
Match matchMember = Regex.Match(inputMember, patternMember);
getMember = matchMember.Value;
if (getMember == "Currently Not a Member")
{
getMember = "Non Member";
}
else
{
getMember = "Member";
}
//parse auth status
string patternAuthUrl = #"iframe src=\""(.*?)""";
string inputAuthUrl = responseContent;
Match matchAuthUrl = Regex.Match(inputAuthUrl, patternAuthUrl);
string getAuthUrl = matchAuthUrl.Groups[1].Value;
using (WebClient client = new WebClient())
{
string authSource = client.DownloadString(getAuthUrl);
string patternAuth = #"RuneScape\s*Authenticator\s*is\s*disabled";
string inputAuth = authSource;
Match matchAuth = Regex.Match(inputAuth, patternAuth);
getAuth = matchAuth.Value;
if (getAuth == "RuneScape Authenticator is disabled")
{
getAuth = "Auth Disabled";
}
else
{
getAuth = "Authed";
}
}
}
captcha = "false";
string curldata = getUsername + "," + getMember + "," + getAuth + "," + check;
Console.Write(curldata);
Console.WriteLine();
}
}
}
}
Instead of making my program check once per few seconds per post webrequest, how can I make this happen 50-100 times at the same time? Is this possible? Or do I need to do this a different way?
You need to avoid using threads as each thread uses in excess of 1MB of RAM and they are slow to create. You really want to use tasks (TPL) or observables (Rx).
In this case it is quite straight forward to use tasks.
Try this code:
string[] lines = File.ReadAllLines("C:\\checker/in.txt");
var accCount = lines.Count();
Console.Write("Accounts loaded: " + accCount);
Console.WriteLine();
var checker = new Checker();
var tasks =
from line in lines
let account = line.Split(new char[] { ':' })
let user = account[0]
let pass = account[0]
select Task.Factory.StartNew(() => checker.checkAccount(user, pass));
Task.WaitAll(tasks.ToArray());
Console.ReadLine();
That will read the text file and queue up a set of tasks to be run to check each line. The Task.WaitAll pauses the code until all of the tasks are completed.
This make efficient use of the thread-pool so that you're not wasting valuable resources starting up threads.
Your checkAccount is also not thread-safe at the moment. You need to move the field-level variables to be inside your method. It should look something like this:
public void checkAccount(string username, string password)
{
string getUsername;
string getMember;
string getAuth;
string check;
It's pretty simple first you need to do a method to call the threads
public void CallingThreadsMethod()
{
ThreadStart ts = new ThreadStart(SomeFunction);
Thread t = Thread(ts);
t.IsBackground = true;
t.Start();
}
void Somefunction(){}
or if you want many threads you can make a thread list
public static List<Thread> Threads = new List<Thread>();
public static void addThreads()
{
Threads.Clear();
Threads.Add(new Thread(Method1));
Threads.Add(new Thread(Method2));
}
And start it in you'r main function
Vars.addThreads();
Vars.Threads.ForEach(t => t.Start());
but if you're using windows forms or wpf i recommend using BackgroundWorkers

StreamWriter failing to run after 1st iteration in for loop

I'm having issues using StreamWriter to code a scraper for a current project i've got. The loop i've coded is below
I've debugged all the variables coming into the loop and everything is set as it should be. When i pass in a url and the range to search through based on an ID GET variable in the url it fails to write the second sourceCode string
Could someone be kind enough to tell me if i'm not flushing something or is there something else at work here??
I've wrecked my head trying to find the root cause but its proving very stubborn
using System;
using System.IO;
using System.Windows.Forms;
namespace Scraper
{
public partial class Form1 : Form
{
Scraper scraper = new Scraper();
private StreamWriter sw;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
string[] urlBits = url.Split('.');
string[] domain = urlBits[2].Split('/');
string filepath = #"C:\Users\Herbaldinho\Desktop\"+urlBits[1]+"-"+domain[0];
string parentPath = #"C:\Users\Herbaldinho\Desktop\";
string newPath = Path.Combine(parentPath, filepath);
if (File.Exists(filepath))
{}
else
{
Directory.CreateDirectory(newPath);
}
DateTime today = DateTime.Today;
string curDate = String.Format("{0:ddd-MMM-dd-yyyy}", today);
string subPath = newPath + "\\" + curDate;
string newSubPath = Path.Combine(newPath, subPath);
if (File.Exists(subPath))
{ }
else
{
Directory.CreateDirectory(newSubPath);
}
string lower = textBox2.Text;
int lowerValue;
int.TryParse(lower, out lowerValue);
string upper = textBox3.Text;
int upperValue;
int.TryParse(upper, out upperValue);
int i;
for (i = lowerValue; i < upperValue; i++)
{
string filename = newSubPath+"\\Advert-"+i+".html";
string adPage = url + i;
bool write = scraper.UrlExists(adPage);
if (write)
{
string sourceCode = scraper.getSourceCode(adPage);
using (sw = new StreamWriter(filename))
{
sw.Write(sourceCode);
}
}
}
MessageBox.Show("Scrape Complete");
}
}
}
####This is the Scraper Object
using System.Net;
namespace Scraper
{
class Scraper
{
WebClient w = new WebClient();
public bool UrlExists(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}
public string getSourceCode(string url)
{
string s = w.DownloadString(url);
return s;
}
}
}
Found the answer to the problem this morning
For anyone else having a similar problem, the try catch logic in the UrlExists method needs to close the response (response.Close())
From what i had understood it autoclosed but this is not the case
Hope this helps
Many thanks for the responses in helping me resolve this everyone

Help with Janrain Engage openID C# code behind for asp.net forms website

I have signed up with Janrain Engage to incorporate its free widget based openID. But i can't figure out what values to put in the C# code behind. They have provided with a C# helper class, the one below:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.XPath;
public class Rpx
{
private string apiKey;
private string baseUrl;
public Rpx(string apiKey, string baseUrl) {
while (baseUrl.EndsWith("/"))
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
this.apiKey = apiKey;
this.baseUrl = baseUrl;
}
public string getApiKey() { return apiKey; }
public string getBaseUrl() { return baseUrl; }
public XmlElement AuthInfo(string token) {
Dictionary<string,string> query = new Dictionary<string,string>();
query.Add("token", token);
return ApiCall("auth_info", query);
}
public List<string> Mappings(string primaryKey) {
Dictionary<string,string> query = new Dictionary<string,string>();
query.Add("primaryKey", primaryKey);
XmlElement rsp = ApiCall("mappings", query);
XmlElement oids = (XmlElement)rsp.FirstChild;
List<string> result = new List<string>();
for (int i = 0; i < oids.ChildNodes.Count; i++) {
result.Add(oids.ChildNodes[i].InnerText);
}
return result;
}
public Dictionary<string,ArrayList> AllMappings() {
Dictionary<string,string> query = new Dictionary<string,string>();
XmlElement rsp = ApiCall("all_mappings", query);
Dictionary<string,ArrayList> result = new Dictionary<string,ArrayList>();
XPathNavigator nav = rsp.CreateNavigator();
XPathNodeIterator mappings = (XPathNodeIterator) nav.Evaluate("/rsp/mappings/mapping");
foreach (XPathNavigator m in mappings) {
string remote_key = GetContents("./primaryKey/text()", m);
XPathNodeIterator ident_nodes = (XPathNodeIterator) m.Evaluate("./identifiers/identifier");
ArrayList identifiers = new ArrayList();
foreach (XPathNavigator i in ident_nodes) {
identifiers.Add(i.ToString());
}
result.Add(remote_key, identifiers);
}
return result;
}
private string GetContents(string xpath_expr, XPathNavigator nav) {
XPathNodeIterator rk_nodes = (XPathNodeIterator) nav.Evaluate(xpath_expr);
while (rk_nodes.MoveNext()) {
return rk_nodes.Current.ToString();
}
return null;
}
public void Map(string identifier, string primaryKey) {
Dictionary<string,string> query = new Dictionary<string,string>();
query.Add("identifier", identifier);
query.Add("primaryKey", primaryKey);
ApiCall("map", query);
}
public void Unmap(string identifier, string primaryKey) {
Dictionary<string,string> query = new Dictionary<string,string>();
query.Add("identifier", identifier);
query.Add("primaryKey", primaryKey);
ApiCall("unmap", query);
}
private XmlElement ApiCall(string methodName, Dictionary<string,string> partialQuery) {
Dictionary<string,string> query = new Dictionary<string,string>(partialQuery);
query.Add("format", "xml");
query.Add("apiKey", apiKey);
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> e in query) {
if (sb.Length > 0) {
sb.Append('&');
}
sb.Append(System.Web.HttpUtility.UrlEncode(e.Key, Encoding.UTF8));
sb.Append('=');
sb.Append(HttpUtility.UrlEncode(e.Value, Encoding.UTF8));
}
string data = sb.ToString();
Uri url = new Uri(baseUrl + "/api/v2/" + methodName);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
// Write the request
StreamWriter stOut = new StreamWriter(request.GetRequestStream(),
Encoding.ASCII);
stOut.Write(data);
stOut.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream ();
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.Load(dataStream);
XmlElement resp = doc.DocumentElement;
if (resp == null || !resp.GetAttribute("stat").Equals("ok")) {
throw new Exception("Unexpected API error");
}
return resp;
}
public static void Main(string[] args) {
Rpx r = new Rpx(args[0], args[1]);
if (args[2].Equals("mappings")) {
Console.WriteLine("Mappings for " + args[3] + ":");
foreach(string s in r.Mappings(args[3])) {
Console.WriteLine(s);
}
}
if (args[2].Equals("all_mappings")) {
Console.WriteLine("All mappings:");
foreach (KeyValuePair<string, ArrayList> pair in r.AllMappings()) {
Console.WriteLine(pair.Key + ":");
foreach (string identifier in pair.Value) {
Console.WriteLine(" " + identifier);
}
}
}
if (args[2].Equals("map")) {
Console.WriteLine(args[3] + " mapped to " + args[4]);
r.Map(args[3], args[4]);
}
if (args[2].Equals("unmap")) {
Console.WriteLine(args[3] + " unmapped from " + args[4]);
r.Unmap(args[3], args[4]);
}
}
}
Forgive me but i'm not a master of C#, but i can't figure out where to put the values for the apiKey and the token_url. Also if a user signs in how to display the username as derived from the accounts he is using to sign up, Google or Yahoo! for example.
Also there is no sign out option provided.
Any help would be much appreciated as the Janrain developer help is nothing but useless.
I agree the JanRain does not make this very clear. You do not need to modify the Rpx helper example code provided. Here is some code that makes use of their Rpx helper class from an MVC application. Be sure to include System.Xml and System.Xml.Linq.
var token = Request.Form["token"];
var rpx = new Helpers.Rpx("your-api-key-goes-here", "https://rpxnow.com");
var authInfo = rpx.AuthInfo(token);
var doc = XDocument.Load(new XmlNodeReader(authInfo));
ViewData["displayName"] = doc.Root.Descendants("displayName").First().Value;
ViewData["identifier"] = doc.Root.Descendants("identifier").First().Value;

Image URL validation in C#

How can i check if my image link is valid for both IE and FF? For example this link works just in FF, no image is displayed in IE browser. I checked the image and the color space is RGB. So image space problem is excluded.
Thanks.
Get a copy of fiddler to see the differences in response for each of the browsers. You may find that the headers are wrong and FF is correcting but IE is not.
http://www.fiddler2.com/fiddler2/
Hope this helps
Here is a class that will let you validate any kind of URI and will support multi-threaded validation of collection of URIs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
namespace UrlValidation
{
public class UrlValidator
{
internal static readonly Hashtable URLVerifications = new Hashtable();
internal readonly List<ManualResetEvent> Handles = new List<ManualResetEvent>();
internal void ValidateUrls()
{
var urlsToValidate = new[] { "http://www.ok12376876.com", "http//:www.ok.com", "http://www.ok.com", "http://cnn.com" };
URLVerifications.Clear();
foreach (var url in urlsToValidate)
CheckUrl(url);
if (Handles.Count > 0)
WaitHandle.WaitAll(Handles.ToArray());
foreach (DictionaryEntry verification in URLVerifications)
Console.WriteLine(verification.Value);
}
internal class RequestState
{
public WebRequest Request;
public WebResponse Response;
public ManualResetEvent Handle;
}
private void CheckUrl(string url)
{
var hashCode = url.GetHashCode();
var evt = new ManualResetEvent(false);
Handles.Add(evt);
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
URLVerifications[hashCode] = "Invalid URL.";
evt.Set();
return;
}
if (!URLVerifications.ContainsKey(hashCode))
URLVerifications.Add(hashCode, null);
// Create a new webrequest to the mentioned URL.
var wreq = WebRequest.Create(url);
wreq.Timeout = 5000; // 5 seconds timeout per thread (ignored for async calls)
var state = new RequestState{ Request = wreq, Handle = evt };
// Start the Asynchronous call for response.
var asyncResult = wreq.BeginGetResponse(RespCallback, state);
ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, TimeoutCallback, state, 5000, true);
}
private static void TimeoutCallback(object state, bool timedOut)
{
var reqState = (RequestState)state;
if (timedOut)
{
var hashCode = reqState.Request.RequestUri.OriginalString.GetHashCode();
URLVerifications[hashCode] = "Request timed out.";
if (reqState.Request != null)
reqState.Request.Abort();
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
ManualResetEvent evt = null;
int hashCode = 0;
try
{
var reqState = (RequestState)asynchronousResult.AsyncState;
hashCode = reqState.Request.RequestUri.OriginalString.GetHashCode();
evt = reqState.Handle;
reqState.Response = reqState.Request.EndGetResponse(asynchronousResult);
var resp = ((HttpWebResponse)reqState.Response).StatusCode;
URLVerifications[hashCode] = resp.ToString();
}
catch (WebException e)
{
if (hashCode != 0 && string.IsNullOrEmpty((string)URLVerifications[hashCode]))
URLVerifications[hashCode] = e.Response == null ? e.Status.ToString() : (int)((HttpWebResponse)e.Response).StatusCode + ": " + ((HttpWebResponse)e.Response).StatusCode;
}
finally
{
if (evt != null)
evt.Set();
}
}
}
}
Hope that helps

Categories