Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Thursday, March 30, 2017

Ethereum Development - Meetup in Perth

I’m really looking forward to giving a presentation on Smart Contracts to a Perth Meetup Group on the 8th of April. I’ve put together instructions on how to setup your environment on GitHub.

Thursday, January 12, 2017

Some more Ruby

Trying out Ruby code again today for no specific reason other than to try out some different languages. Expanding on the previous example I decided to allow edge detection for multi-row matrix. This time we look for changes to the matrix with the left character and the row above.

Some comments on the syntax

- I found the for loop syntax a little weird “…” does not seem very intuitive.
- Reading from standard Input was really simple and felt good.
- Some of the syntax like ‘gsub’, ‘def’ (instead of 'function') would take a little getting used too, but Stack Overflow was a big help with that.
- RegEx was never my favourite technology, but Rubular website was very good; however did not work on Safari only Chrome.
- Closing ‘if' statements with ‘end’ felt like I was coding basic again.
Full code example is below.
#!/usr/bin/env ruby
# Usage:     cat <filename> | ./<edge.rb>
def CalculateEdge(arr)
  result = ""     # loop over each line of the array of text items
  for lineIndex in 0 ... arr.size
     topChar = "0" # start empty
     prevChar = "0" # start empty
     for charIndex in 0 ... arr[lineIndex].chomp.size
       # consider <whitespace> as '0'
       currentChar = arr[lineIndex][charIndex].gsub(/\s/,'0')
       # validation checks
       if lineIndex == 0 then
          topChar = currentChar  # assume current char if first row
        elsif lineIndex > 0 && charIndex > arr[lineIndex-1].chomp.size
          topChar = "0"  # assume "0" if missing on row above
        else
          topChar = arr[lineIndex-1][charIndex].nil? ? "0" : arr[lineIndex-1][charIndex].gsub(/\s/,'0')
        end
        # XOR char against the previous char to the left of current
        edgeLeft = prevChar.to_i(2) ^ currentChar.to_i(2)
        # XOR char against the char above the current
        edgeTop = currentChar.to_i(2) ^ topChar.to_i(2)
        # if the left char has not changed use the top row
        edge = edgeLeft == 1 ? edgeLeft : edgeTop
        prevChar = currentChar
        result = result+"#{edge}"
     end   result = "#{result}\n\t"
   end
   return result
end
# Place each line into an array
input = $stdin.read
if not (input =~ /[^0-1\W]/).nil? then
    puts "Error: Only 0-1 values allowed. e.g. 0100001111"
    puts "       Whitespace will be considered '0'"
    exit
end
arr = input.split(/\n/)
result = CalculateEdge(arr)
puts "Input :\t#{input}"
puts "Output:\t#{result}"

Next steps for the language

Must see if you can Unit Test this language ….. debugging on the command line was not great.

Tuesday, January 10, 2017

Going with Ruby

Today I decided to try some different languages just to see what would happen. I decided to try Ruby, just because it was on my laptop. Created by Yukihiro "Matz” Matsumoto around 1995, Ruby is one of those dynamic languages, primevally used on the Web. I have found out however that it’s also quite general so can be used as an alternative for Bash.
I took a simple edge case computation to try out. This is where a string of binary numbers is suppled and the program notes when the pattern changes. It’s a fairly simple problem, but nice as it hits all the main pain points, input for users, validation, loops, output of results, etc.
I’m happy to say it was a really simple language to understand. The “IRB” (Interactive RuBy) command within Terminal, lets you try out code on the fly. Getting the script to run on the Mac required a change to permissions to give it execute rights (“chmod 777”), but that’s was acceptable.
#!/usr/bin/env ruby
# Edge detection script
input = gets.chomp
if not (input =~ /[^0-1]/).nil? then
    puts "Error: Only 0-1 values allowed. e.g. 0100001111"
    exit
end
prevChar = "0"
result = ""
begin
   input.split("").each do |currentChar|
    # XOR each char against the previous
    edge = (prevChar.to_i(2) ^ currentChar.to_i(2)).to_s(2)
    result = result+"#{edge}"
    prevChar = currentChar
  end
puts "Input : #{input}"
puts "Output: #{result}"
rescue Exception => e
puts 'There was an unexpected error processing. ' + e.messageend 
end
All in all, it’s a nice language

Sunday, June 12, 2016

Entity Framework error ‘There is already an open DataReader associated with this Command which must be closed first.’

Had an error on a WebAPI call, which suddendly appeared, when attempting to get a list of Users from standard Identity Framework code.

There was the ususal massive (and almost completely useless) outer exception of "Error getting value from 'Claims' on 'System.Data.Entity.DynamicProxies.ApplicationUser_7215CB73076794A910D6058DEA10BE4541B79EFD3A2E64C8BB0403E9276DE20E'.” and within that "An error occurred while executing the command definition. See the inner exception for details”. Until finally we got to the base error "There is already an open DataReader associated with this Command which must be closed first.” of type System.InvalidOperationException.

After a few minutes scrating my head trying to figure out what was wrong, changing connection strings and trying to shut down all connections I came across a new option that can be added to the connection string, which was "MultipleActiveResultSets=True” (https://msdn.microsoft.com/en-ie/data/jj556606.aspx).

Changing the string from:
Server=(LocalDb)\MSSQLLocalDB;Database=<name>;Trusted_Connection=True
to
Server=(LocalDb)\MSSQLLocalDB;Database=<name>;Trusted_Connection=True;MultipleActiveResultSets=True;

Addressed the issue; I’m not 100% on the impact of this change, but it seems to fix the error and have no obvious down side.

Sunday, April 13, 2014

Strange CSC build Error in Visual Studio

Today I had one of those really horrible Visual Studio errors that just would not go away …

clip_image002

OK .. Message seemed simple enough, I’m missing a reference to the DataAccess assembly, which was breaking with a compilation error … So I check the solution to make sure WGPSN.Utility has been referenced and everything looked fine…

clip_image004

Reference is correct and when I compile WGPNS.Utility it’s building correctly. Weird …… ???

I went through the usual stuff like making sure that everything was building against the same version of .NET Framework (4.5) and everything was set correctly.

Solution !!

The reason for this error was nothing to do with the code but the Build Order for the solution …

Right click the solution file and select “Project Build Order”.

clip_image006

WGPSN.DataAccess was before WGPSN.Utility??? Why?? DataAccess references Utility and therefore the build should be Utility first then DataAccess.

Click the “Dependencies” tab and select the offending project “WGPSN.DataAccess” and it has not dependencies on “WGPWN.Utility”? That was not correct as once a project is referenced, that project should be built before the project that is using the reference.

clip_image008

Check the WGPSN.Utility and click “OK”.

clip_image010

All the problems went away.

I really don’t understand why this problem occurred as these settings are usually automatically controlled by Visual Studio, but keep your eyes out for it.

Sunday, March 23, 2014

Getting AD Users into your database

I had one of ‘those’ requirements the other day where I had a WebApp that needed to see all the Users information from Active Directory; however I also had to show details from the internal database.  It’s one of the requirements that popup from time to time and has about 50 different options for implementation. 

In this case I just wanted to have a nightly job to populate a simple table that I could query.  Going direct to AD using code was to slow as there where about 20000 records and they where nested into 20 levels of folders.

The solution was to create a few simple stored procedures:

The first was to get all the Users from a provided folder name;

CREATE PROCEDURE [dbo].[GetUsersFromRoot] ( @root as varchar(1000), @name as varchar(100) = '' )
AS 
SET NOCOUNT ON
-- get the 
DECLARE @sqlString as varchar(1000)

SET @sqlString = 'SELECT '''+ @root+''' as OU, sn, givenName, lower(sAMAccountName), company, lower(userPrincipalName) FROM OPENQUERY(ADSI, ''SELECT givenName, sn, sAMAccountName, company, userPrincipalName FROM ''''LDAP://' + @root + ''''' WHERE objectClass=''''Person'''' AND objectClass=''''User'''' AND sAMAccountName='''''+@name+'*'''''')';
EXECUTE ( @sqlString )
;

The second was to get all the OU’s in the folder; this would be used for a recursive search.
CREATE PROCEDURE [dbo].[GetOUsFromRoot] ( @root as varchar(1000) )
AS 
-- get the 
DECLARE @sqlString as varchar(2000)
SET @sqlString = 'SELECT ''' + @root + ''' as RootOU, distinguishedName FROM OPENQUERY(ADSI, ''<LDAP://' + @root + '>;(&(objectClass=organizationalUnit));distinguishedName;onelevel'')';
EXECUTE ( @sqlString )
;

Now that we have these, we have something that will bind these all together…


CREATE PROCEDURE [dbo].[GetADUsers] ( @root as varchar(1000) )
AS 
DECLARE @rootOUError as varchar(1000);

IF OBJECT_ID('tempdb..#ous') IS NOT NULL DROP TABLE #ouUsers
IF OBJECT_ID('tempdb..#ouUsers') IS NOT NULL DROP TABLE #ous

-- create user table if needed
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
BEGIN
    CREATE TABLE Users ( OU varchar(1000), LastName varchar(100), Firstname varchar(100), LanId varchar(100), Company varchar(100), Email varchar(100)) ;
END

-- create temp tables
CREATE TABLE #ous ( RootOU varchar(1000), OU varchar(1000), error bit)
SELECT OU, LastName, Firstname, LanId, Company, Email INTO #ouUsers FROM dbo.Users WHERE 1=2;  -- get round Collation issue
EXEC dbo.GetADUsersSub @root

-- recurse search any OU that had an error
DECLARE @ouErrorCursor CURSOR
SET @ouErrorCursor = CURSOR FAST_FORWARD FOR SELECT OU FROM #ous WHERE error=1 AND RootOU = @root
OPEN @ouErrorCursor
FETCH NEXT FROM @ouErrorCursor INTO @rootOUError
-- Get all users with the OU 
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Error reported on ' + @rootOUError + ' so running against that OU.'
        EXECUTE dbo.GetADUsersSub @rootOUError
        FETCH NEXT FROM @ouErrorCursor INTO @rootOUError
    END
;

GO

The procedure above will create our Temp table for the data and then kick off a recursive search for any folders within the root folder.

CREATE PROCEDURE [dbo].[GetADUsersSub] ( @root as varchar(1000) )
AS 
SET NOCOUNT ON
------- Main procedure
DECLARE @alpha as int;
DECLARE @rootOU as varchar(1000);
DECLARE @ouUserCursor CURSOR
DECLARE @message as varchar(1000);
DECLARE @rootOUError as varchar(1000);

-- Get all OUs within this root
INSERT INTO #ous ( RootOU, OU ) EXECUTE dbo.GetOUsFromRoot @root;

SET @ouUserCursor = CURSOR FAST_FORWARD FOR SELECT OU FROM #ous WHERE RootOU = @root
OPEN @ouUserCursor
FETCH NEXT FROM @ouUserCursor INTO @rootOU
-- Get all users with the OU 
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- Loop over each character from A-Z as a simple way to Window the query
        -- ADSI interface has a 900 entry limit which is a limitation to stop DOS attacks
        -- increasing this limit is an option but for the moment this is a simple way to extract everything 
        SET @alpha = 65; -- start at 'A'
        WHILE @alpha < 91
        BEGIN
            BEGIN TRY
                  DECLARE @character as char;
                  SET @character = char(@alpha);
                  INSERT INTO #ouUsers ( OU, LastName, firstname, lanid, company, email ) EXECUTE dbo.GetUsersFromRoot @rootOU, @character;
                  SET @alpha = @alpha+1
            END TRY
            BEGIN CATCH
                -- Execute the error retrieval routine.
                SET @message = ( SELECT ERROR_MESSAGE());
                PRINT 'ERROR: getting OU data ' + @rootOU + '(' + @message + ')';
                -- loog the error
                UPDATE #ous set error=1 where OU = @rootOU;
                BREAK;
            END CATCH;
        END
        FETCH NEXT FROM @ouUserCursor INTO @rootOU
    END
CLOSE @ouUserCursor
DEALLOCATE @ouUserCursor

-- Clean up the OU Names by removing anything without an email
UPDATE #ouUsers set OU = REPLACE(REPLACE(REPLACE(OU, @root, ''), 'OU=', ''),',','')
MERGE dbo.Users AS T
USING (SELECT DISTINCT OU, LastName, Firstname, LanId, Company, Email FROM #ouUsers WHERE LanID is not null and Email is not null) AS S
    ON (T.LanId = S.LanId)
    WHEN MATCHED THEN
        UPDATE SET T.OU = S.OU, T.LastName = S.LastName, T.Firstname = S.Firstname, T.Company = S.Company, T.Email = S.Email
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (OU, LastName, Firstname, LanId, Company, Email) VALUES (OU, LastName, Firstname, LanId, Company, Email);

PRINT 'Cleaning out Users Table';
TRUNCATE TABLE #ouUsers;

PRINT 'run the procedure for any OUs in error';
DECLARE @ouErrorCursor CURSOR
SET @ouErrorCursor = CURSOR FAST_FORWARD FOR SELECT OU FROM #ous WHERE error=1 AND RootOU = @root
OPEN @ouErrorCursor
FETCH NEXT FROM @ouErrorCursor INTO @rootOUError
-- Get all users with the OU 
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Error reported on ' + @rootOUError + ' so running against that OU.'
        EXECUTE dbo.GetADUsersSub @rootOUError
        FETCH NEXT FROM @ouErrorCursor INTO @rootOUError
    END
;

GO

Above; we get round the limits on AD queries by going via the alphabet, All A’s, B’s, C’s etc…. It’s not fast but it was easier than getting the network limits changed.

Tuesday, March 4, 2014

Attending ThoughtWorks Hang out today

I had the good fortune to attend the ThoughtWorks technology Radar presentation this morning ..  Reviewing the Radar gave me some ideas for new technologies on the horizon, but most importantly which technologies and frameworks that I can safely ignore for a few more months.

It’s well worth a review… http://www.thoughtworks.com/radar/#/

Tuesday, February 11, 2014

List of Items in Business Objects

Today one of the Users asked if it was possible to update the list of items that appear in a query list….

clip_image002

For example, the list above shows all months in 2014 .. they only want to see dates in 2013 and 2014.

You can do this using Information Designer.

1) Open the Universe

2) Select the “Parameters List of Values option”

clip_image004

3) Edit the existing list or create a new one.

clip_image006

4) Edit the Query and change the name

clip_image008

5) Add the additional values you want in the list and click OK.

6) clip_image010

7) Next ensure that the filter/field in the Universe is associated with the correct list

8) Click on “Business Layer” and the field; then click “Advanced”

clip_image012

9) Publish the Universe.

Sunday, January 12, 2014

Compressing PDF files with Nitro PDF

Today I had a problem getting a file sent to to a client. The issue was that the PDF was running to 32Mb in size and the email limits where stoping transport. The solution was to "Optimise" the document.

Open the doc in Nitro PDF; select File / Optimize

clip_image002

Select "Web" and click "Optimize" button .. simple. After a few seconds you end up with a file just under 6Mb!

Friday, December 20, 2013

Problems with date/time formats with Telerik Grid

Today I had a problem with Telerik Grid showing a databound column on the test server, in that crazy US format (no offence to Dave!) 'mm-dd-yyyy' rather than they far more logical format 'dd-mm-yyyy'. This was not the case on the Production server or when running locally on a development PC. Logging on to the server and manually setting the region to "Australia" did not work.

The solution is to check the user account under which the application is running under IIS; then logon to the server using this account and changing the region. After that you'll need to do an IIS reset and all should be well.

Wednesday, February 2, 2011

Encrypting Web.Config part 2

Someone noted that my previous script for encrypting web.config files was missing out some applications and I discovered it was because they where at the root level and my script expected everything to running under a virtual directory.  This was correct for the development machines but on a production machine the site could be anywhere.

Working by file

To fix this I changed the script to simply find all the web.configs on a specific drive and do it that way.  It turned out to be easier than going via IIS and probably more accurate too.  There modified script is below:

$Dir = get-childitem G:\ -recurse
$List = $Dir | where {$_.name -eq "web.config"}

## Sections we want Hashed ###
$configSections = @('connectionStrings','appSettings')
## Command line for the encrypting system ###
$CmdLine = "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "

foreach($file in $List)
{
    ### Process the directories ###
    write-Host "processing  -> " $file.fullname;
    foreach($section in $configSections)
    {
        $command = $CmdLine + $section + " " + $file.fullname + "' -prov 'RsaProtectedConfigurationProvider'";
        #invoke-expression -command $command | out-null
    }

}

Tuesday, February 1, 2011

Encrypting Web.Config

Today I spent a few hours getting a script together that would encrypt all the web.config files for all the sites and applications on a server.   It was more difficult than expected, but I think that’s more because I don’t really know PowerShell as well as I figured.  It was also the fact that our servers are running version 1 rather than version 2 which makes things a little more complicated.

The Script

The script is given below (not much sot show for 4 hours work!). 

### Powershell script to encrypt all web.configs###
$objSites = [adsi]"IIS://localhost/W3SVC"
foreach ($objChild in $objSites.psBase.children)
{
    $sitePath=$objChild.psBase.Path + "/Root";
    Write-Host "Processing Site:" + $sitePath;
    $iis=[adsi]$sitePath;
    $vroot = $iis.psbase.children ;
    trap  { continue;}

    ## Sections we want Hashed ###
    $configSections = @('connectionStrings','appSettings')
    ## Command line for the encrypting system ###
    $CmdLine = "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pe "
    ### Process the directories ###
    foreach($vdir in $vroot)
    {   
        Write-Host "processing  -> " $vdir.psBase.Name;
        foreach($section in $configSections)
        {
            $command = $CmdLine + $section + " -app '/" + $vdir.psBase.Name + "' -prov 'RsaProtectedConfigurationProvider'";
            invoke-expression -command $command | out-null
        }
    }
}

In essence its a simple loop, find all teh defined sites, then all the virtual directories below these.  Run teh command line utility “aspnet-regiis –pe ”, which will work it’s magic.

Powershell

One of the major things you need to have on teh server for this work is PowerShell.  This feature is built into Windows 2008 so all you need to do is enable it by adding the “Microsoft Powershell” feature.  For Windows 2003 you’ll need to download the installation package from Microsoft.

If you’ve installed PowerShell for teh first time tehn you’ll also need to set th Execution Policy.  Just enter “Powershell” at the command prompet and enter “Set-ExecutionPolicy RemoteSigned”, then exit.

 

The Timer Job

The simplest way of making sure that this is always applied to all sites is to create a timer job that runs every hour.

Wednesday, November 24, 2010

Authentication against Active Directory and ADAM

Today we were doing some work with authentication to see if we can improve the way it’s done on the external environments, Corp Website, Xtranet and the CEBs.  The plan was to use ADAM (Active Directory Application Mode) but this would mean a lot of nice features that are out-of-the-box with Active Directory.

To test both options I created a simple winform that will verify both options.

image

Using Active Directory

This is very well supported in the .Net Framework, you can use the built-in .Net references:
System.DirectoryServices.AccountManagement;
System.DirectoryServices;

Here is the code;

try
{ 
  // create a "principal context" - e.g. the domain (can also be a machine, too)
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, txtDomain.Text))
    {
        // validate the credentials
        if (pc.ValidateCredentials(txtUsername.Text, txtPassword.Text))
            lblStatus.Text = "Login successful!";
        else
            lblStatus.Text = "Login unsuccessful!";
    }
}
catch (Exception ex)
{
    lblStatus.Text = ex.Message;
}

The PrincipleContext connects you to the domain, while the ValidateCredentials method will return True if its a valid name/password pair and false if not.

Using ADAM

This is not as well supported but it is there if needed.

try
{
     using (DirectoryEntry entry = new DirectoryEntry(txtPath.Text, txtUsername.Text, txtPassword.Text))
     {
         try
         {
             if (entry.Guid != null)
                 lblStatus.Text = "Login successful!";
             else
                 lblStatus.Text = "Login unsuccessful!";
         }
         catch (NullReferenceException ex)
         {
             lblStatus.Text = ex.Message;
         }
     }
}
catch (Exception ex)
{
     lblStatus.Text = ex.Message;
}

Here we create a Directory entry and connect to it using an LDAP path.  That is we tell the application where to find the Users information.  In my form I used; LDAP://localhost:389/cn=Groups,cn=XXX,cn=YYY,dc=ZZZ

The important thing here is that the address is entered in reverse order.  You enter the container for the User, then the container in which the User is located and ten any other container and so on until the top.

Someone might find it useful, but I’m happy to stick with Active Directory.

Wednesday, November 17, 2010

Running SQL scripts in PowerShell

I had the requirement to create a power shell script that would query a SQL database.  It turned out to be very easy indeed…

# Create SqlConnection object, define connection string, and open connection
$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server=Livesqlserver; Database=WebCDB; Integrated Security=true"
$con.Open()

First create the connection…

$cmdSelect = "SELECT DATEDIFF(day, update_date, getdate()) as datedifference, DATENAME(dw, update_date) as theday , count(*)as TotalMails FROM  mail_tbl where sent=1 and mail_type='XTRANET' and  DATEDIFF(day, update_date, getdate()) < 7 group by DATEDIFF(day, update_date, getdate()), DATENAME(dw, update_date) order by datedifference desc"
$da = New-Object System.Data.SqlClient.SqlDataAdapter($cmdSelect, $con)

Create the SQL you want to return values on..

$dt = New-Object System.Data.DataTable
$da.Fill($dt) | Out-Null

Fill a dataset with the results

Foreach ($row in $dt.rows)
{  Write-Host $row.theday $row.TotalMails  }

Print out the results… easy

Monday, November 1, 2010

Charting in ASP.NET and Visual Studio 2008

I was doing some VS2010 migration research over the weekend and found that the Charting options available are really good, we could finally rid ourselves of our old Dundus Charting software.  My heart sank when I came back to the other problems in moving from VS2008 to VS2010, but after a bit of searching I found that all the charting options are backwardly compatible.

Things to install

You need to install two items onto your desktop development PC, both are very simple self extractors.  It would be best to close Visual Studio before doing this, but I don’t think it would make a lot of difference.

Following the installation you should now have a new Chart option available in your Data tool bar.

image

Using the new graph facilities

To create a simple graph I just created a new ASP.NET application with a single ASPX page called default. Dragging a chart from the toolbar to the design surface and switch to the source view will give you the code below.

<asp:Chart ID="Chart1" runat="server">
    <Series>
        <asp:Series Name="Series1">
        </asp:Series>
    </Series>
    <ChartAreas>
        <asp:ChartArea Name="ChartArea1">
        </asp:ChartArea>
    </ChartAreas>
</asp:Chart>

First thing we need to do is add soem values.  I could do this a code behind, but for this demo I’ll just use the page code.

<asp:Series Name="Column" BorderColor="180, 26, 59, 105" YValuesPerPoint="2">
    <points>
        <asp:DataPoint YValues="45,0" AxisLabel="Jan" />
        <asp:DataPoint YValues="34,0" AxisLabel="Feb" />
        <asp:DataPoint YValues="67,0" AxisLabel="Mar" />
        <asp:DataPoint YValues="31,0" AxisLabel="Apr" />
        <asp:DataPoint YValues="27,0" AxisLabel="May" />
        <asp:DataPoint YValues="87,0" AxisLabel="Jun" />
        <asp:DataPoint YValues="45,0" AxisLabel="Jul" />
        <asp:DataPoint YValues="32,0" AxisLabel="Aug" />
    </points>
</asp:Series>

Here I’ve added 8 random numbers and given them a label for each month.  Next we add in the chart area code.

<asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid" BackSecondaryColor="White" BackColor="64, 165, 191, 228" ShadowColor="Transparent" BackGradientStyle="TopBottom">
    <area3dstyle Rotation="10" perspective="10" Inclination="15" IsRightAngleAxes="False" wallwidth="0" IsClustered="False"></area3dstyle>
    <axisy linecolor="64, 64, 64, 64">
        <labelstyle font="Trebuchet MS, 8.25pt, style=Bold" />
        <majorgrid linecolor="64, 64, 64, 64" />
    </axisy>
    <axisx linecolor="64, 64, 64, 64">
        <labelstyle font="Trebuchet MS, 8.25pt, style=Bold" />
        <majorgrid linecolor="64, 64, 64, 64" />
    </axisx>
</asp:ChartArea>

Doing a preview will give you the following error: “Error executing child request for ChartImg.axd”

image

So what went wrong?  Well, as all the charts are generated on the fly, we need to make a few changes in the Web.Config.  Add the following  lines and all should be well; 

Within <system.web><httpHandlers>, add the following: <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />

Within <system.webServer><handlers>, add the following:

<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

Now when we run the programme, we get the following:

image

Putting on a bit more flash on our creation

Ok that graph looks a bit dull, so we add a legend and border by adding the following code to the page;

<legends>
    <asp:Legend IsTextAutoFit="False" Name="Default" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"></asp:Legend>
</legends>
<borderskin skinstyle="Emboss"></borderskin>

Then we change the type to “Area” by modifying the series properties;

<asp:Series Name="Column" BorderColor="180, 26, 59, 105" YValuesPerPoint="2" ChartType="Area">

Now it looks like this:

image

Its simple easy to use and very powerful and should be compatible with SharePoint.  It may not be Sliverlight, but it work…

Friday, October 29, 2010

Getting Jiggy with Ajax and fields

I was asked to do something that I’ve done a million times before the other day, link a drop down field to a radio button so depending on what is selected the list of option should reduce. I decided to use Ajax and JQuery to do all the hard work and also because its really good at what it does.

The first requirement was to have a number of radio buttons on screen each showing the name of a department. These were very simple at first, not even taken from the database. So I created a very simple bit of HTML…

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Ajax Demo</title>
</head>
<body>
Corporate <input type="radio" id="radio1" name="BU" value="Corporate" /><br />
Food <input type="radio" id="radio2" name="BU" value="Food" /><br />
Investment <input type="radio" id="radio3" name="BU" value="Investment" /><br />
<select id="department">
<option value="0">-- No business unit selected --</option>
</select>
</body>
</html>

Nothing crazy here, just your basic setup, with three radio buttons and a select box with no values. It would look like this.

image

Adding the Ajax bit

Now we need to implement JQuery onto the page, and we do this by including the latest script file. You can get this on the internet, via a content delivery network or just download it. I’ve taken a copy as its quicker.

<script type="text/javascript" src="template/scripts/jquery-1.4.2.min.js"></script>

The line above adds the JQuery script into the page your are working with.

Below is the script to do all the wor, I’ve highlighted the interesting bit.

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("input[name*='BU']").click(function() {
callAjax($(this).val());
});
});

function callAjax(val) {

var selectedValue = val;
var servletUrl = '/OrganisationChartDataService.svc/Departments/'">http://<server>/OrganisationChartDataService.svc/Departments/' + val + '/JSon';

$.getJSON(servletUrl, function(options) {
var department = $('#department');
$('>option', department).remove(); // Clean old options first.
$.each(options, function(index) {
department.append($('<option/>').val(options[index].Id).text(options[index].Name));
});
});

}

</script>

The first section binds a “click” function to any element on the page with the name “BU”. This is handy because we don’t have to write a separate function for each element and if we add more we don’t have to do anything, it will just work.

The second highlighted bit is teh call to a WCF web service that takes in the name of a business Unit as being part of the URL, what’s returned can then be added to the select list.

The results can be see below, its fast simple and very powerful.

image

clicking another item shows this:

image

Wednesday, October 20, 2010

Old school CSV without creating a temp file

I had a request to export a report out to Excel today, which is something I’ve done a bunch of times before but always by producing a temporary file.  I figured I’d try something different, find a way to give me the same functions without having to worry about permissions on the file system, or deleting the files afterwards.

It turned out to be very easy… use a TextStream that writes out  a HTML header so Explorer does all the hard work.

On the ASPX page…

On the click event for the export button we turn off the usual ASP.NET view state stuff and make a new header with the content type of "application/vnd.ms-excel", this tells IE to start Excel regardless of the details sent.  Another interesting thing to see here is the Response.End call, you’ll need this to prevent ASP.NET sending the page refresh information along with your data.

protected void ExportButton_Click(object sender, EventArgs e)
{
      this.EnableViewState = false;
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "inline;filename=TeamExport.csv");
        team.ExportToExcel(Response.Output, true);
        Response.Charset = "";
        Response.End();
}

On the Business Object its a simple matter of building up an array of results, making sure to wrap them in “” for each field.  Then added this to the HTML TextStream …..

/// <summary>
/// Export Global Team lists to Excel
/// </summary>
/// <param name="httpStream">The HTTP stream.</param>
public void ExportToExcel(TextWriter httpStream)
{
     // find all associated applications
     IList<Application> applications =  (from application in Application.FindAllByProperty("GlobalTeam", Id)
             select application).ToList<Application>();

     foreach(Application app in applications)
     { 
         string[] dataArr = new string[]
             {
                 WriteableValue(app.Id),
                 WriteableValue(app.GlobalTeamName),
                 WriteableValue(app.Title),
                 WriteableValue(app.SupportManager),
                 WriteableValue(app.ProjectManager),
                 WriteableValue(app.StartDate.ToShortDateString()),
                 WriteableValue(app.EndDate.ToShortDateString())
             };
         httpStream.WriteLine(string.Join(",", dataArr));
     }
}

public static string WriteableValue(object o)
{
    if (o == null || o == null)
        return "";
    else
        return "\"" + o.ToString() + "\"";
}

Its good to rediscover something old, simple but yet works so well ….

Thursday, October 14, 2010

More pain with Windows x64 migration

You have no idea how hard it was to get this to work!.  following on from my last posting I moved over from Windows XP to Windows 7 on x64 for development.  Although there was some pain in setting up the VB COMs it was nothing to the suffering when it comes to Registry settings.

Some applications were continually giving Generic 500 errors with little or nothing in the Event Logs, so I presumed it was a security problem.  Following many hours of messing about, it turns out I was on the wrong track altogether.  The specific COMs were failing because they were looking for Registry settings…

All the settings had been imported into their usual position under HKEY_LOCAL_MACHINE\SOFTWARE\SomeApplication, but no matter what I did the values always came back null. 

The solution

The answer was hidden away in a MS support article (http://support.microsoft.com/kb/896459)

32-bit programs and 64-bit programs that are running on an x64-based version of Windows operate in different modes and use the following sections in the registry:

  • Native mode 64-bit programs run in Native mode and access keys and values that are stored in the following registry sub key:
    HKEY_LOCAL_MACHINE\Software
  • 32-bit programs run in WOW64 mode and access keys and values that are stored in the following registry sub key:
    HKEY_LOCAL_MACHINE\Software\WOW6432node

So adding a copy of the REG settings to this second location made everything work again.

Tuesday, October 5, 2010

Setting up Windows 7 for Classic ASP

I’ve decided to move over from using the slow VPN to local development so decided to setup some old classic ASP applications on my local machine which is running IIS 7.5.  Unfortunately this process was far from easy.

Setting up IIS

First you need to be able to activate all the required roles.  You do this by selecting Control Panel/Programs/Turn Windows features on or off.  from the list you select the following:

Parallels Picture

Doing some configuration

Next you should create an Admin Console for you to work with.  Type  “MMC” into the start menu and select File/Add Remove Snap in from the menu.  Select IIS Manager and IIS Manager Ver.6, Also choose Event Log for the current machine.

Parallels Picture 1

File Save this to your desktop for later.

Getting it working

When I got a local copy of the application all the .NET code worked first time without any issue, however when I tried to run any Class ASP code I got a standard Error: This error (HTTP 500 Internal Server Error) means that the website you are visiting had a server problem which prevented the webpage from displaying.

After some checking about on the net it turns out that you can turn on messages for ASP code using a configuration setting in IIS Manager,

Within IIS Manager Browse to the Virtual Directory you need and Double click click on the ASP icon and expand the “Debugging Properties” tree.

Parallels Picture 2

Turn on “Log Errors to NT Log” and “Send Errors to Browser”.

Unfortunately after doing this I still did not get an error messages displayed so had to do some more hunting down of the error.

Tracing requests

You also need to turn on Tracing which can be done by reading the instructions on the following link: http://learn.iis.net/page.aspx/565/using-failed-request-tracing-to-troubleshoot-classic-asp-errors/

Following this you actually get to see a correct error!

Parallels Picture 3

LineNumber:21
ErrorCode:800a01ad
Description: ActiveX component can't create object

Checking the global.asa gave me the following line:
Set GetDirectory = Server.CreateObject("EnterpriseIreland.BusinessObjects.HumanResources.Directory")

Checking Permissions

This error is usually down to permissions or the worker process can’t find the DLL.  Setting “Everyone” with Full permissions on the D:\Applications\ folder did not work, neither did giving “Everyone” access to the D:\Development folder.

Next I checked to make sure the DLLs were correctly registered by re-running  the “register_assembly.bat” command file located with in the D:\Applications\Common folder.

Next open Regedit.exe and browse to the DLL that was failing:
HKEY_CLASSES_ROOT\EnterpriseIreland.BusinessObjects.HumanResources.Directory open the CLSID key and you find a GUID.  In my case it was “{C940B037-A429-303E-8B2E-162E4E19AC91}” search the registry for this GUID.

You should find it somewhere in the HKEY_CLASSES_ROOT\Wow6432Node\CLSID\ key group; in my case it was here: HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{C940B037-A429-303E-8B2E-162E4E19AC91} click into the “InprocServer32” key and look for the value key “Codebase” this should show the file location of the DLL.  If it’s not pointing to the correct location change it.

Moving to App Pool

None of these fancy changes seemed to make any difference so I decided to look into the AppPool configuration.  The DefaultAppPool was working fine with .Net, so I created a second one based on this called “ASP”.

Parallels Picture

Next in the Advanced settings you need to make one minor but VERY IMPORTANT change;

Parallels Picture 1

You must set “Enable 32-bit Applications” to “True”

Finally assign your website to use this application pool by selecting it in IIS Manager and click Basic Settings in the Action Menu.

Parallels Picture 2

Click Select and choose “ASP” or whatever your AppPool name is called.

Success At last!!

After all this, we finally have a working legacy ASP site working on Windows 7.

Monday, April 5, 2010

Adventures when moving to GIT

I’ve been on Git hub a few times but never actually set this up on my laptop.  Following some Open Source work with a group of friends I finally got the point to the solution.  Distribution of the repositories and the ability to pick and choose the areas you want to take into your own, was such a simple and effective way to share code I decided to adopt it for most of my local development.

I am however not the best with the command line interface so when I heard that the tortoise group had got together and created an integrated windows version, I had to give it a go.

Setup

Download the software from Google code and run the MSI file worked first time without any issue.  You will however need to restart your PC/Laptop following the installation.

image

Following an reset you’ll get some extra options in your stadard windows explorer.

Connection to an existing repository

I already had an existing GitHub repository so it was a simple matter of connecting up to this.  First create a folder on your drive (in my case I called it Development) on your C Drive.  Right click on the empty directory and select Git Clone.

Select the URL on git hub of the git file and project you want to connect too, in this case the NXMPP code project.

image

Click Ok.

image

All going well you can click Close and have a copy of the code on your PC.

image

Pushing a change

So supposing you’ve a change to make to this code, how can you get it back to the cloud repository?  I’ve made a very simple change to one of the tests to illustrate the changes in one file.

image

Here in explorer you can see that Git has realised that there was a change to one of the files.

image

Right click the file and select “Diff” will bring up the a description of the changes.

Now lets say that change needs to be placed back into the repository, simply right click the file or directory and select Git Commit.  This will place the code back into the repository.

I’m looking forward to getting more into this very simple and interesting product.