Archive

Archive for 2006

Firing an onchange event from a HTMLSelectElement

Something I just solved, which alot of people seemed to be stuggling with, is the ability to fire the onchange method of a select
box programatically from .NET (in this case VB.NET)
 
Basically the problem is, if you have a drop down list, stored in a HTMLSelectElement, and you set the selectedIndex propery, the onchange event doesn’t automatically get called. – the same happens in Javascript – but you can’t call onchange() like in Javascript, since it’s a property, not a method.
 
Solution
 
hse.FireEvent("onchange", hse.onchange)
 
where hse is the HTMLSelectelement
 
 
Categories: Uncategorized

Javascript redirect after images have loaded

This is a handy piece of javascript that can be used to execute a redirect only after all images have loaded on a page, up to a maximum of 10 seconds. I put in this maximum threshold, to account for the possibility of a bad link on the page, or a user with images turned off on their browser.

waitForImages();
var imageLoadTimeout = 10; // max 10 seconds;
var timeWaited = 0;
function waitForImages()

 var AllLoaded=true;
 if (timeWaited>imageLoadTimeout)
 {
  // redirect after 10 seconds, regardless of whether images are loaded.
  ImagesLoaded();
  return;
 } 
 for(i=0;i<document.images.length;i++)
 {
  var image = document.images[i];   
  if (!image.complete && image.name != "brokenImage" )
  {
  
   AllLoaded=false;
   break;
  }
 }  
 if (AllLoaded)
 {
  ImagesLoaded();
 }
 else
 {
  timeWaited += 0.5;
  setTimeout(‘waitForImages()’,500);
 }
}

function ImagesLoaded()
{
 RedirectPage();
}

Categories: Uncategorized

Useful c# function – remove duplicates

This is a useful c# function, that removes duplicates from an arraylist
 

public ArrayList RemoveDups(ArrayList items)

{

ArrayList noDups = new ArrayList();

foreach(string strItem in items)

{

if (!noDups.Contains(strItem.Trim()))

{

noDups.Add(strItem.Trim());

}

}

noDups.Sort();

return noDups;

}

 

Handy!

Categories: Uncategorized

del.icio.us auto-post

This is a bit of code I wrote that will automatically post a website to delicious.  The HttpRequest Class is outside of the scope of this post, but you should get the jist of how it’s done.
 

private void SubmitDelicious(string url,string description,string username,string password,string tags)

{

#region

postdata

/*

POST /login HTTP/1.1

Host: secure.del.icio.us

user_name=nora344

password=lokiju

jump=no

url=http%3A%2F%2Fwww.envoyez.com

login=log+in

GET /nora344?url=http%3A%2F%2Fwww.envoyez.com

jump=no

POST /nora344?636480 HTTP/1.1

Host: del.icio.us

url=http%3A%2F%2Fwww.envoyez.com

oldurl=http%3A%2F%2Fwww.envoyez.com

description=envoyez+sms

notes=

tags=

jump=no

key=6c7b3c42b196c8e3ebc90130317786eb

*/

#endregion

// step 1. login

string strUrl = "https://secure.del.icio.us/login&quot;;

string strPostdata = "user_name=" + username + "&";

strPostdata += "password=" + password + "&";

strPostdata += "jump=no&";

strPostdata += "url=" + HttpUtility.UrlEncode(url) + "&";

strPostdata += "login=log+in&";

HTTPRequest hrWeb =

new HTTPRequest();

hrWeb.blnExpect100Continue = false;

string html = hrWeb.Request(strUrl,"POST",strPostdata);

// at this point, we may need to transfer cookies from secure.delicious to delicious?

CookieCollection ckCol = hrWeb.RequestCookies.GetCookies(

new Uri("https://secure.del.icio.us&quot;));

 

Cookie ckAccept = new Cookie("_accept_s_cookies","1","/",".icio.us");

Cookie ckInstall =

new Cookie("_ext_install_redir","1","/",".icio.us");

Cookie ckRegister =

new Cookie("_register_id","1248967165","/",".icio.us"); // _register_id?

Cookie ckUser =

new Cookie("_user",ckCol["_user"].Value,"/",".icio.us");

Cookie ckBM = new Cookie("_bm_url",HttpUtility.UrlEncode(url),"/",".icio.us");

// BX=4ehl0pt2i6vse&b=3&s=dr – already set

hrWeb.RequestCookies.Add(ckAccept);

hrWeb.RequestCookies.Add(ckInstall);

hrWeb.RequestCookies.Add(ckRegister);

hrWeb.RequestCookies.Add(ckUser);

hrWeb.RequestCookies.Add(ckBM);

// step 2. redirect

strUrl = "http://del.icio.us/&quot;;

strUrl += username;

strUrl += "?url=" + HttpUtility.UrlEncode(url) + "&jump=no";

html = hrWeb.Request(strUrl);

if (html.IndexOf("in order to save an item, you have to log in")!=-1)

{

return;

}

string strIDRegex = @"action…w+?(?<ID>d+)";

string strID = Regex.Match(html,strIDRegex).Groups["ID"].Value;

string strKeyRegex = @"key..value..(?<KEY>w+)";

string strKey = Regex.Match(html,strKeyRegex).Groups["KEY"].Value;

// step 3. post

strUrl = "http://del.icio.us/&quot; + username + "?" + strID;

strPostdata = "url=" + HttpUtility.UrlEncode(url) + "&";

strPostdata += "oldurl=" + HttpUtility.UrlEncode(url) + "&";

strPostdata += "description=" + HttpUtility.UrlEncode(description) + "&";

strPostdata += "notes=&";

strPostdata += "tags=" + HttpUtility.UrlEncode(tags) + "&";

strPostdata += "jump=no&";

strPostdata += "key=" + strKey;

html = hrWeb.Request(strUrl,"POST",strPostdata);

}

 

Categories: Uncategorized

Java Midlet for .NET web services

Ever wonder how they make Java games for mobile phones, and ever wondered how to make something more useful on them than a Game. I was curious, and thought about writing an app that can use a webservice from a mobile phone (mine’s a Sanyo S750i). To dispell the myth that networking from phones is expensive. I checked my credit before and using this code, and it only cost me 2p. No Lie!.
 
To cut to the chase, you can download the source code from http://www.freebiesms.com/javasms.zip and the JAD file (for a mobile phone) at http://www.freebiesms.com/sms.jad
 
First off, you’ll need to download the Java Micro Edition (v5), get the bundle with the NetBeans IDE. You’ll also need to download the Netbeans mobility pack v5. This makes it easy to develop mobile applications (although the GUI designer is rubbish).
 
– ok cut short. need to go to work. Check out the code to see how I did it! 🙂
 
Categories: Uncategorized

Visitor Tracker in ASP.NET

Visitor trackers aren’t new, and even novice HTML coders can place a free tracker in their webpage, but there comes a point when
you outgrow what’s available free, and you really need to get hold of the raw data behind your tracker.
 
Recording data for every visitor to the site may be out of the question, as you end up filling your database with too much archival data. Generally a tracker will keep detailed information about the last day’s traffic, then aggregated information for archival material. For example, it might be of interest to view which websites the last 20 visitors came from, but just a count of how many people came to the site last march might be sufficient.
 
I therefore created two tables in my database, RecentVisitors and AggregatedVisitors. With a trigger set up between the two, to automatically populate the AggregatedVisitors table based on new inserts into the RecentVisitors table, thus:
 
CREATE TRIGGER trigger_RecentVisitors
ON RecentVisitors
FOR INSERT
AS
BEGIN
 — note this will track hits not unique visitors.
 declare @websiteID int
 select top 1 @websiteID = websiteid from inserted  
 declare @VisitorsToday int
 select @VisitorsToday = count(*) from RecentVisitors  
 where dateDiff(day,Date,getdate())=0
 and websiteId=@websiteID
  
 delete from AggregatedVisitors where
 websiteID = @websiteID
 and
 Datediff(day,date,getDate())=0
 insert into AggregatedVisitors (Number,websiteID)
 values (@VisitorsToday,@websiteID)
 
 delete from recentVisitors where dateDiff(day,Date,getdate())>1
 
END
 
 
I then, put together some javascript to load a hidden image, which would execute an insert into RecentVisitors
 
<img name="Tracker" style="display:none">
 <script language="javascript">
 var WebsiteID = 1;
 var Tracker = window.document.images["Tracker"];
 Tracker.src = "default.aspx?WebsiteId=" + WebsiteID + "&Referrer=" + escape(document.referrer);
 </script>
 
To return a 1px x 1px image from asp.net is really easy, and combined with an insert into the database, I came up with:
 

if (Session["FirstTime"]==null)
{
   string strReferrer = Request.QueryString["Referrer"].ToString();
  
int intWebsiteID = Convert.ToInt32(Request.QueryString["WebsiteID"]);
  
string strSQL = "insert into RecentVisitors (IP,Referrer,websiteId) values (";
   strSQL += "’" + Request.ServerVariables["REMOTE_ADDR"] + "’,";
   strSQL += "’" + strReferrer.Replace("’","”") + "’,";
   strSQL += intWebsiteID + ")";
  
base.ExecuteNonQuery(strSQL);
   Session["FirstTime"]=
false;
}
Bitmap bmpCanvas =
new Bitmap(1,1);
Response.ContentType = "image/gif";
bmpCanvas.Save(Response.OutputStream,ImageFormat.Gif);

ExcecuteNonQuery is a function I wrote to run a statement against the database, and is outside the scope of this blog.

Then, to view this data in a meaningful way, I created a page with two dataGrids, dgRecentVisitors and dgAggregatedVisitors, which used the following SQL to display their results:

select top 20 rv.id,referrer,date from recentvisitors rv
join websites w on w.id = rv.websiteid
where charindex(w.websiteaddress,rv.referrer)=0
order by date desc

and

select * from aggregatedVisitors order by date desc.

and, that suffices for a tracker for my purposes, and I have access to the raw data, should I need to run queries to work out sales conversion rates etc. The only downfall is that it does not correctly measure visitors rather than hits, but that’s work for another day.

Njoy.

 

 

 
 
 
 
 
Categories: Uncategorized

Reconnecting ADSL programatically

I had an issue that my ADSL connection kept disconnecting every few hours, which meant that I manually had to go and open
the local web interface to my ADSL modem (Binatone), and press connect.
 
I figured out how to do this from code, by making a GET request to the following URL, my ADSL was reconnected.
 

http://192.168.1.2/doc/loginout.htm?

WINDWEB_URL = %2Fdoc%2Floginout.htm&

simple_ppp_username = xxxx&

simple_ppp_pwd = xxxx&

wanAdapterSelection = 0&

wan_encapsulation = 0&

wan_VPI = 0&

wan_VCI = 38&

PPP_connection_number = 1&

New_PPP_Action = 0

 

Categories: Uncategorized

VPN option greyed out in Windows XP

When setting up a VPN connection on Windows XP Pro, I found the VPN option greyed out.
 
Searching on the net, people said that the Remote Access Connection Manager service wasn’t running, however when you try to start this, you get an Access Denied error, and a "cannot allocate buffers" errror in the event log.
 
This is actually due to a registry corruption,
To fix it, go to HKL:MSystemCurrentControlSetRasmanPPPEAP then delete subkeys EXCEPT 13 & 4. Then reboot the pc.
 
Categories: Uncategorized

Parser Error Message: Access is denied

This is one of those horrible asp.net error messages, when for no reason, you update some code with new code and you get an access is denied error.(*)
 
There are some sensible suggestions listed on msdn as to why this happens, and how it’s all down to indexer service – although, when you already have this service disabled, you’d wonder what’s up?
 
Basically, I went through these steps
Kill the asp_wp process
stop w3svc service
delete the bin folder
restart w3svc service, and go to offending page
stop the w3svc service
replace the bin folder with old files
restart the w3svc service.
 
It makes little sense why this works, but it worked for me.
 
 
(*) the specifics of the error (if you do view|Source) are
[FileLoadException]: Access is denied: ‘erc’.
   at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Boolean isStringized, Evidence assemblySecurity, Boolean throwOnFileNotFound, Assembly locationHint, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Boolean stringized, Evidence assemblySecurity, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.Load(String assemblyString)
   at System.Web.UI.CompilationConfiguration.LoadAssemblies(Hashtable original)
[ConfigurationException]: Access is denied: ‘erc’. (c:winntmicrosoft.netframeworkv1.1.4322Configmachine.config line 258)
   at System.Web.UI.CompilationConfiguration.LoadAssemblies(Hashtable original)
   at System.Web.UI.TemplateParser.AppendConfigAssemblies()
   at System.Web.UI.TemplateParser.PrepareParse()
   at System.Web.UI.TemplateParser.Parse()
   at System.Web.UI.TemplateParser.GetParserCacheItemThroughCompilation()
   at System.Web.UI.TemplateParser.GetParserCacheItemInternal(Boolean fCreateIfNotFound)
   at System.Web.UI.TemplateParser.GetParserCacheItemWithNewConfigPath()
   at System.Web.UI.TemplateParser.GetParserCacheItem()
   at System.Web.UI.ApplicationFileParser.GetCompiledApplicationType(String inputFile, HttpContext context, ApplicationFileParser& parser)
   at System.Web.HttpApplicationFactory.CompileApplication(HttpContext context)
   at System.Web.HttpApplicationFactory.Init(HttpContext context)
   at System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context)
   at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
Categories: Uncategorized

Using DBCC to create fair performance tests on stored procedures

When tweaking stored procedures, to make them run faster, we often compare them against a benchmark,
say SP_A vs SP_B.
 
However, if SP_A has been used actively, as part of a running system (i.e. website). it will be optimized by SQL server and will be placed in the procedural cache. This then results in Biased tests between SP_A and SP_B.
 
Therefore I would recommend using
DBCC FREEPROCCACHE
and
DBCC DROPCLEANBUFFERS
 
before timing the execution of SP_A against SP_B. Although, the affect of clearing the cache will cause them both to run slower, it will highlight performance gains of one against the other fairly.
 
 
 
Categories: Uncategorized