Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created December 24, 2010 13:40
Show Gist options
  • Select an option

  • Save follesoe/754239 to your computer and use it in GitHub Desktop.

Select an option

Save follesoe/754239 to your computer and use it in GitHub Desktop.
First code snippet from blog post on free SMS
// Copyright (c) 2007, Jonas Follesø
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Jonas Follesø nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY Jonas Follesø ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Jonas Follesø BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Security.Authentication;
namespace Ung1881
{
/// <summary>
/// Proxy class wrapping the Ung1881 site for free SMS messaging.
/// </summary>
public class Ung1881Proxy
{
/// <summary>
/// Variable used to store the authentication cookie.
/// </summary>
private CookieContainer cookies;
/// <summary>
/// Variable used to store the base uri of the page.
/// </summary>
private string baseUri = "https://www.ung1881.no/";
/// <summary>
/// Default constructor.
/// </summary>
public Ung1881Proxy()
{
cookies = new CookieContainer();
}
/// <summary>
/// Login on Ung1881 using username and password.
/// Authenticates against the site and keeps the auth cookie for next request.
/// </summary>
/// <param name="username">Username used to logon.</param>
/// <param name="password">Password used to logon.</param>
public void Login(string username, string password)
{
//Validate arguments.
if (username == null || username.Length == 0)
throw new ArgumentException("You must provide a username!", "username");
if (password == null || password.Length == 0)
throw new ArgumentException("You must provide a password!", "password");
string loginUri = baseUri + "default____3.aspx";
// Perform the first http request against the asp.net application login site.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUri);
// Get the response object, so that we may get the session cookie.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Populate the cookie container.
request.CookieContainer = cookies;
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
// Read the incoming stream containing the login dialog page.
StreamReader reader = new StreamReader(response.GetResponseStream());
string loginDlgPage = reader.ReadToEnd();
reader.Close();
// Extract the viewstate value from the login dialog page.
// We need to post this back, along with the username and password
string viewState = GetViewState(loginDlgPage);
// Build postback string.
// This string will vary depending on the page. The best way to find out what your postback
// should look like is to monitor a normal login using a utility like Fiddler.
string postback = String.Format("__VIEWSTATE={0}&defaultframework:login:tbxUsername={1}" +
"&defaultframework:login:tbxPassword={2}" +
"&defaultframework:login:LoginButton.x=0&defaultframework:login:LoginButton.y=0",
viewState, username, password);
// Our second request is the POST of the username / password data.
request = (HttpWebRequest)WebRequest.Create(loginUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
// Write our postback data into the request stream
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(postback);
writer.Close();
reader = new StreamReader(request.GetResponse().GetResponseStream());
loginDlgPage = reader.ReadToEnd();
reader.Close();
int index = loginDlgPage.IndexOf("Logg ut", StringComparison.OrdinalIgnoreCase);
if (!CheckAuthenticationCookies() || index == -1)
{
throw new AuthenticationException("Unable to authenticate user. Check your username and password.");
}
}
/// <summary>
/// Method sending a new SMS message trough Ung1881.
/// </summary>
/// <param name="phoneNumber">The phone number of the receiver.</param>
/// <param name="message">The message to send.</param>
/// <returns>True if the message was sendt sucsessfully.</returns>
public void SendSms(string phoneNumber, string message)
{
//Validate arguments
if (phoneNumber == null || phoneNumber.Length == 0)
throw new ArgumentException("You need to provide a phone number!");
if (message == null || message.Length == 0)
throw new ArgumentException("You need to provide a message!");
//Check that we have an authentication cookie.
if (!CheckAuthenticationCookies())
throw new AuthenticationException("User not authenticated. Call Login first!");
//our third request is for the actual webpage after the login.
string smsUrl = baseUri + "/Templates/SMS____24.aspx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(smsUrl);
request.CookieContainer = cookies;
//and read the response
StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());
string page = reader.ReadToEnd();
string viewState = GetViewState(page);
string postback = String.Format("__VIEWSTATE={0}&defaultframework:_ctl2:Smssend:txtPhonenumber={1}" +
"&defaultframework:_ctl2:Smssend:txtText={2}&defaultframework:_ctl2:Smssend:butSend.x=0" +
"&defaultframework:_ctl2:Smssend:butSend.y=0", viewState, phoneNumber, message);
reader.Close();
request = (HttpWebRequest)WebRequest.Create(smsUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
//Write our postback data into the request stream
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(postback);
writer.Close();
//Execute the request and read the response.
reader = new StreamReader(request.GetResponse().GetResponseStream());
page = reader.ReadToEnd();
reader.Close();
//Verify that the message was sent.
if (!page.Contains("SMS sendt"))
{
throw new Ung1881Exception("Unable to send SMS message. Unknown error.");
}
}
/// <summary>
/// Check if the user is authenticated.
/// </summary>
/// <returns>True if the user is authenticated.</returns>
private bool CheckAuthenticationCookies()
{
bool authenticated = false;
//Check that we have cookies.
if (cookies != null)
{
//Check all cookies for the EpiServerLogin cookie.
foreach (Cookie cookie in cookies.GetCookies(new Uri(baseUri)))
{
if (cookie.Name != null &&
cookie.Name.Equals(".EPiServerLogin", StringComparison.OrdinalIgnoreCase))
authenticated = true;
}
}
return authenticated;
}
/// <summary>
/// Extract the viewstate data from a page.
/// </summary>
/// <param name="aspxPage">The raw HTML of the page.</param>
/// <returns>Thew viewstate data of the page.</returns>
private string GetViewState(string aspxPage)
{
Regex regex = new Regex("(?<=(__viewstate\".value.\")).*(?=\"./>)", RegexOptions.IgnoreCase);
Match match = regex.Match(aspxPage);
return System.Web.HttpUtility.UrlEncode(match.Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment