How to consume an ASP.NET webpage in JavaScript?

Ever wondered how you can use your .net page to render output in javascript, something similar to Google Ads (Adsense)? What you want to do is have an ASP.NET page which does a bit of logic coded in C#VB.NET which other people can consume on their websites through a simple javascript call to your asp.net page. The solution is really easy – all you have to do is create your webpage as normal and stick your business logic inside it and then for the things your want to output, you use:

// BusinessLogicPage.aspx

string message = “This is the output from my ASP.NET page!”;

Response.Write(“document.write(‘” + message + “‘);”;

Response.End();

// ConsumerPage.html (it can be anything because we are going to consume it in javascript

<script src=”BusinessLogicPage.aspx” type=”text/javascript”></script>

Where you place the script tag, you will get the output from your BusinessLogicPage just like when you place Adsense codes on your pages, Google delivers ads to these pages.

Problem with IFrame in a table

You must be wondering why would someone need an iframe within a table, right? Well, i had to consume an rss feeds within a Classic ASP application and the VB6 codes were not doing the job because the MSXML parser found errors in the XML document. Doing it in C# (asp.net) had no problems at all and because i had already waster more than 1 day trying all the different solutions i’ve googled, i thought it would be best to load the rss feeds in an iframe within the classic asp codes as you cannot import aspx pages in a classic asp page. To add to the fun, the iframe would need to sit within a table and the moment i tried sticking the iframe in, all the other data in the table data (td) dissappeared. The solution was really simple, the browser (internet explorer) did not like the self-closing tag, so you need to explicitly have a closing tag.

<iframe src=”bla.aspx” frameborder=”no” /> (did not work)

<iframe src=”bla.aspx” frameborder=”no”></iframe> (works like a charm)

There you go! Saved for future reference 🙂

Creating bookmarks with anchor tags

There are times when you need to create bookmarks within your webpage. A bookmark allows you to jump from one section of your webpage to another and is especially useful if you have a webpage which is long enough to make you scroll a lot. In these situations, you are better off creating bookmarks throughout the webpage so that don’t need to scroll all the way down to find a particular subject of interest. The bookmark takes the form of an anchor tag as follows:

<a name=”myBookmark”>I am bookmarking this line</a>

And somewhere else on my webpage i call call it through this:

<a href=”#myBookmark”>Go to bookmark</a>

Just for reference!

Working with Excel and C#

I had the task of building a small app to re-order the tabs in a spreadsheet and get rid of those which are unnessary. However doing this in C# is surprisingly difficult mainly because the Microsoft.Office.Interop.Excel was intended to work primarily with VB/ VBA but was customised to work with C# as well. The task was really simple in terms of functionality as it would need to read an xml file which contained the required worksheets (tabs) in the order which we want them, so the app would need to iterate through that list and copy the specific worksheet to another workbook and save it. Unfortunately i ran into many problems in getting this to work, such as the ‘missing’ value needed to be substituted for (Type.Missing), the worksheet couldn’t be copied, it was difficult to add a new worksheet to the new workbook, the workbook would have 3 empty worksheets by default and you couldn’t delete them all at the beginning because a workbook needs to have at least one worksheet etc. Here are the codes i ended up doing:


using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Xml;
 using System.Configuration;

// import the excel library
 using Microsoft.Office.Interop.Excel;

namespace Tam.Spreadsheet
 {
 public class Process
 {
 public delegate void OnFinishProcessingHandler(string message);
 public static event OnFinishProcessingHandler OnFinishProcessing;

public static void Start()
 {
 // This is going to be the message that we are going to build up as we go along and convey to the user
 StringBuilder message = new StringBuilder();

// start a new excel application
 Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

try
 {
 // load the funds document
 XmlDocument fundsData = new XmlDocument();
 fundsData.Load(ConfigurationManager.AppSettings["funds"]);

// store the fund codes (tabs) in the order they are presented in the xml file
 List<string> funds = new List<string>();
 XmlNode root = fundsData.DocumentElement;
 XmlNodeList allFunds = root.SelectNodes("//funds/fund");

message.Append("Reading xml file...\r\n");

foreach (XmlNode fund in allFunds)
 {
 funds.Add(fund.Attributes["code"].Value);
 }

xlsApp.DisplayAlerts = false; // please do not bother with the alerts!
 xlsApp.Visible = false; // no need to open the excel program visually (ie on the screen)
 xlsApp.SheetsInNewWorkbook = 1; // set the number of sheets to 1 (default is 3)

if (xlsApp != null)
 {
 message.Append("Processing excel file...\r\n");

// create a new workbook to work with...
 Workbook newWorkbook = xlsApp.Workbooks.Add(Type.Missing); // (XlWBATemplate.xlWBATWorksheet)

// the original workbook
 Workbook originalWorkbook = xlsApp.Workbooks.Open(ConfigurationManager.AppSettings["filename"],
 0,
 false,
 5,
 "",
 "",
 false,
 Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
 "",
 true,
 false,
 0,
 true,
 false,
 false);

// We'll need a count for the worksheets
 int count = 0;

// which workbooks do we want?
 foreach (string sheetName in funds)
 {
 count++;

// do we have the required sheet
 bool IsSheetAvailable = false;

foreach (Worksheet ws in originalWorkbook.Worksheets)
 {
 if (ws.Name.Trim().ToLower() == sheetName.Trim().ToLower())
 {
 // Yupie, the sheet is available for copy!
 IsSheetAvailable = true;

ws.Copy(newWorkbook.Worksheets[count], Type.Missing);

// no need to search any further for this sheet
 break;
 }
 }

if (!IsSheetAvailable)
 {
 // the worksheet couldn't be found, but we still need to create a tab for it
 // with the actual name of the tab and the word 'missing' prepended to it
 message.Append("Missing Worksheet : " + sheetName + "\r\n");

// add a blank worksheet to the workbook
 // Note: we are making a copy of the last worksheet (which is blank) to the workbook
 Worksheet newSheet = new Worksheet();
 newSheet = (Worksheet)newWorkbook.Worksheets[newWorkbook.Worksheets.Count];
 newSheet.Copy(newWorkbook.Worksheets[count], Type.Missing);

// Now we need to rename the worksheet to the actual name (as the name would be called 'Sheet1 (2)' by default)
 Worksheet currentSheet = new Worksheet();
 currentSheet = (Worksheet)newWorkbook.Worksheets[count];
 currentSheet.Name = "Missing fund " + sheetName;
 }
 }

// Since a workbook needs to have at least one worksheet as a rule of thumb and we have now added
 // all the sheets we are interested in, we need to get rid of the default sheet which was created for us
 // and this sheet would be the last one as we have been adding sheets to the beginning of the workbook
 Worksheet unwantedSheet = new Worksheet();
 unwantedSheet = (Worksheet)newWorkbook.Worksheets[newWorkbook.Worksheets.Count];
 unwantedSheet.Delete();

message.Append("Saving new excel file...\r\n");

// save the new excel file now...
 newWorkbook.SaveAs(ConfigurationManager.AppSettings["newFilename"],
 Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet,
 Type.Missing,
 Type.Missing,
 false,
 false,
 Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
 Type.Missing,
 Type.Missing,
 Type.Missing,
 Type.Missing,
 Type.Missing);

// close the workbook
 xlsApp.Workbooks.Close();

// exit the excel application
 xlsApp.Quit();

message.Append("Successfully processed excel file...\r\n");
 }
 else
 {
 message.Append("Please check that Microsoft Excel is installed on this machine. Aborting processing...");
 }

message.Append("*** Finished ***");

}
 catch (Exception ex)
 {
 message.Append("ERROR: " + ex.ToString());

// exit the excel application
 xlsApp.Quit();
 }

if (OnFinishProcessing != null)
 {
 OnFinishProcessing(message.ToString());
 }
 //return message.ToString();
 }
 }
 }

Cross threading problem with updating UI in WinForms

While trying to make a Windows application more responsive, i ended up cross threading, that is, i had one thread starting my application and another thread performing the work but trying to update the UI (a textbox) after the processing was done.

The solution is to call the Invoke method on the UI control as follows:

public delegate void UpdateTextboxHandler(string message);

private void UpdateTextbox(string message)
{
textBox1.Text += message;
}

private void Process_OnFinishProcessing(string message)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new UpdateTextboxHandler(UpdateTextbox), message);
}
else
{
textBox1.Text += message;
}
}

More information can be found on Multithreading with Windows Forms

Problem installing Sql Server 2005 on Vista Home Premium

So i decided to get Vista to take advantage of IIS 7 and i anticipated a few problems to get all my Windows XP programs to work properly, but i thought it would need maybe some Service Packs and i should get it all working. However when i tried to install Sql Server 2005 on Vista, the setup wizard warned me of two problems (one compatibility with this new version of windows and second the IIS thingy). I didn’t care because at the end of the day, all i want is a database for me to use for my web apps.

Having said this, i was trying to instal SQL Server 2005 Developer edition on Vista and although i had previously installed Visual Studio 2008 which would have installed SQL Server Express, i thought it would not cause any problems but after the installation i couldn’t find SQL Server Management Studio and all that was listed under SQL Server 2005 was the configuration tools. If you run into the same problem, you will need to go to uninstall programs in Control Panel and choose to uninstall workstation components ONLY. Then run the setup of SQL Server again and remember to go to advanced to select the workstation components and it will install it properly for you. The problem is that Vista does not realise that the workstation components (including SQL Server Management Studio) is an upgrade to the SQL Server Express and it therefore discards it during setup. Follow this link for more information.

How to get rid a small bump on eyelid?

Small bumps on the eyelid are normally styes. A stye is like a pimple that can appear red and swollen and it is basically an inflamed oil gland on the edge of your eyelid. It is caused by bacteria on the skin that get into the hair follicle of the eyelash.

To get rid of the stye (small eye bump), apply warm compresses for 10 mins, 4 times a day. The stye should disappear within 2 days.

To avoid styes always wash your hands thoroughly before touching the skin around your eye!