: Code




Attach JavaScript loaded as part from an external html page

September 30th, 2010 admin Posted in Html-JavaScript Comments Off


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>JavaScript On The Fly</TITLE>
 </HEAD>

 <BODY>

<input type="button" id="dialogOpener"  value="Show Dialog" onClick="handleDialogOpener();" />
<div id="dialog" style="position:absolute; width=200; height=200; left:100px; top:100px">
</div>

<SCRIPT LANGUAGE="JavaScript">
var dynamicConetnts = '<select name="number" onchange="handleNumberSelect(this);"><option value="1">one</option><option value="2">two</option><option value="3">three</option></select><script language="JavaScript">function handleNumberSelect(obj) {alert("selectedIndex = " + obj.selectedIndex);}<\/script>';
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
function handleDialogOpener() {

	var scriptInnerText = parseScriptInnerText(dynamicConetnts);

	var head = document.getElementsByTagName("head")[0];
	var scriptElement = createScriptElement(scriptInnerText);
	head.appendChild(scriptElement);

	document.getElementById('dialog').innerHTML = dynamicConetnts;
}

function parseScriptInnerText(scriptString) {
	scriptString = scriptString.substring(scriptString.indexOf("<script"));
	scriptString = scriptString.substring(scriptString.indexOf(">")+1);
	scriptString = scriptString.substring(0, scriptString.indexOf("<\/script>"));
	return scriptString;
}

function createScriptElement(scriptInnerText) {
	var scriptElement = document.createElement('script');
	var is_ie = navigator.userAgent.toLowerCase().indexOf("msie")!=-1?true:false;
	if (is_ie) {
		scriptElement.text = scriptInnerText;
	} else {
		var textNode = document.createTextNode(scriptInnerText);
		scriptElement.appendChild(textNode);
	}
	return scriptElement;
}

</SCRIPT>

 </BODY>
</HTML>
AddThis Social Bookmark Button

HTTP Digest Authentication: A Java Client

October 23rd, 2009 admin Posted in Java Comments Off

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

public class BrowserAuth {

	public static void main(String[] args) {
		try {

			// 
			String urlStr = “http://example.com:8080/abc/”;
			String host = “example.com”;
			String realm = “ExampleRealm”;
			String userName = “user”;
			String password = “password”;
			// 

			HttpClient client = new HttpClient();

			GetMethod getMethod = new GetMethod(urlStr);

			int status = client.executeMethod(getMethod);
			System.out.println(”status: ” + status);
			String responseBody = getMethod.getResponseBodyAsString();
			System.out.println(”responseBody: ” + responseBody);

			Header wwAuthHeader = getMethod.getResponseHeader(”WWW-Authenticate”);
			for (HeaderElement element : wwAuthHeader.getElements()) {
				System.out.println(element.getName() + “: ” + element.getValue());
			}

			UsernamePasswordCredentials upc = new UsernamePasswordCredentials(userName, password);
			AuthScope as = new AuthScope(host, 8080, realm);
			client.getState().setCredentials(as, upc);
			status = client.executeMethod(getMethod);
			System.out.println(”status: ” + status);
			responseBody = getMethod.getResponseBodyAsString();
			System.out.println(”responseBody: ” + responseBody);

			getMethod.releaseConnection();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
AddThis Social Bookmark Button

NTLM Authentication: Java Client Code

October 23rd, 2009 admin Posted in Java Comments Off

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

public class NtlmTest01 {

	public static void main(String[] args) throws Exception {

		String urlStr = “http://example.com/root/action.dll?p1=value1″;
		String domain = “”; // May also be referred as realm
		String userName = “CHANGE_ME”;
		String password = “CHANGE_ME”;		

		String responseText = getAuthenticatedResponse(urlStr, domain, userName, password);

	    System.out.println(”response: ” + responseText);
	}

	private static String getAuthenticatedResponse(final String urlStr, final String domain, final String userName, final String password) throws IOException {

	    StringBuilder response = new StringBuilder();

		Authenticator.setDefault(new Authenticator() {
	        @Override
	        public PasswordAuthentication getPasswordAuthentication() {
	            return new PasswordAuthentication(domain + “\\” + userName, password.toCharArray());
	        }
	    });

	    URL urlRequest = new URL(urlStr);
	    HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
	    conn.setDoOutput(true);
	    conn.setDoInput(true);
	    conn.setRequestMethod(”GET”);

	    InputStream stream = conn.getInputStream();
	    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
	    String str = “”;
	    while ((str = in.readLine()) != null) {
	        response.append(str);
	    }
	    in.close();		

	    return response.toString();
	}

}

Notest: NTLM Handshack
————————————————-

GET …

401 Unauthorized
WWW-Authenticate: NTLM
————————————————-
GET …
Authorization: NTLM TlRMTVNTUAABAAAAA7IAAAoACgApAAAACQAJACAAAABMSUdIVENJVFlVUlNBLU1JTk9S

401 Unauthorized
WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==
————————————————-
GET …
Authorization: NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABQAFABAAAAADAAMAFQAAAASABIAYAAAAAAAAACiAAAAAYIAAFUAUgBTAEEALQBNAEkATgBPAFIAWgBhAHAAaABvAGQATABJAEcASABUAEMASQBUAFkArYfKbe/jRoW5xDxHeoxC1gBmfWiS5+iX4OAN4xBKG/IFPwfH3agtPEia6YnhsADT

200 Ok
————————————————-

Ref: http://www.innovation.ch/personal/ronald/ntlm.html

AddThis Social Bookmark Button

Get Exception StackTrace as a String

June 25th, 2009 admin Posted in Java Comments Off

public static String getStackTraceString(Exception e) {
	StringWriter writer = new StringWriter();
	PrintWriter pw = new PrintWriter(writer);
	e.printStackTrace(pw);
	StringBuffer sb = writer.getBuffer();
	return sb.toString();
}
AddThis Social Bookmark Button

HtmlUnit: A Simple Example: Check Yahoo Email

August 26th, 2008 admin Posted in Java Comments Off

by Muneeb Ahmad


package com.examples.htmlunit;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;

public class YahooMail {

	public static void main(String[] args) throws Exception {

		// Create and initialize WebClient object
	    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_2);
	    webClient.setThrowExceptionOnScriptError(false);
	    webClient.setRefreshHandler(new RefreshHandler() {
			public void handleRefresh(Page page, URL url, int arg) throws IOException {
				System.out.println("handleRefresh");
			}

	    });

	    // visit Yahoo Mail login page and get the Form object
	    HtmlPage page = (HtmlPage) webClient.getPage("https://login.yahoo.com/config/login_verify2?.intl=us&amp;.src=ym");
	    HtmlForm form = page.getFormByName("login_form");

	    // Enter login and passwd
	    form.getInputByName("login").setValueAttribute("@@@@@@@");
	    form.getInputByName("passwd").setValueAttribute("@@@@@@@");

	    // Click "Sign In" button/link
	    page = (HtmlPage) form.getInputByValue("Sign In").click();

	    // Click "Inbox" link
	    HtmlAnchor anchor = (HtmlAnchor) page.getHtmlElementById("WelcomeInboxFolderLink");
	    page = (HtmlPage) anchor.click();

	    // Get the table object containing the mails
	    HtmlTable dataTable = (HtmlTable) page.getHtmlElementById("datatable");

	    // Go through each row and count the row with class=msgnew
	    int newMessageCount = 0;
	    List rows = (List) dataTable.getHtmlElementsByTagName("tr");
	    for (HtmlTableRow row: rows) {
	    	if (row.getAttribute("class").equals("msgnew")) {
	    		newMessageCount++;
	    	}
	    }	    

	    // Print the newMessageCount to screen
	    System.out.println("newMessageCount = " + newMessageCount);

	    //System.out.println(page.asXml());	   	     	    

	}
}
AddThis Social Bookmark Button

Get URL Response

July 18th, 2008 admin Posted in .NET/C# Comments Off


public string GetSiteContents(string url)
{
	StringBuilder sb  = new StringBuilder();
	byte[] buf = new byte[8192];
	HttpWebRequest  request  = (HttpWebRequest)	WebRequest.Create(url);
	HttpWebResponse response = (HttpWebResponse) request.GetResponse();

	Stream resStream = response.GetResponseStream();
	string tempString = null;
	int count = 0;
	do
	{
		count = resStream.Read(buf, 0, buf.Length);
		if (count != 0)
		{
			tempString = Encoding.ASCII.GetString(buf, 0, count);
			sb.Append(tempString);
		}
	}
	while (count > 0);

	return sb.ToString();
}
	
AddThis Social Bookmark Button

Cookies

July 18th, 2008 admin Posted in .NET/C# Comments Off


private void Page_Load(object sender, System.EventArgs e)
{
	if (!IsPostBack)
	{
		if (Request.Cookies["MuneebCookies"]!=null)
		{
			HttpCookie httpCookie = Request.Cookies["MuneebCookies"];
			TextBox1.Text = httpCookie["FirstName"];
			TextBox2.Text = httpCookie["LastName"];

		}
	}
}
private void Button1_Click(object sender, System.EventArgs e)
{
	HttpCookie httpCookie = new HttpCookie("MuneebCookies");
	httpCookie.Values.Add("FirstName", TextBox1.Text);
	httpCookie.Values.Add("LastName", TextBox2.Text);
	httpCookie.Expires  = DateTime.Now.AddHours(2);
	// httpCookie.Expires  = DateTime.Now.AddYears(50);
	// NEVER EXPIRES (practically)
	Response.Cookies.Add(httpCookie);
}

AddThis Social Bookmark Button

SMTP Mail

July 18th, 2008 admin Posted in .NET/C# Comments Off


using System;
using System.Web.Mail;

namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
	MailMessage Message = new MailMessage();
	Message.To = "to_address@domain.com";
	Message.From = "from_address@domain.com";
	Message.Subject = "test1";
	Message.Body = "test1";

	try
	{
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "muneebsa");
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "you03ahm");
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.sbcglobal.yahoo.com");
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", 10);
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
		Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", false); 

		SmtpMail.SmtpServer = "smtp.mydomain.com";
		SmtpMail.Send(Message);
	}
	catch(System.Web.HttpException ehttp)
	{
		Console.WriteLine("{0}", ehttp.Message);
		Console.WriteLine("Here is the full error message output");
		Console.Write("{0}", ehttp.ToString());
	}

}
}
}

AddThis Social Bookmark Button

Simple Database Access

July 18th, 2008 admin Posted in .NET/C# Comments Off


string connectionString = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=test;USER=root;PASSWORD=mypassword;OPTION=3;";
IDbConnection conn = new OdbcConnection(connectionString);
conn.Open();
IDbCommand command = new OdbcCommand("select UserID, FirstName from Users");
command.Connection = conn;
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
	string userID = (string) reader["UserID"];
	string firstName = (string) reader["FirstName"];
	Console.WriteLine("@@");
}
conn.Close();
AddThis Social Bookmark Button

Send Email using SmartMail

July 18th, 2008 admin Posted in ASP Comments Off


<%
On error resume next

Dim mySmartMail
Set mySmartMail = Server.CreateObject("aspSmartMail.SmartMail")
mySmartMail.Server = "mail.pakreal.com"
mySmartMail.SenderName = "Your Name"
mySmartMail.SenderAddress = "youremail@yourdomain.com"
mySmartMail.Recipients.Add "muneebsa@yahoo.com", "Muneeb Ahmad"
mySmartMail.Subject = "aspSmartMail Sample 1"
mySmartMail.Body = "This mail has been sent with aspSmartMail."
mySmartMail.SendMail
if Err.Number<>0 then
	Response.write "Error: " & Err.description
else
	Response.write "An e-mail has just been sent to " & mySmartMail.Recipients.Item(1).Name & "."
end if
%>
AddThis Social Bookmark Button

Similar Posts