Archive

Archive for the ‘Uncategorized’ Category

Unzipping GZIP files on the fly (C#)

I recently set about writing some code to download a file named pf[1].csv.gz – which was GZIP’ed and creating the corresponding CSV file on disk. Using the ICSharpCode Zip compression library, I used this code:

string strCSVFile = "c:\pf[1].csv";
string strUrl = "http://www.someurl.com/pf[1].csv.gz";
WebClient wc =
new WebClient();
Byte[] bZip = wc.DownloadData(strUrl);
MemoryStream msZip =
new MemoryStream(bZip);
GZipInputStream gzisZip =
new GZipInputStream(msZip);
FileStream fsOutput =
new FileStream(strCSVFile,FileMode.Create);
Byte[] bCSV =
new Byte[Byte.MaxValue];
Int32 iReadCount = Byte.MaxValue;
while(iReadCount>0)
{
   iReadCount = gzisZip.Read(bCSV,0,iReadCount);
   fsOutput.Write(bCSV,0,iReadCount);
}
fsOutput.Close();
gzisZip.Close();

Categories: Uncategorized

Printer friendly CSS

A tip I just learned this morning, if you need a website to appear different when it prints, you can add a CSS style that is only applied during printing. – For instance, if you wanted to strip off menus, or remove certain graphics, you could use display:none in the printer css style.

The trick to it is to use this format to include your CSS

<style type="text/css" media="screen">@import "screen.css";</style>
<style type="text/css" media="print">@import "print.css";</style>

On a personal note, I just noticed that one of my domains has either not been listed or removed from google http://www.listofestateagents.info, which was a bit of a pity. For some reason over the last week my Page impressions have gone down, but my CTR has gone up. Net result being that revenue took a hit. But I guess that means that at least google is targeting my pages better.

 

Categories: Uncategorized

ASP.NET chatroom with out of band calls.

Chatrooms are typically developed in Flash or java, since they both contain the facility to make HTTP requests to the server from which the Applet / SWF was downloaded from. An ActiveX control named Microsoft.XMLHTTP also has the same capability, and is capable of running on browsers with default security settings (I believe it may be marked ‘safe for scripting’). I also believe that it is compatible with FireFox, and IE7 are relaxing security for this specific control.

So, I decided to put together a simple chatroom example in asp.net using this technology. Based on an excellent example by Dino Esposito.

Starting off with a simple html form thus:

<form runat="server">
   <h1>Demonstrate Simple chatroom with Out-of-band Calls</h1>
   <hr>
   Message: <input type="text" name="txtMessage">
   <Button Runat="server" ID="ButtonGo">Send & Receive</Button>
   <hr>
   <span ID="Msg" />
  </form>

and some associated javascript:

<SCRIPT language="javascript">
    setTimeout("Callback(”)",2000);
 function DoCallback(url, params)
    {
  var pageUrl = url + "?callback=true&param=" + params;
  var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
  xmlRequest.open("POST", pageUrl, false);
        xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlRequest.send(null);
        return xmlRequest;
    }
   
    function Callback(message)
    {
  var xmlRequest = DoCallback("callback.aspx", message);  
  Msg.innerHTML = xmlRequest.responseText;
     if (message==”) setTimeout("Callback(”)",2000);
    }
</SCRIPT>

As we can see, a post request is sent back to callback.aspx, which handles the request thus:

<script runat="server">
private void Page_Load(object sender, EventArgs e)
{
 if (Request.QueryString["callback"] != null)
 {
  string param = Request.QueryString["param"].ToString();
  Response.Write(RaiseCallbackEvent(param));
  Response.Flush();
  Response.End();  
 }
 else
 {
  string callbackRef = "Callback(document.all[‘txtMessage’].value)";
  ButtonGo.Attributes["onclick"] = callbackRef;
 }
}

 string RaiseCallbackEvent(string eventArgument)
 {
  if (eventArgument!="")
  {
   Application["conversation"] += eventArgument + "<br>";
  }
  return Application["conversation"].ToString();
 }
 
</script>

Pretty simple. To check out a demo see www.globefinder.info/callback.aspx

 

 

 

Categories: Uncategorized

MSysObjects SQL injection attack

A colleague of mine recently had his website hacked with a sql injection attack, with a url something like http://www.someurl.com/somepage.asp?
id=153%20union%20%20select%201,2,3,4,fldusername,
6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,fldpassword,
fldpassword,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,
39,40,41,42,43,44,45,46,47,48%20from%20tbluser%27

hense exposing all the usernames and passwords on the page. it lead me to think, how did the hacker guess the column names? – I knew about the sysobjects table in sql server, but being a classic ASP page, it would undoubtedly have an Access back end. Then I spotted the following hidden tables in access:

    MSysObjects
    MSysACEs
    MSysQueries
    MSysRelationships
    MSysAccessObjects
    MSysAccessXML
    MSysDb

    Which you can query to obtain the database schema. All I can say is . NEVER EVER BUILD SQL STATEMENTS DIRECTLY WITH USER PROVIDED TEXT (without calling Replace("’","”") at least!

Categories: Uncategorized

Error in OleAut32.Dll Offset 4c47

AppName: vb6.exe AppVer: 6.0.97.82 ModName: oleaut32.dll

 

ModVer: 5.1.2600.2180 Offset: 00004c47

 

Unhandled exception at 0x77124c47 in VB6.EXE: 0xC0000005: Access violation reading location 0x80020000.

 

77124C47 mov eax,dword ptr [eax-4]

 

This is a lovely error that crashes VB6 if you make a little typo, and here’s how to fix it:

 

If you make write code like this

 

 Dim rsProduct As New ADODB.Recordset

 sql = " select *  from orderlines "

 rsOrderLines.Open sql, DSN

 Do While Not rsProduct

  ‘ process rsProduct

  rsOrderLines.MoveNext

 Loop

 

The application will compile, But, note that I have accidentaly ommitted the ".EOF" in the while loop. This causes VB6 to crash with the above error. To Fix it, use the EOF.

 

Categories: Uncategorized

Microsoft.VisualStudio.Shell.Interop.IVsRuningDocumentTable2

After installing Visual Studio 2005 beta 2 on a machine that previously had a copy of VS 2005 Beta 1, I got an error when trying to open the windows forms designer –

visual studio settings and project designers package has failed to load properly

Could not load type Microsoft.VisualStudio.Shell.Interop.IVsRuningDocumentTable2
from Assembly Microsoft.VisualStudio.Shell.Interop.8.0

To fix this, I spotted that in the GAC (C:windowsAssembly) there were two versions of Microsoft.VisualStudio.Shell.Interop.8.0, I uninstalled the older version, restart visual studio and it worked. Apparently the same problem occurs with the ASP.NET web page designer with Microsoft.VisualStudio.Shell.Interop.SVsSmartOpenScope.

There are a number of similar DLL’s in the GAC with identical names and version numbers – such as Microsoft.VisualStudio.TextManager.Interop.8.0 (which causes a bug with Microsoft.VisualStudio.TextManager.Interop.IVsQueryUndoUnit) and Debugger.interop.8.0

On a personal note, I just noticed that one of my websites, www.buymusic.cd just reached a Google PR 5.

 

 

Categories: Uncategorized

Url rewriting

If you have a large website that you need to be google indexable (Googlable if I may coin a new phrase). Then it is worthwhile converting standard links such as myPage.asp?x=1&y=2 to someting like /web/x/1/y/2/myPage.asp where the "folder structure" translated back to a standard querystring before it is processed.

You can do this though .NET by writing a class that implements IHttpModule, however for added performance you should use an ISAPI filter. My personal favourite is UrlReWrite by Smalig software.

The only catch with using url-rewrites the new ‘virtual’ folder structure can lead to a heap of bad links. In this case you have to use <base href> to correct this.

I used it on three new sites www.listofdevelopers.info www.listofEstateAgents.info and www.listofschools.info

Categories: Uncategorized

Generating thumbnails in ASP.NET

Hi,

I found just developed a nice new function for uploading images from a website, and generating thumbnails on the fly

 public string storeFile(HttpPostedFile postedFile)
 {
   string strFilename="";
   string strPath = "c:\wherever\";
   if( postedFile.FileName != "" )
   {
 HttpPostedFile hpfFile = postedFile;
    int nFileLen = hpfFile.ContentLength;
 byte[] bData = new byte[nFileLen];
 hpfFile.InputStream.Read(bData, 0, nFileLen);
    strFilename = Path.GetFileName(hpfFile.FileName);
 FileStream fsFullImage = new FileStream(strPath + strFilename , FileMode.Create);
 fsFullImage.Write(bData, 0, bData.Length);
 fsFullImage.Close();
    System.Drawing.Image  iPhoto;
 System.Drawing.Image  iThumbnail;
    iPhoto = System.Drawing.Image.FromFile(strPath + strFilename);
   iThumbnail = iPhoto.GetThumbnailImage(100, 100, null, IntPtr.Zero);
 FileStream fsThumbnailImage = new FileStream(strPath + "tn" + strFilename , FileMode.Create);
 iThumbnail.Save(fsThumbnailImage, ImageFormat.Gif);
 fsThumbnailImage.Close();
   }
   return strFilename;
 }

This is then called in a asp.net page with

string strFilename = storeFile(Photo.PostedFile);

Where Photo is a name of a file input box such as:

<input type=file name="Photo" id="Photo" runat="server">

You also have to add the following – enctype="multipart/form-data" to your form, and ensure you have write permissions on the destination folder.

 

Categories: Uncategorized

Browser Helper Objects C#

Can anybody help tell my why this code isn’t working. Its a Browser Helper Object for Internet Explorer, Simply designed to Write the Current Time at the bottom of each page. It compiles ok, and it registers as a COM object with regasm ok, and I put its GUID in the correct place in the registry (under Explorer/Browser Helper Objects). I can’t even get VS.NET to attach to the IEXPLORE process.

using System;

using

SHDocVw;

using

mshtml;

namespace BrowserHelperObject

{

using System;

using System.Runtime.InteropServices;

[ComVisible(true),

InterfaceType(ComInterfaceType.InterfaceIsIUnknown),

Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]

public interface IObjectWithSite

{

void SetSite ([MarshalAs(UnmanagedType.IUnknown)]object site);

void GetSite (ref Guid guid, out object ppvSite);

}

/// <summary>

/// Summary description for CustomBrowserHelperObject

/// </summary>

[ComVisible(

true),

ClassInterface(ClassInterfaceType.None),

Guid("9E6F3590-52D0-406d-A7ED-DAE87BED989F")]

public class CustomBrowserHelperObject : IObjectWithSite

{

const int E_FAIL = unchecked((int)0x80004005);

const int E_NOINTERFACE = unchecked((int)0x80004002);

private IWebBrowser2 iwb2InternetExplorer;

public void SetSite ([MarshalAs(UnmanagedType.IUnknown)]object site)

{

iwb2InternetExplorer = (IWebBrowser2)site;

if (iwb2InternetExplorer != null)

{

WebBrowser wbInternetExplorer = (WebBrowser)iwb2InternetExplorer;

wbInternetExplorer.DocumentComplete +=

new DWebBrowserEvents2_DocumentCompleteEventHandler(

this.OnDocumentComplete);

}

}

public void GetSite (ref Guid guid, out object ppvSite)

{

ppvSite=

null;

if (iwb2InternetExplorer != null)

{

IntPtr ipSite = IntPtr.Zero;

IntPtr ipUnknown = Marshal.GetIUnknownForObject(iwb2InternetExplorer);

Marshal.QueryInterface(ipUnknown, ref guid, out ipSite);

Marshal.Release(ipUnknown);

Marshal.Release(ipUnknown);

if (!ipSite.Equals(IntPtr.Zero))

{

ppvSite = ipSite;

}

else

{

Release();

Marshal.ThrowExceptionForHR(E_NOINTERFACE);

}

}

else

{

Release();

Marshal.ThrowExceptionForHR(E_FAIL);

}

}

private void OnDocumentComplete (object frame, ref object urlObj)

{

HTMLDocument hDoc = (HTMLDocument)iwb2InternetExplorer.Document;

hDoc.body.innerHTML = hDoc.body.innerHTML + "<hr><br>Page viewed at " + DateTime.Now;

}

protected void Release()

{

if (iwb2InternetExplorer != null)

{

Marshal.ReleaseComObject(iwb2InternetExplorer);

iwb2InternetExplorer = null;

}

}

}

}

Categories: Uncategorized

“Send to a Friend” Menu extension for Internet Explorer

I recently was using the Full Source utility by ThunderMain, and I was curious to see if I could make my own context menu for Internet Explorer. A useful utility I thought of using was a "send to a friend" utility.

I created the following registry key

HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMenuExtSend to a friend

and set the default value to

c:windowswebsendToAFriend.html

Which contains the following

<script language="JavaScript">
window.open("http://www.pop3webmail.info/reply.aspx?url=" + external.menuArguments.document.URL);
</script>

From the page on www.pop3webmail.info, it automatically fills in a message saying "Please Visit: (whatever url)"

 

Categories: Uncategorized