Friday, 1 March 2013

Dynamically loading HTML from another page using Javascript

And here's another great JQuery feature. If you want to include content from another html page you can use JQuery to drag it in. Here's a sample page with a button that pulls in and uses text from a second HTML page.
<html>
    <head>
     <script src="js/jquery-mobile/jquery-1.9.1.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            function a() {
                $('#contentFromOtherPage').load('test2.html #iphone');
            }
        </script>
    </head>
    <body>
    <div id="contentFromOtherPage">
        this text will be replaced
    </div>
    <button onclick= "javascript:a();">click</button>    
</html>
... and here's the second page where the content comes from
<html>
<head></head>
<body>
<div id="iphone">
 this is iphone content
</div>
<div id="android">
 this is android content
</div>
</body>
</html>

Thursday, 28 February 2013

Javascript : How many times was the function called

I recently ran into a problem where my Javascript was looping, and constantly calling a function.  As the browser was locking up, I found it very hard find out the cause of the issue.  To help resolve this issue I  wrote the following.

The comments explain how to use it. In short it records every entrance into a function and counts the instances and pops up an "alert" when a proc is called 50 times (the number is adjstable).


            //
            // You should  place the following lines at the top of your page
            //
            // var functionCalls = new Array();             // used to record all the calls
            // var consecutiveCallCount = 0;                // used to check for consecutive calls    
            // var lastFunctionCalled = '';                 // used to check for consecutive calls    
            // var consecutiveCallCountAlertThreshold = 50; // an alert is generated if a method is called this many times consecutively
            //
            // You should also put an empty DIV as show below, somewhere on the page. The 
            // contents of the div will be updated after every function call, and will 
            // highlight the through put of every function.  If you have a serious loop
            // this will not be updated until the consecutive threshold is reached.
            //
            // 
// // Place a call to this function at the top of every function that you want to track // e.g... // function someFoo () { // storeFunctionCalls(); // ... // // This function will count every call to the function and display it to screen. function storeFunctionCalls() { // get the name of the function that called this one var temp = arguments.callee.caller.toString(); var fName = temp.substring(temp.indexOf("function") + 8, temp.indexOf("(")) || "anoynmous"; fName = fName.replace(/^\s+|\s+$/g, ''); // loop through the existing method calls and update the count var indexOfExistingRow = -1; for (var i = 0; i < functionCalls.length; i++) { if (functionCalls[i].Name == fName) { functionCalls[i].Count++; indexOfExistingRow = i; break; } } // the method that called this has not done so before so add it into the collection if (indexOfExistingRow == -1) { functionCalls.push({ "Name": fName, "Count":1 }); } // update the onscreen display of method calls var s = ''; for (var i = 0; i < functionCalls.length; i++) { s += functionCalls[i].Name + ': ' + functionCalls[i].Count + ''; } $('#debugOutput').html(s); // checks for the consecutive calls and alert if we've passed the threshold. if (fName == lastFunctionCalled) { consecutiveCallCount++; if (consecutiveCallCount == consecutiveCallCountAlertThreshold) { alert(consecutiveCallCount + ' consecutive method calls to the same function :' + fName); } } else { lastFunctionCalled = fName; consecutiveCallCount = 0; } }

Monday, 8 August 2011

IE9 Javascript change

I ran into a problem where by a piece of positioning Javascript that worked in all browser including IE 8 did not work in IE9.  "style.top" did not work under IE9 !

The original code was this...

ele.style.top = (a - b);

I had to change it to...

ele.style.tp = (a - b).toString() + 'px';

Wednesday, 18 May 2011

Avoid Collation Issues

I had yet another query where the difference in the collation between my development database and tempdb that caused a TSQL error to be thrown.

The answer was to "collation proof" the query. It was really simple, you add the collation to be used into the query itself! below is the example.

WHERE #RawData.FullName = DiscrepancyReport.FullName COLLATE SQL_Latin1_General_CP1_CI_AS

Monday, 18 April 2011

Encoding images into HTML using C#

Here's a sample that converts a jpeg into an imline image tag...


using System;
using System.IO;
using System.Drawing;
namespace ImageToBase64
{
class Program
{
static void Main(string[] args)
{
using(System.Drawing.Image i = (Image)Bitmap.FromFile(@"c:\test\TMC_logo_2.jpg"))
{
using(MemoryStream ms = new MemoryStream())
{
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bytes = ms.ToArray();
string s = Convert.ToBase64String(bytes);
using(TextWriter tw = new StreamWriter(@"c:\test\string.txt"))
{
tw.WriteLine(string.Format(@"", s));
}
}
}
}
}
}

Friday, 11 February 2011

WatiN Samples

Accessing an HTML Table, which gives access to rows and columns

WatiN.Core.Table tbl = this.IE.Table(Find.ById("ctl00_bodyContentPlaceHolder_GridView"));

Typing into text field

this.IE.TextField(Find.ByName("ctl00$bodyContentPlaceHolder$Name")).TypeText(CompanyName);

Thursday, 1 July 2010

Anonymous Types in a RowDataBound event

Using Linq to SQL to populate a grid

protected void ConsignmentGridView_RowDataBound(object sender,GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var o = e.Row.DataItem;
Type t = o.GetType();
PropertyInfo pi = t.GetProperty("ConsignmentID");
long ConsignmentID = (long)pi.GetValue(o, null);

Thursday, 19 February 2009

Chart Control Problem

I've been banging my head againsta problem with the new Microsoft Charting control for an hour or so.

It turns out that the problem is simply that it can not be invisible!

I originally had the control in a Multiview and the View it was on was not the first view shown, you had to click a button or two and then the chart should appear by setting its view to be the active one. No luck, when it came time to display the view the "Error executing child request for ChartImg.axd" error came up.

So thinking it might be linked to the Multiview, I simply turned the chart invisible. Same problem.

But if I leave the chart on the screen at all time and simply use a style sheet to hide and show it, it works fine. So it seems that the problem is just that if the chart is first invisible ( server-side ) it will crash when you make it visible.

A bit crap really, but never mind, it's done now, phew!

Wednesday, 18 February 2009

C# Extention methods

This is a way of extending a class by adding methods to it. Heres a sample extention method class.

namespace ExtentionMethodSample
{
public static class ExtentionMethodSampleClass
{
public static Int32 myToInt32(this string s)
{
return Convert.ToInt32(s);
}
}
}


This example method adds a new method called "myToInt32" to the standard "string" class. This method will appear in intellisense.

In this case it simply allows you to convert a string to an Int32, which is a bit daft, but it could do any number of things. For instance it might return -1 if the string is empty. You can put any code into the method.

Another example is you might extend the DataRow class to return a Company object, as an alternative to creating a class that requires a DataRow in its constructor.

Another sample I've seen is where "string" was extended to give it a method to return only the numeric parts of the strings contents.

Tuesday, 17 February 2009

Returning tables from TSQL Functions

I was just blown away when I saw that you could return a table from a TSQL function. It's just something I've not seen before despite working with TSQL for years.

Heres a sample function :


CREATE FUNCTION [dbo].[FNHTest]()
RETURNS @MyTbl TABLE(ID INT NOT NULL, Keyword varchar(max))
AS
BEGIN
INSERT INTO @myTbl (ID,Keyword)
SELECT CompanyID, CompanyName FROM Company
RETURN
END


...and calling it ...

select * from dbo.FNHTest()


... I wonder if this is how Views are created and used internally by SQL?

Thursday, 15 January 2009

Creating a simple Pivot Table example

This has been driving me batty for hours. I finally managed to get one working. Here's what I did.

Firstly for this example I created a time table here's the data. As you can see it's a simple table showing year,town and an amount, this is the source data which is in a table I've called "felbrigg".

year,town,amount
1994,towcestor,1
1994,towcestor,2
1995,towcestor,4
1994,mk,8
1994,mk,16
1995,mk,32
1996,mk,64
1994,barley,128
1994,barley,256
1995,barley,512

Now here is what I'm trying to achieve.

year,towcestor,mk,barley
1994,3,24,384
1995,4,32,512
1996,NULL,64,NULL

And here is the pivot statement to do it. with line numbers to help explain

1
SELECT [year],[towcestor],[mk],[barley]
2
FROM (SELECT [year],town,amount from felbrigg) as source
3
pivot
4
(
5
sum(amount)
6
for town in ([towcestor],[mk],[barley])
7
) as pvt



1. Is the column list in the final output

2. Is the source of data, matches my source table in this example.

5. Is the calculation that is to appear in each cell of the final results

6. This specifies the column in the source that will be turned into columns in the final result, and you have to hardcode the values you want from the source column!

Thursday, 31 July 2008

Load XML doc from URL

Really easy :)

XmlTextReader rssReader;
XmlDocument rssDoc = new XmlDocument();
rssReader = new XmlTextReader(rssFeedURL);
rssDoc.Load(rssReader);

Thats it!

Friday, 18 July 2008

Writing a DataSet to a Text File


DataSet versions = new DataSet();
versions.Tables.Add(newTable);
string versionFilePath = Path.Combine(tempDir, "Versions.xml");
if(File.Exists(versionFilePath))
{
File.Delete(versionFilePath);
}
FileStream fs = new FileStream(versionFilePath, FileMode.CreateNew);
versions.WriteXml(fs,XmlWriteMode.WriteSchema);
fs.Close();
fs.Dispose();


This writes out a text file containing the data schema and the data.

Friday, 4 July 2008

Control Adapters

Had my first run it with ASP.Net control adapters this week. I was using the built in Menu control which was unfortunately rendering as a table. I needed a menu that rendered as a list using <li> tags instead.

Up to the plate stepped control adapters. These let you mess with the presentation layer of the control, in this case change a menu from rendering <Table> tags to <li>.

Here's how...

Add a App_Browsers folder to the project, you can do this from the right click menu.
Add in a "Form.browser" file. This is an XML file that tells the ASP system what class to use instead of the menus presentation layer. Here's a sample.

<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Menu" adapterType="TDWeb.MenuControlAdapter" />
</controlAdapters>
</browser>
</browsers>

The "TDWeb.MenuControlAdapter" is the Namespace and class name.


namespace TDWeb {

#region Namespace references

using System;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Adapters;


#endregion

public class MenuControlAdapter : MenuAdapter {

#region Methods

private bool MenuItemContainsSelectedItem(MenuItem menuItem) {

if ( menuItem.Selected )
return true;

foreach ( MenuItem childItem in menuItem.ChildItems ) {

if ( this.MenuItemContainsSelectedItem(childItem) ) {
return true;
}

}

return false;

}

protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);

if ( this.Control != null ) {

this.SelectCurrentPage(this.Control.Items);

}

}

protected override void RenderContents(HtmlTextWriter writer) {

if ( this.Control != null ) {

writer.AddAttribute(HtmlTextWriterAttribute.Id,"qm0");
writer.AddAttribute(HtmlTextWriterAttribute.Class,"qmmc");
writer.RenderBeginTag(HtmlTextWriterTag.Ul);
foreach ( MenuItem menuItem in this.Control.Items ) {
this.RenderMenuItem(menuItem, writer, 0, true);
}
writer.RenderEndTag();

}

}

private bool RenderMenuItem(MenuItem menuItem, HtmlTextWriter writer, int level, bool withArrows) {

bool selected = this.MenuItemContainsSelectedItem(menuItem);

if ( this.Control.StaticDisplayLevels >= level ) {

// Render each item as a
  • ...

  • //writer.RenderBeginTag(HtmlTextWriterTag.Li);
    writer.Write(@" if (menuItem.Selected)
    {
    writer.Write(@" class=""selectedmenuitem"" ");
    //writer.AddAttribute(HtmlTextWriterAttribute.Class, "selectedmenuitem");
    }
    writer.Write(@">");
    // Current item should be styled with "selected" class ...
    //if ( selected )
    // writer.AddAttribute(HtmlTextWriterAttribute.Class, @"qmparent");

    // If a description was specified, add it as a tooltip ("title" attribute) ...
    if ( menuItem.ToolTip != string.Empty )
    writer.AddAttribute(HtmlTextWriterAttribute.Title, menuItem.ToolTip);


    // Render the "href" attribute ...
    //if ( !menuItem.Selected )
    writer.AddAttribute(HtmlTextWriterAttribute.Href, menuItem.NavigateUrl);


    //writer.AddAttribute(HtmlTextWriterAttribute.Class, "selectedmenuitem");

    //// Render the "A" element ...
    //if (level == 0)
    //{
    // writer.AddAttribute(HtmlTextWriterAttribute.Class, "qmparent");
    //}
    writer.RenderBeginTag(HtmlTextWriterTag.A);
    writer.WriteEncodedText(menuItem.Text);
    writer.RenderEndTag();



    //if ( withArrows )
    // writer.WriteEncodedText(@" | ");

    // Now render any child items ...
    if ( this.Control.StaticDisplayLevels > level ) {
    if (menuItem.ChildItems.Count > 0 ) {
    writer.RenderBeginTag(HtmlTextWriterTag.Ul);
    foreach ( MenuItem childItem in menuItem.ChildItems ) {
    this.RenderMenuItem(childItem, writer, level + 1, false);
    }
    writer.RenderEndTag();
    }
    }

    // Close the
  • ...
  • tag ...
    writer.Write(@"");
    //writer.RenderEndTag();
    }

    return menuItem.Selected;

    }

    private void SelectCurrentPage(MenuItemCollection menuItems) {

    Uri rawUrl = new Uri(this.Control.Page.Request.Url, this.Control.Page.Request.RawUrl);
    this.SelectCurrentPage(menuItems, rawUrl);

    }

    private void SelectCurrentPage(MenuItemCollection menuItems, Uri rawUrl) {

    foreach ( MenuItem menuItem in menuItems ) {

    string navigateUrl = this.Control.ResolveUrl(menuItem.NavigateUrl);
    Uri targetUrl = new Uri(rawUrl, navigateUrl);
    menuItem.Selected = string.IsNullOrEmpty(menuItem.NavigateUrl = rawUrl.MakeRelativeUri(targetUrl).ToString());

    this.SelectCurrentPage(menuItem.ChildItems, rawUrl);

    }

    }

    #endregion

    }

    }

    Wednesday, 2 July 2008

    Making a Webpage look the same in Firefox and IE

    The problem : the styling works in Firefox but doesn’t in IE6.

    Here’s how to get round many of the problems. Initially build the site so that it works in Firefox. Then look at it in IE. If it looks different then add a second stylesheet that’s only read by IE.

    Example : In the below image the shaded bar should reach to the edge of the blue box. In Firefox it does reach the edge, but as shown here in IE, it does not.









    Here’s the style sheet reference that controls the width of the bar…

    .menubar
    {

    width:724px;
    text-align:left;
    clear:left;

    background-image: url(../images/menu_back.gif);

    background-repeat:repeat-x;
    font-weight:bold;
    height:25px;
    padding-left:18px;

    }


    So to get it to work in IE, add a second stylesheet and add an override to correct the problem…

    .menubar
    {

    width:742px;

    }


    Note that the IE stylesheet does not replace everything, it is simply overriding one attribute in the stylesheet.

    Next you have to add a special link to the new style sheet like this.



    <link href="Styles/P.css" rel="stylesheet" type="text/css" />>
    <!--[if gte IE 6]>
    <link href="styles/Pie6.css" rel="stylesheet" type="text/css" />
    <![endif]-->



    The second stylesheet (IE ONLY) is hidden from other Browsers by putting its link statement in the HTML comment as shown.

    Tuesday, 24 June 2008

    Creating a simple Computed Column in SQL2005

    CREATE TABLE [dbo].[CustomerType](
    [iCustomerTypeID] [int] IDENTITY(1,1) NOT NULL,
    [vcDescription] [varchar](50) NOT NULL,
    [vcMore] [varchar](50) NULL,
    [LookUpDescription] AS
    (
    vcDescription
    ) Persisted NOT NULL
    )

    In this example the LookUpDescription column mimics the contents of the vcDescription field. Could have been concatenated fields or written a case statement or pretty much anything else. These columns do not take up storeage and CAN BE INDEXED!

    So they will have a cost as far as indexing, and returning the results are concerned.