Search This Blog

Saturday, December 29, 2012

RDLC Basics


So less than 6 hrs of time invested and I have basic RDLC reporting working for data displayed in a table / grid.  Also created several multi-column reports.

So here is my basic approach:

My data source is a MS Access MDB file but this would work for SQL server just as easy. Simply a different connection string.

Step #1 - Create a visual dataset with table adapters that can be bound to a report.



Step #2 Create basic RDLC report without using the wizard.

  1.  Add new item, select reporting template, select Report.
  2. In report data panel, select new dataset
  3. Select data source 
  4. Select table adapter
  5. Add table / grid to body of the report.
  6. Assign columns in the table / grid to fields from the tableAdapter field list
  7. Right-click in the report designer below the report body and add page header or page footer as needed.
  8. Add Report name, execution time, and page number from built-in fields
Step #3 Fetch data for report and return it as a data table
Here is  my design approach.  I only use table adapters to bind fields in the designer.  At runtime, I like to manually fetch the data and add it to report data source.  I do this so I can re-use report design and pass slightly different data sets to the same report.  This is similar to the approach I used 10 year ago with MS Access reports.  Not for everyone but it works for me.

I create a function where I can return the data I want by passing in the report name.


public static DataTable GetReportData(string reportName, string MDBfile)
{
try
{
EnterProc(MethodBase.GetCurrentMethod());
string sql = null;
DataTable table = null;
switch (reportName)
{
case "":
break;
case "CollectionSummaryByYear":
sql = "SELECT [Year], COUNT([Year]) AS SpecimenCount FROM tblMineral_Collection WHERE (Len([Year]) > 0) GROUP BY [Year]";
break;
case "FossilLabel_SmallCabinet":
case "FossilLabel_Thumbnail":
sql = "SELECT tblFossils.ID_Text, tblFossils.CommonName, tblFossils.ProperName, tblFossils.RockFormation, tblFossils.RockAge, tblFossils.Location, tblFossils.County, tblFossils.City, lstStates.State, lstCountries.Country, Str([tblFossils].[Year]) AS strYear FROM (tblFossils LEFT JOIN lstCountries ON tblFossils.CountryID = lstCountries.ID) LEFT JOIN lstStates ON (tblFossils.StateID = lstStates.ID) AND (tblFossils.CountryID = lstStates.CountryID);";                        
break;
case "MineralLabel_Cabinet":
case "MineralLabel_SmallCabinet":
case "MineralLabel_Micromount":
case "MineralLabel_Thumbnail":
sql = "SELECT tblMineral_Collection.ID_Text, tblMineral_Collection.Variety, tblMineral_Collection.Mineral_Name, tblMineral_Collection.Mine, tblMineral_Collection.City, tblMineral_Collection.County, lstStates.State, lstCountries.Country, Str([tblMineral_Collection].[Year]) AS StrYear, tblMinerals.Formula_1, tblMinerals.Formula_2 FROM (((LabelQueue INNER JOIN tblMineral_Collection ON LabelQueue.Specimen_ID = tblMineral_Collection.Specimen_ID) LEFT JOIN lstCountries ON tblMineral_Collection.CountryID = lstCountries.ID) LEFT JOIN lstStates ON (tblMineral_Collection.CountryID = lstStates.CountryID) AND (tblMineral_Collection.StateID = lstStates.ID)) LEFT JOIN tblMinerals ON tblMineral_Collection.Mineral_Name = tblMinerals.Mineral";
break;
case "SpeciesList":
sql = "SELECT tblMineral_Collection.Mineral_Name, Count(tblMineral_Collection.Mineral_Name) AS SpecimenCount FROM  tblMineral_Collection WHERE LEN(Mineral_Name)>0 GROUP BY tblMineral_Collection.Mineral_Name";
break;
}
 
if (!string.IsNullOrEmpty(sql))
{
table = TableFromMdb(MDBfile, sql);
}
ExitProc(MethodBase.GetCurrentMethod());
return table;
 
}
catch (Exception ex)
{
ErrorLog(ex);
return null;
}

The only trick to this approach is to pass in the data using name of dataset originally used to setup report.

var rds = new ReportDataSource("DataSet1", args.ReportData);
var report = new LocalReport
{
ReportEmbeddedResource = string.Format("DRC.RDLC.{0}.rdlc", args.ReportName)
};
report.DataSources.Add(rds);



Creating Labels in RDLC


Next step in Reporting without Crystal reports using RDLC: Multicolumn labels.

See Wrox article on Multicolumn labels

Safety tip for those playing at home with VS2010.  ReportViewer control does not render report to show data spread across into multiple columns.  To save paper, user Convert to PDF as Print preview.

I was able to create a report in landscape layout with 3 columns using Tablix control to display two data fields.

Be mindful to manage column spacing and margins otherwise there will be column spill over to the next page.



Friday, December 28, 2012

Finally Replacing CrystalReports

I've had a long hate-hate relationship with crystal reports.  Latest version of Crystal Reports via SAP is a 72 MB install!?! Why....  CrystalReport 2008 was only 17 MB.  Leave it to SAP to take a poor solution and make it worse.

So, I've been on a quest to replace crystal Reports.  In VS 2010, I've found a workable client side reporting solution in RDLC.  Now, I know its going to be an uphill battle to produce Avery style labels with RDLC but I'm going uphill 75MB lighter.

The real motivation for this reporting switch is my next version of Digital Rockhound's Companion software is going to be a download users can buy.  I'll trimmed down the files my software uses.  I'm ditching my street level arcview shapefiles dated circa 1995 for Google/Bing/OSM online maps.  Last piece is really the reporting engine.

In a little under 3 hours, I was able to add in a basic grid RDLC report into DRC 3.0 and get the report to display in the report viewer, print directly to a local printer, and render to a PDF and word file formats.

Resources that helped me with RDLC reports:

Brian Hartman's code to manually print a RDLC report.  Code sample Here.

MSDN: Walkthrough: Printing a Local Report without Preview 

Get this error attempting to print a localreport without a RDLC source.
The report definition for report 'xxx' has not been specified.

A couple of useful stackoverflow posts:
Code to convert RDLC to a PDF
Code to convert RDLC to Word.

Article from dotnetsoldier blog

My code to render a simple RDLC report to a word Doc and then launch word:


var rds = new ReportDataSource("DataSet1", args.ReportData);
                        var report = new LocalReport
                            {
                                ReportEmbeddedResource = string.Format("DRC.RDLC.{0}.rdlc", args.ReportName)
                            };

                        report.DataSources.Add(rds);
                        // ReSharper disable RedundantAssignment
                        string encoding = String.Empty;
                        string mimeType = String.Empty;
                        string extension = String.Empty;
                        // ReSharper restore RedundantAssignment

                        Warning[] warnings = null;
                        string[] streamids = null;
                        string wordDocName = args.PDFFileName.ToLower().Replace(".pdf", ".doc");
                        byte[] bytes= report.Render("WORD", null, out mimeType, out encoding, out extension, out streamids, out warnings);
                        using (var fs = new FileStream(wordDocName, FileMode.Create))
                        {
                            fs.Write(bytes, 0, bytes.Length);
                        }
                        if (File.Exists(wordDocName))
                            System.Diagnostics.Process.Start(wordDocName);



//My code to print RDLC locally:

                        var rds = new ReportDataSource("DataSet1", args.ReportData);
                        var report = new LocalReport
                            {
                                ReportEmbeddedResource = string.Format("DRC.RDLC.{0}.rdlc", args.ReportName)
                            };

                        report.DataSources.Add(rds);
                        var reportPrintDoc = new ReportPrintDocument(report)
                            {
                                PrinterSettings = {PrinterName = Properties.Settings.Default.DRC_Printer}
                            };

                        reportPrintDoc.Print();


Monday, December 24, 2012

Slight tweak to proposed Handbrake improvement



Added leading zero when converting offset back to a string.


Proposed Handbrake improvement.



destinationFilename = destinationFilename.Replace(tag, (iDvdTitle - iOffset).ToString("D2",CultureInfo.InvariantCulture));

Sunday, December 23, 2012

Proposed Handbrake improvement.

I've been busy ripping DVDs from my collection and I've run into an improvement for handbrake.

While converting TV episodes on DVD, I wanted to autoname the new file using output pattern S01-E0{title+offset}  like {title+5} for disc 2 in a DVD set where the title-1 is episode 6.

Handbrake - HandBrake is an open-source, GPL-licensed, multiplatform, multithreaded video transcoder, available for MacOS X, Linux and Windows

So I downloaded the codebase and found where in Windows code tree auto naming occurs.  HandBrakeCS its in Main.cs and Handbreake WPF autoNameHelper.cs

I have this code compiled and working locally great!

Now a commentary:

Dear SourceForge:

You have to be kidding! Separate logins for main site and forums site.  What is going on?
SourceForge also give lip service only to OpenID.  I initially created my user account with OpenID and  only to find I have limited permissions and I would need to create 'real' account to do anything useful.

SourceForge your site is terrible and I would recommend handbrake moving to another open source hosting site.

destinationFilename = UserSettingService.GetUserSetting<string>(UserSettingConstants.AutoNameFormat);

                    //Add ability to auto name file using {title-offset} or {title+offset}
                    // example {title-1} or {title+3]
                    // This is extremely useful when ripping DVD of tv show episodes.
                    #region AutoName based on {title-offset} or {title+offset}

                    int startPos = 0;
                    int stopPos = 0;
                    string offsetTag;
                    var iDvdTitle = Convert.ToInt32(dvdTitle);

                    if (destinationFilename.Contains("{title-"))
                    {
                        offsetTag = "{title-";
                        startPos = destinationFilename.IndexOf(offsetTag, StringComparison.InvariantCulture);
                        stopPos = destinationFilename.IndexOf("}", startPos, StringComparison.InvariantCulture);
                        string tag = destinationFilename.Substring(startPos, stopPos - startPos + 1);
                        string offset = destinationFilename.Substring(startPos + offsetTag.Length, stopPos - startPos - offsetTag.Length);
                        int iOffset = 0;
                        try
                        {
                            iOffset = Convert.ToInt32(offset);
                        }
                        catch { }
                        destinationFilename = destinationFilename.Replace(tag, (iDvdTitle - iOffset).ToString(CultureInfo.InvariantCulture));

                    }

                    if (destinationFilename.Contains("{title+"))
                    {
                        offsetTag = "{title+";

                        startPos = destinationFilename.IndexOf(offsetTag, StringComparison.InvariantCulture);
                        stopPos = destinationFilename.IndexOf("}", startPos, StringComparison.InvariantCulture);
                        string tag = destinationFilename.Substring(startPos, stopPos - startPos + 1);
                        string offset = destinationFilename.Substring(startPos + offsetTag.Length, stopPos - startPos - offsetTag.Length);
                        int iOffset = 0;
                        try
                        {
                            iOffset = Convert.ToInt32(offset);
                        }
                        catch { }
                        destinationFilename = destinationFilename.Replace(tag, (iDvdTitle + iOffset).ToString(CultureInfo.InvariantCulture));

Saturday, December 1, 2012

Plex Media Server

Over Thanksgiving, my brother-in-law introduced me to Plex Media Server.
It's like  your own personal Netflix using MP4 ripped from your collection.

Plex Media Server is a media distribution system that can use a variety of formats (I'm using MP4/m4v) and distribute the media to different devices at once.
In my household, I am streaming to 3 xboxes, 6 computers, and 4 android tablets.

There other nice aspect of Plex Media server, it is going to allow me to purchase movies and TV shows now in MP4 format then deploy them

Plex is just the server so you will need additional software to convert DVD to MP4s. http://www.plexapp.com/

I am using AnyDVD HD from SlySoft. http://www.slysoft.com/en/anydvd.html

And I am using Handbrake for Windows. http://handbrake.fr/downloads.php

HandBrake can seems a bit complex but reading through the explanaion of the parameters and the help got me started.  I would recommend that you do a couple sample conversions and testing the resulting MP4.

The nice thing is in handbrake you can save your settings as presets.

I created a preset for action movies and went with very conservative parameters to capture motive and I tested the with Wide screen edition of Empire Strikes Back which I then viewed in a 60in TV via XBOX 360.  Handbrake ripped the movie in 2 hrs on 4 3.0 GHz Quad core XEON Dell Precison 490 with 4 GB RAM running 32 bit Windows 7.  The video came out fantastic.



Of course with any software solution, better hardware results in better performance.

Compare:  Ripping a Red Dwarf Episode using good quality video settings (identical on both).

Intel 2-CPU 2-Core Xeon 3.0 Ghz, 4GB RAM , 32bit Windows 7:  ~28 min
Intel i7-2600 CPU 3.40 Ghz, 8 GB RAM, 64bit Windows 7: ~8:30 min !!







ReSharper 7

Recently, I was reintroduced to ReSharper version 7.0.

Resharper 7 is completely awesome.  Best feature is code editing helpers.  With ReSharper, I transformed some reasonably complex nested for each  and if else statements into Linq.  I also love the invert If transformation.  It's great to reduce if else statements complexity.

I put it through its paces refactoring code in my Digital Rockhound's Companion software project.  I decided I would attempt to accept as many of the resharper suggestions as possible.  My code is so much cleaner.

I did notice that on Event delegate declarations, that on occasion Resharper was tagging an event incorrectly as being unsubscribed / unused.  I am still trying to understand the use case but it was easy to get Resharper to ignore it using comment tags.

Anyone who is doing .net development and has never used Resharper should download the trial.  You'll be hooked.

Take it for a test drive.  Any company employing .net developers will save money by using this product by getting better code.

http://www.jetbrains.com/resharper/features/index.html


Monday, September 3, 2012

Convert coordinates between Web Mercator and WGS84 Geographic

From: http://www.gal-systems.com/2011/07/convert-coordinates-between-web.html

Convert coordinates from Web Mercator (102100/3857) to WGS84 Geog (4326) and vice versa you can use these short functions (taken from Esri):


private void ToGeographic(ref double mercatorX_lon, ref double mercatorY_lat)
{
    if (Math.Abs(mercatorX_lon) < 180 && Math.Abs(mercatorY_lat) < 90)
        return;

    if ((Math.Abs(mercatorX_lon) > 20037508.3427892) || (Math.Abs(mercatorY_lat) > 20037508.3427892))
        return;

    double x = mercatorX_lon;
    double y = mercatorY_lat;
    double num3 = x / 6378137.0;
    double num4 = num3 * 57.295779513082323;
    double num5 = Math.Floor((double)((num4 + 180.0) / 360.0));
    double num6 = num4 - (num5 * 360.0);
    double num7 = 1.5707963267948966 - (2.0 * Math.Atan(Math.Exp((-1.0 * y) / 6378137.0)));
    mercatorX_lon = num6;
    mercatorY_lat = num7 * 57.295779513082323;
}

private void ToWebMercator(ref double mercatorX_lon, ref double mercatorY_lat)
{
    if ((Math.Abs(mercatorX_lon) > 180 || Math.Abs(mercatorY_lat) > 90))
        return;

    double num = mercatorX_lon * 0.017453292519943295;
    double x = 6378137.0 * num;
    double a = mercatorY_lat * 0.017453292519943295;

    mercatorX_lon = x;
    mercatorY_lat = 3189068.5 * Math.Log((1.0 + Math.Sin(a)) / (1.0 - Math.Sin(a)));
}

Thursday, July 26, 2012

Stripping special characters from SQL text

Reposting only to keep this from disappearing.  Simple redundancy and I do not claim any part of this work as my known.


This is a repost from Sean McWherter's blog.  

Excerpt from his blog:
Was looking for a better solution than a mile long REPLACE statement, found this. Originally written by Christian d’Heureuse, modified slightly by me. Removes all characters except: 0-9, a-z, A-Z, and spaces (remove “or @c = 32” if you want to also remove spaces).

Here is my usage.  Only added fx_ to function name.

CREATE function dbo.fx_RemoveSpecialChars (@s varchar(256)) returns varchar(256)
   with schemabinding
begin
   if @s is null
      return null
   declare @s2 varchar(256)
   set @s2 = ''
   declare @l int
   set @l = len(@s)
   declare @p int
   set @p = 1
   while @p <= @l begin
      declare @c int
      set @c = ascii(substring(@s, @p, 1))
      if @c between 48 and 57 or @c between 65 and 90 or @c between 97 and 122 or @c = 32
         set @s2 = @s2 + char(@c)
      set @p = @p + 1
      end
   if len(@s2) = 0
      return null
   return @s2
   end


Wednesday, July 18, 2012

What do to if Google tags your blogger blog with a Malware warning

So yesterday, I discovered that Google had tagged my Digital Rockhound's site.

So I used Google WebMaster's tools and verified that my site was clean.
I used this site  http://www.unmaskparasites.com to confirm that I had links to a site with malware.
Turns out I did.

I used a Google site search to help narrow where the links were.  I had two links in a link gadget to the offending site.  Simply removed them.

Then, I used WebMaster's tools a requested a reindex of my site. Good news here is that the links were at root level so the indexing was fast.  


After Google re-indexed my site, no more scary malware warnings.




Thursday, July 12, 2012

SQL 2005/2008 Max(bit)

I'm certain it was possible to Max(bit) in SQL 2000 but that changed in SQL 2005/2008.

 SELECT Max(Col1+0)
   FROM SomeTable

Monday, July 9, 2012

Displaying a public key for an assembly.

This was way harder that it needs to be....

Use sn.exe with -Tp argument.  However,  to make this useful instead of just seeing it in cmd windows,
Follow the steps in this article: http://goo.gl/lFx1B

Use the following path for sn.exe:

For me on a Windows 7 64-bit using VS2010, the path to sn.exe was C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe

Related stackoverflow link :http://stackoverflow.com/a/1123831/44597

Did this so I could attempt to unit test a MVC application that is strongly signed.


ASP.NET MVC - How to Unit Test an Action Method which returns JsonResult?





WebPart Tip: How to quickly view the public key for an assembly in the output window

I saw this handy little helper function being used on a MOSS screencast by Todd Bleeker and decided to figure out how he did it :). Basically it allows you to view the public key token of an assembly from within Visual Studio's output window, which saves time when you need to grab the key for use with the safe control entries in the web.config for example.
First step, fire up your copy of Visual Studio 2005 and open up a webpart class library project. Then from the Tools menu select External Tools. This will bring up the following dialog:
 
From the options, click Add and then give your utility a title. Now all we're doing here is essentially grabbing the output from the sn.exe command, so you will need to provide the path to your local sn.exe file. Mine was located in the following folder:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe 
Now, just like if we were running the strong name utility from the command line, we're going to need to pass in the correct arguments. Firstly we'll need to pass the -Tp argument, as we want to get the token for the public key, together with the public key itself. Then we need to specify the target assembly, which can be done by clicking on the button to the right of the Arguments field and selecting 'Target Path'. This basically gets the full qualified path to item which is being built, in our case a webpart assembly. Lastly just tick the 'Use Output Window' checkbox and then click ok and you're good to go :)
The new utility you've just created should now show up in the Tools menu, you can go ahead and click it and you should now see the output window popup with the details of the public key. This is a really nice feature of Visual Studio and I'm sure this can be tailored for many other uses.

Saturday, July 7, 2012

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Here is an odd bug with an even odder workaround solution.

In a large C# solution, I have numerous projects and some COM wrapped .net controls.


After running the solution, a rebuild might fail with DLL cannot be copied to \bin locked by another process. It was not happening everytime so I thought may one of my components were not getting disposed correctly.  The frequency of occurrence jump 10x after I moved to Windows 7 64bit and VS 2010.  A GIS map control assembly always failed to build after it was run.  Again, first this I thought was my implementation must incorrect.  After some refactoring,I still have the problem, then I found this question on stackoverflow.


The workaround eliminated the issue for me.  


It would be easy to blame VS 2010 or Windows 7 but given the complexity of the two products, little oddities are par for the course.  Just glad for Stackoverflow!




Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug


Seems it is caused by using default assembly version numbers.

This same problem was discussed on Stack Overflow in this question: http://stackoverflow.com/q/2895898/310001

The following answer was proven to be one possible workaround:
http://stackoverflow.com/questions/2895898/visual-studio-build-fails-unable-to-copy-exe-file-from-obj-debug-to-bin-debug/2994502#2994502

I have verified both the bug and the above mentioned workaround in the attached project. In short, what to do to avoid this error is:

1. Open AssemblyInfo.cs in the WindowsService1 project
2. Change the line [assembly: AssemblyVersion("1.0.*")] to [assembly: AssemblyVersion("1.0.0")]
3. Save All solution files
4. Clean solution
5. Using a file browser, go into WindowsService1\bin\Debug\ and rename the locked file Solution6.Module.dll (e.g. to Solution6.Module1.dll - you must use rename, because you won't be allowed to delete it)
6. Go back into Visual Studio
7. Rebuild Solution twice
8. If the error still happens, go to step 4 and repeat again (I had to repeat once - it makes no sense, and I have no idea why, but it works)

When you get this far, everything should now be OK. You can rebuild as often you need to without any problems. Yes, you'll have to take care of incrementing AssemblyVersion manually, but it is a tiny tiny price to pay compared to many of the other "hacks" out there to work around this.


So in short: avoid using default Revision/Build numbers in AssemblyVersion!

Source:VSIP


Thursday, July 5, 2012

Using stored proc with table parameters


Sample stored procedure. SQL Server 2008+


CREATE PROCEDURE [dbo].[usp_audit_select_criticalresults]
    @exams dbo.ExamIDType READONLY    
AS
BEGIN
    SET NOCOUNT ON;
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

    SELECT DISTINCT x.ExamID, 
           case 
             WHEN sap2.ParameterValue is not null then CONVERT(bit,sap2.ParameterValue)
             else CONVERT(bit,0)
           END            
    FROM @exams x
    LEFT JOIN SessionActivityParameters sap
        ON sap.ParameterName='ExamId' AND x.ExamID = sap.ParameterValue
    LEFT JOIN SessionActivityParameters sap2 
        ON sap2.ParameterName='confirmed' AND sap.SessionActivityId =sap2.SessionActivityId
    LEFT JOIN SessionActivity sa
        ON sa.SessionActivityId = sap.SessionActivityId
    WHERE (sa.AttributeId='55CD62C2-AED5-4216-A3C6-FABD0183E130' or sa.AttributeId is null)

            
END

Executing stored procedure with test data in T-SQL:


DECLARE @exams dbo.ExamIDType;

INSERT INTO @exams (ExamID)
SELECT '00993736'
UNION SELECT '00993737'
UNION SELECT '00993738'
UNION SELECT '00993749'
UNION SELECT '00993750'
UNION SELECT '00993766'
UNION SELECT '00993767'

--SELECT * FROM @exams

exec usp_audit_select_criticalresults @exams

Sunday, July 1, 2012

Less Msiérables (LessMSI) - Extraction tool for MSI

Less Msiérables (LessMSI)

A great little tool to extract files from a MSI without installing it.  Had to use this for office 11 (2003) interop assemblies install without having to have office 2003 installed.

Source:

My Dropbox link (because things on the internet tend to disappear)


Saturday, June 30, 2012

Crystal Reports for VS2010

Crystal Reports has been excluded In VS2010. 
To download Crystal Reports, click on the following link:

Friday, June 29, 2012

Javascript, firefox, and ASP.NET MVC 3 development

I am currently part of a development team extending functionality of ASP.NET MVC project allowing users to review data reports.  

The cool parts of this job are: 
  • MVC from 1.1 to 3.0 in this version
  • Getting to move up to VS 2010.  (before anyone comments I know I want VS 2012 and MVC4) 
  • Learning the ends and outs of a complex web site/service by analyzing extending code.  (So much better than the 'Hello World' using .net).
  • Being able to leverage by SQL and C# knowledge so I'm not completely dead weight until I become proficient in javascript.
Things I learned so far:
  • Javascript, are you kidding?  This is why smart device development is such a good idea.  Gets away from a rather poor scripting language. 
  • I hate using FireFox but I love it for debugging.  It is too bad the rapid release process has destroyed one of my favorite browsers.  
  • Browsers I'm currently concerned with supporting: IE9/IE10, Chrome, and Safari.  
  • Two things I love about Javascript: debugger and alert().  The rest can go away.
  • The joy of getting a html button wired to a javascript function to hit Controller.Action()
  • Much deeper understanding and appreciation for large sites as Google and Facebook.
  • http://stackoverflow.com/  is still my best friend!

Defining a function call in javascript

Current project at work has me learning more Javascript.
Here is a simple example of defining a function call for a button in a separate script file.
The project is ASP.NET MCV3 project and the javascript files are incorporated in Site.Master file.

Simple function call in Javascript:

<script type="text/javascript" src="<%= Portal.UrlHelper.VirtualPath %>/Scripts/portal-about.js?ver=<%= Portal.VersionHelper.Version %>">script>

portal-about.js
(function() {

    Portal.about = function() {
    
    };

})();

Strange new world at least for me ;)

Thursday, May 24, 2012

Add date string to a file name

 string logfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), string.Format("RISCONVDB_{0}.LOG", DateTime.Now.ToFileTime()));

Wednesday, May 16, 2012

Using WGR614v5 router as an access point

I needed to by pass config wizard
http:/// basicsetting.htm

Gets you into the settings w/o hitting the wizard.
Note to Netgear, always add the by pass directly to the wizard.

  1. By pass wizard:  http:/// basicsetting.htm
  2. Lan Settings: 
  3. Disable DHCP
  4. Change IP Address
  5. Change wireless SSID to make current router.




Windows NT could not start because the following file is missing or corrupt:

On Windows XP Home Edition, got this message at startup:


Windows NT could not start because the following file is missing or corrupt:
Winnt_root\System32\Ntoskrnl.exe
Please re-install a copy of the above file.


Solution from Microsoft KB314477
Turns out it maybe a bad entry in boot.ini file.
Several approaches to fix this problem.

Method 2

Use the Bootcfg utility in the Recovery Console to correct the Boot.ini file:
  1. Use the Windows XP CD-ROM to start your computer.
  2. When you receive the message to press R to repair Windows by using the Recovery Console, press the R key.
  3. Select the Windows installation that you want, and then type the administrator password when prompted.
  4. Type bootcfg /rebuild, and then press ENTER.
  5. When the Windows installation is located, the following instructions are displayed:
    Add installation to boot list? (Yes/No/All)
    [Type Y in response to this message.]

    Enter Load Identifier:
    [This is the name of the operating system. Type Windows XP Professional or Windows XP Home Edition.]

    Enter OS Load options:
    [Leave this field blank, and then press ENTER].
    After you perform the preceding steps, restart the computer, and then select the first item on the boot menu. This should allow Windows XP to start normally.

    After Windows XP has successfully loaded, the Boot.ini can be modified to remove the incorrect entry.
For more information about how to edit the Boot.ini file, click the following article number to view the article in the Microsoft Knowledge Base:

Performed method 2 but still seeing error message on reboot.

Attempting to fix bad sectors CHKDSK /r from recovery console and then I'll retry Method 2.
This also failed.  Rebuilding the machine.

Monday, April 30, 2012

Creating a linked server

Example specifying a specific name for the linked server:


/****** Object:  LinkedServer [MYLINKEDSERVER]    Script Date: 04/30/2012 09:24:54 ******/
EXEC master.dbo.sp_addlinkedserver @server = N'MYLINKEDSERVER'
                                 , @srvproduct=N'KINDEL-G-W7'
                                 , @provider=N'SQLNCLI'
                                 , @datasrc=N'10.245.8.103'
 /* For security reasons the linked server 
             remote logins password is changed with ######## 
    @server - The name assigned to the linked server definition.
    @srvproduct - Name or IP Address of server sql instance where the linked server                  is being added to.    
    @datasrc - Name or IP Address of remote server sql instance
Sample query: SELECT * FROM MYLINKEDSERVER.<database name>.dbo.<table Name> */ EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'MYLINKEDSERVER'
                                    ,@useself=N'False'
                                    ,@locallogin=NULL
                                    ,@rmtuser=N'sa'
                                    ,@rmtpassword='########'

GO

Tuesday, April 24, 2012

SQL Server 2008/2008R2 Intellisense

I've noticed that SQL server 2008 intellisense frequently stops working/refreshing the database tree nodes immediately after I have just added a new new table.  


In MS SQL Server Management Studio:
Edit menu -> Intellisense -> Refresh Local Cache (CTRL+Shift+R)

Convert a DateTime to a BIGINT or 64bit Integer

Okay, so I have a stored procedure that is creating an Timestamp from a date field using: CONVERT(BIGINT,[UpdatedDate])

So I'm using Linq, lambda expressions, IList to parse and filter the resultset from SQL server.
I need all of the records affected within the last 90 days but the UpdatedDate is transformed into a BIGINT
from 20.12-04-04 05:37:28.717 to 41001.  Now I needed a way to convert DateTime.Now into a 64bit integer.  Convert.ToInt64(DateTime.Now) throws a typeException error.

The Answer: DateTime.Now.ToOADate():
 DateTime.Now {4/24/2012 8:49:19 AM}
DateTime.Now.ToOADate() 41023.367304120373

Thursday, April 19, 2012

Using Merge to Update or Insert single row of data

Example of recent procedure I wrote to either update an existing row or insert a new row.
Table has the same structure as MembershipEmailFormat the table variable.

Found it easiest to create a table variable to be the source in the Using clause.  I realize that the main purpose of Merge statements really are merging muliple rows between two tables.  My use case is that I need to insert a new email address for a user or modify and existing email address.

CREATE PROCEDURE [dbo].[usp_user_merge_emailformat]
        @UserID UNIQUEIDENTIFIER,
        @Email varchar(256),
        @UseHTML bit
AS
BEGIN
    --SELECT @UserID='04EFF187-AEAC-408E-9FA8-284B31890FBD',
    --       @Email='gkindel@merge.com',
    --       @UseHTML=0
       
    DECLARE @temp TABLE
    (
            UserID UNIQUEIDENTIFIER,
            Email varchar(256),
            HtmlFormat bit
    )       

    INSERT INTO @temp(UserID,Email, HtmlFormat)
    Values(@UserID,@Email,@UseHTML)
           
    SELECT * FROM @temp    

    MERGE dbo.MembershipEmailFormat as t
    USING @temp AS s
    ON (t.UserID = s.UserID and t.Email = s.Email)
    WHEN MATCHED THEN UPDATE SET t.HtmlFormat = s.HtmlFormat
    WHEN NOT MATCHED THEN INSERT VALUES(s.UserID,s.Email,s.HtmlFormat);
END    

Tuesday, April 10, 2012

PayPal Store Front

Last time I edited my StoreFront was 2008!

http://storefront.paypallabs.com/
This is the Store Front gadget configuration pages.
Create / edit gadget with list of products.
Update and republish, copy html and add as a HTML element in Blogger template.


Friday, April 6, 2012

Create a new Guid in T-SQL

Use NewID() function.


1SELECT newid()
Result:
11CA040D5-53D6-4E7C-8D36-1000C8B03A91

Saturday, March 24, 2012

Installling NSIS 2.46


I'm busy setting up builds of DRC 3.0 on a new Windows 7 64bit workstation using VS2010 and NSIS 2.46

Always an intertesting adventure setting up a new Development workstation especially when you didn't take the time to document your setup.

Setting up NSIS 2.46 on Windows 7 64 bit
  1.   Run nsis-2.46-setup.exe
  2.  Run Venis setup VenisIX225.exe
    1.  Run Venix, click register menu
    2.  Add name and license.
    3.   First time running Venix, Use file menu to open Nsi script directly.  After that, Windows will open Venix when double-clicking on script file.  (Not sure why this does work w/o first running Venix right after install.
  3.   Add Plugins
    1.        Registry
      1.  Copy Include to NSIS\Include
      2.  Copy Example to NSIS\Examples
      3. Copy Plugin to NSIS\Plugins
Venis IX 2.2.5



Thursday, March 22, 2012

Things I learned this week

At work, current project is nearing release as the calendar nears the end of the quarter.

(A random thought, think of the money that could be saved in business would adopt trimesters instead of quarters...  public companies would only have 3 releases for numbers + annual statements to be made.  I think the savings in worthless red tape would be significant.  What the percent different between 1/3 vs 1/4?)

Some of these items I already knew but relearned them this week again.
  • Scope_Identity() works locally not via a linked server.
  • spIDs are also local for processes running and should not be correlated over a linked server.
  • Always and I mean always specify country ID when looking up State codes even if you current design only supports US only. 
  • When you get a new 64bit development machine, build properties on a C# project specifying CPU type is no longer insignificant.
  • Many people are happily using 64bit version of Windows 7 and don't even realize it.
  • SysWOW64 is still the dumbest name for a folder to date.
  • There is more to life than work.
  • I enjoy singing more than I would have ever guessed.
  • Lunch is my favorite part of the weekday.



Friday, February 24, 2012

I love stackoverflow.com

I needed a query to use Rank() row counters within a Group

Here it is:  http://stackoverflow.com/questions/1139719/sql-server-query-for-rank-rownumber-and-groupings

Here is my query and resultset


SELECT
    Rank() over (Partition by EncounterID Order by EncounterID, RefPhysID)+1 as ranks
    ,EncounterID
    , RefPhysID
FROM 
    tbEncountersCourtesyCopies
Group By
    EncounterID, RefPhysID, RefPhysOfficeID 
Order by
    ranks asc

ranks    EncounterID    RefPhysID
2        9              1022
2        12             1095
2        18             91
3        12             1279


Monday, February 20, 2012

Windows 7 Activation Problems.

I've been struggling with Windows 7 license issues.  After hard drive changes (not the boot drive), one of my test machines keeps have the Windows 7 Pro license invalidated.  This is odd since I thought I had a real license key for the machine and not one of those tech-net, it expires in a year licenses but I'm not really sure anymore.

My solution was to purchase a discounted license from a non-Microsoft website whose claimed to be a Genuine MS Partner.  Initially the key I received did not work but I used the following steps and I was able to activate Windows 7 Pro using automated phone registry.

From http://social.microsoft.com/Forums/en-US/genuinewindows7/thread/dd8f477a-07a7-42b5-b5bb-5079a5fd8140


First off, try these alternate steps to change the product key
1)    Click the Start button
2)    Type: slui.exe 3 and hit the Enter key
3)    Type in the Product key from the sticker on your computer
4)    Click the Next button.
5)    You will be asked if want to Activate, click ok
6)    It will attempt to Activate by the internet and will return an Invalid Key error (this is ok, continue to step 7)
7)    Click the Start button
8)    Type: slui.exe 4 and hit the Enter key
9)    Select your location in the drop down menu and click the Next button
10) The next screen provides the number to call to Activate by Phone
If that doesn't work, try these steps that will recreate Windows 7's Licensing Store.  When it recreates the file, Windows will need to repopulate it with Licensing Information so will ask you to enter the Product Key and to Activate (use the Activate by Phone method)
1) Open an Internet Browser
2) Type %windir%\system32 into the browser address bar.
3) Find the file CMD.exe
4) Right-Click on CMD.exe and select 'Run as Administrator'
5) Type: net stop sppsvc  (it may ask you if you are sure, select yes)
6) Type: cd %windir%\ServiceProfiles\NetworkService\AppData\Roaming\Microsoft\SoftwareProtectionPlatform
7) Type: rename tokens.dat tokens.bar
8) Type: slui
9) After a couple of seconds Windows Activation dialog will appear. You may be asked to re-activate and/or re-enter your product key.


Lastly, if neither set of steps resolves the problem, download and run the Genuine Diagnostics tool (MGADiag.exe) at this linkhttp://go.microsoft.com/fwlink/?linkid=52012. Click "Continue", click the "Copy" button then “Paste” the report into a reply message in this thread.