Monday, December 31, 2012

n+1 problems in stored procedures

It is probably best to NOT call a function making a select statement for each record returned from a select statement in a sproc. Try to instead query the other data in one select to a temp table and join the table onto the select that otherwise needed to reach out to the function.

This will delete a stored procedure...

DROP PROC [dbo].[Whatever]

Friday, December 28, 2012

reach out to the master page in a web forms ASP.NET project

This is one way to go fishing for a method in the master page from the page using it:

char foo = (Page.Master as Bar).ContentSeparator

 
 

The master page itself would start out like so:

public partial class Bar : System.Web.UI.MasterPage
{
   protected void Page_Init(object sender, EventArgs e)
   {

Thursday, December 27, 2012

using IIS with VS2010

You will need to run Visual Studio as administrator to open web sites right out of IIS in Visual Studio 2010.

If a desktop has two DVI ports on it, it may randomize which of the two ports it decides to broadcast the signal out of.

This sort of pain point fits with the challenging day I've been having. I have a sore throat, there was a fire at the hotel, and it snowed heavily...

Update: The fire turned out to be a prank. Someone sprayed a fire extinguisher all over the fourth floor and then pulled the fire alarm. I was fooled!

System.Web is the namespace for HttpContext.Current

Dim context As HttpContext = HttpContext.Current

...didn't "want to take" just now so I replaced it with...

Dim context As HttpContext = Web.HttpContext.Current

...and referenced the System.Web namespace at the top of the file like so...

Imports System.Web

...and yes, this is VB script :(

There will be a setting somewhere on a monitor for toggling between DVI cable input and VGA cable input.

This informed me and I verified.

Wednesday, December 26, 2012

sniff the name of your computer in C#

In C# System.Net.Dns.GetHostName() returns the "DNS host name of the local computer" which may be thought of less verbosely as "the computer name" and should be the same thing you get by typing hostname at a command prompt. A use of System.Net.Dns.GetHostName() will be flagged by HP Fortify as a "Often Misused: Authentication" error.

Monday, December 24, 2012

Server.Transfer has a preserveForm parameter that is not trivial methinks.

preserveForm is the second parameter in a Server.Transfer call and it is pretty important. I think the code I gave here is pretty bad and should really look like this (note the true value in black for passing the HttpContext variables):

HttpContext CurrContext = HttpContext.Current;
CurrContext.Items.Add("q", q.Value);
Server.Transfer("/search/default.aspx",
true);

 
 

...cannot be like so which won't fly...

Server.Transfer("/search/default.aspx?q=" + q.Value, true);

 
 

Fish variables back out on the other side of the leap like so:

HttpContext CurrContext = HttpContext.Current;
var whatever = CurrContext.Items["q"].ToString()

 
 

While we are at it, here is the same thing in VB (per this):

Dim context As HttpContext = HttpContext.Current
context.Items.Add("q", q.Value)
Server.Transfer("/search/default.aspx",
True)

 
 

Go fishing for the variables in VB:

Dim context As HttpContext = HttpContext.Current
If Not context.Items("q") Is Nothing Then
   Dim q As String = CType(context.Items("q"), String)
End If

 
 

This also shows off VB script object-to-string casting and some if logic. (I've been doing some VB script lately in plumbing in old code.) preserveForm should be true to "preserve the QueryString and Form collections" according to this Visual Studio intellisense helper, so I am betting I need it to preserve the HttpContext I just created.

Share photos on twitter with Twitpic

Set cookie paths and domains.

This restricts a cookie to a subdomain, I think:

HttpContext.Current.Request.Cookies["foo"].Domain = "support.example.com";

 
 

This restricts a cookie to a folder:

HttpContext.Current.Request.Cookies["foo"].Path = "/support";

 
 

Note: A single forward slash for the path setting will encompass the whole of the site. This is will cause an "Overly Broad Path" in a HP Fortify scan.

HttpUtility.HtmlEncode

The way to parrot @Html.Encode on the C# side is with HttpUtility.HtmlEncode(foo) according to this. I think Server.HtmlEncode(foo) in the VB equivalent.

 
 

An update: I think HttpUtility.HtmlEncode may also be the way to go in VB as Server.HtmlEncode seems to force a conversion to a string. I think I might be able to get away with wrapping a DataSet in HttpUtility.HtmlEncode in both C# and VB. More soon.

beat XSS attacks with Razor

This suggests that one may sanitize stuff that bubbles up to a view against being XSS vulnerable like so in Razor markup:

@Html.Encode(Model.MyMultilineTextField).Replace(@"\n", "<br />")

Sunday, December 23, 2012

OWASP

https://www.owasp.org/index.php/Main_Page and https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project were given to me as other links to look into in the name of beating Fortify bugs. OWASP seems to stand for "The Open Web Application Security Project."

Saturday, December 22, 2012

The Hobbit

I have just returned from seeing the movie The Hobbit. Overall, it was so-so, but most rewarding was some initial study on why one should go on a reckless and dangerous adventure. The adventure might yield rewards, but is the risk really worth stepping outside of what you know and where you feel safe? If you think about it pragmatically you might conclude that such an adventure is unwise. The stronger counterarguments to contrary were articulated pretty well however:
  1. Think of what you wanted to do when you were young and how badly you wanted it then.
  2. Think of the regret you will carry from passing on the opportunity.
The second point is illustrated subtly and cleverly in the film. It was what I was most impressed with. Later in the movie, the selfish do-it-for-yourself thing seems to give way for the hero into a sense of obligation and a want for wanting to help others. I've experienced this. I'll start something for one reason and then, hip deep into the thing, the reason to continue is... different. I think most of us can read parallels of our professional choices and dreams onto some of The Hobbit's content. I saw the rationale for many of my own recent post-Headspring adventures.

Friday, December 21, 2012

an XSLT example

This suggests that one apply an XSLT (another thing I learned about from C# 4.0 in a Nutshell) transformation like so:

XPathDocument myXPathDoc = new XPathDocument(myXmlPath);
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load(myXsltPath);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

 
 

This is something else I found which has this XML...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="tutorials.xsl"?>
<tutorials>
   <tutorial>
      <name>XML Tutorial</name>
      <url>http://www.quackit.com/xml/tutorial</url>
   </tutorial>
   <tutorial>
      <name>HTML Tutorial</name>
      <url>http://www.quackit.com/html/tutorial</url>
   </tutorial>
</tutorials>

 
 

...and suggests that it may be used with this:

<xsl:template match="tutorial">
   <span class="tutorial-name"><xsl:value-of select="name"/></span>
   <span class="tutorial-url"><xsl:value-of select="url"/></span>
</xsl:template>

get rid of adware at Internet Explorer in Windows 7

You are going to have to get rid of some of your plugins and this is a good cheatsheet on how to do so.

  1. Go to: Start > All Programs > Accessories > System Tools > Internet Explorer (No Add-ons)
  2. Click on: "Manage Add-ons"
  3. Start disabling the bad stuff.

VB script style try/catch/finally

isAsset = False
Try
   If content_data.AssetData.Id = "" Then
      isAsset = False
   Else
      isAsset = True
   End If
Catch
   Throw New System.Exception("Whatever")
Finally
   somethingElse = "Whatever"
End Try

where T : Whatever

More fun from "C# 4.0 in a Nutshell": In the second line below, the ourSound string will end up set to "PuRRRRRRRRRRRRR" and the way in which it happens is pretty interesting...

Purrer<Tiger> purrer = new Purrer<Tiger>();
string ourSound = purrer.Purr();

 
 

OK, this is our Purrer class...

using System;
using System.Reflection;
public class Purrer<T> where T : Cat
{
   public Purrer()
   {
   }
   
   public string Purr()
   {
      Type type = typeof (T);
      var infos = type.GetMethods();
      MethodInfo info = infos[0];
      Cat cat = (Cat)type.GetConstructor(new Type[] { }).Invoke(new object[] { });
      return "Pu" + info.Invoke((object)cat, new object[] { }).ToString();
   }
}


 
 

Above, please note:

  1. T cannot just be anything as is the norm. A contract restrains T to Cat.
  2. On the second to last line the constructor of T is invoked to make a T-shaped Cat.
  3. On the last line the first method in the new T-shaped Cat is invoked with no parameters and an assumed return value is cast to a string.
  4. That is all of the magic there is!

 
 

The Cat object looks like so...

public class Cat
{
   public Cat()
   {
   }
   
   public virtual string Growl()
   {
      return "rrrrrr";
   }
}

 
 

The Tiger child of Cat overrides the Growl method to make the growl "louder" for a Tiger. The magic of this pattern happens in overriding. You may guarantee that FooProcessor will understand the methods of Foo while also being able to accomodate the variations of Foo's children.

public class Tiger : Cat
{
   public Tiger()
   {
   }
   
   public override string Growl()
   {
      return "RRRRRRRRRRRRR";
   }
}

 
 

 
 

Man, this posting is so nice and fluffy and cat-related. What's wrong with me?

don't swallow exceptions

catch (InvalidCastException e)
{
   throw (e);
}

Thursday, December 20, 2012

cast a wider net when fishing for server variables when switching from Response.Redirect to Server.Transfer

long asset_id = 0;
HttpContext CurrContext = HttpContext.Current;
if (CurrContext.Items["id"] != null)
{
   asset_id = Convert.ToInt64(Request.QueryString["id"]);
}
if (! (Request.QueryString["id"] == null))
{
   asset_id = Convert.ToInt64(Request.QueryString["id"]);
}

When trying to replace Response.Redirect with Server.Transfer you will need to handle get variables a different way.

http://shawpnendu.blogspot.com/2010/12/using-servertransfer-how-to-pass-values.html seems to have a pretty good article on it. The write up suggests that this...

Response.Redirect("/search/default.aspx?q=" + q.Value);

 
 

...is most appropriately replaced like so...

HttpContext CurrContext = HttpContext.Current;
CurrContext.Items.Add("q", q.Value);
Server.Transfer("/search/default.aspx");

 
 

...and NOT like so which won't fly...

Server.Transfer("/search/default.aspx?q=" + q.Value);

 
 

Fish variables back out on the other side of the leap like so:

HttpContext CurrContext = HttpContext.Current;
var whatever = CurrContext.Items["q"].ToString()

 
 

This way isn't going to cut it in this implementation.

HP Fortify Challenges

Oh boy, if it takes three hours to run a Fortify scan it is really hard to validate that your fixes are really fixes. (see: this) :( All you can do is guess how to fix a problem and then let a scan run overnight. I am just this morning realizing that I've solved no problems yesterday whatsoever. Today, I guess I will try to fix one bug in each category of bugs and then see if I have any successes. I found http://stackoverflow.com/tags/fortify-software/hot online which seems to be a pretty good cheatsheet for how to fix up some things. Server.Transfer("/whatever.aspx") is perhaps superior to the approach of using Response.Redirect("/whatever.aspx") but I won't really know for sure until tomorrow after a scan runs overnight.

I was really wrong...

These two blog postings from yesterday are dead wrong:

  1. http://tom-jaeschke.blogspot.com/2012/12/the-magic-of-stringformat-in-fixing.html
  2. http://tom-jaeschke.blogspot.com/2012/12/for-avoiding-xss-attacks-fortify-may.html

Wednesday, December 19, 2012

an underscore lets you wrap to a new line in VB Script

I learned something new about Visual Basic today. Sigh.

The magic of String.Format in fixing Fortify bugs.

lblFileBlurb.Text = String.Format("{0}",fileBlurb);

...is likely better than this...

lblFileBlurb.Text = fileBlurb;

(chuckle)

For avoiding XSS attacks Fortify may prefer that you associate a sproc directly with a database connection.

cmd = New SqlCommand("sp_Whatever", conn)
cmd.CommandType = CommandType.StoredProcedure

...may be superior to...

cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = ("sp_Whatever")

 
 

Note:

  1. XSS is an acryonym for Cross-Site Scripting.
  2. Please forgive the VB Script. :(

filtering HP Fortify

Share photos on twitter with Twitpic

Tabs in Fortify, both in the Audit Workbench and the Visual Studio 2010 plugin, will denote the issues which are:

  1. Critical
  2. High
  3. Medium
  4. Low
  5. and a collection of the four above
Share photos on twitter with Twitpic

Right-click on any one issue and pick "Generate Filter..." to generate a filter across all of the Fortify issues. For an Ektron project, it is going to be best to exclude errors of the "Workarea" and "widgets" folders as fixing such errors would be tinkering with Ektron itself. There is a separate filters pane one may bring up too.

Share photos on twitter with Twitpic

Monday, December 17, 2012

empower Remote Desktop connections at a PC running Windows 7

Control Panel > User Accounts > Give other users access to this computer ...is where one empowers the ability for another to remote desktop in. When connecting, just connect to the name of the PC on the LAN at hand.

crawl XML from with MSSQL

This touches on XMLCOL which is some awful way to crawl XML from with MSSQL. As example:

SELECT XMLCOL.query('user/name').value('.','NVARCHAR(20)') as name

 
 

This is going to look in the "user" node for the "name" node.

backup and restore a MSSQL database

Per this:

  1. Back-up a database in MSSQL:

    Right-click on a database in MSSQL Management Studio Express 2008 and pick "Back Up..." under "Tasks." You will need to specify something like this...

    C:\Program Files\Microsoft SQL Server\WHATEVER\MSSQL\Backup\

    ...for the where-to-back-up-to setting.
     

  2. Tasks > Restore > Database... is where one should restore from

of WinForms state and Fortify

The web forms concepts of Session and ViewState do not apply to WinForms. Here, just keep stuff in a private or even public field. Do not try to store state in a control as say the text of a Label however or HP Fortify will slap your hand.

Sunday, December 16, 2012

NVARCHAR(max) in MSSQL is flagged as Insecure Randomness in HP Fortify.

I found this in Googling which suggests that such a type can contain up to 1,073,741,822 characters. Many other threads suggest that the maximum length is 4000. This is one of them. Hmmm...

I suppose I'm going to use NVARCHAR(4000) everywhere NVARCHAR(max) is used to best the HP Fortify error.

Saturday, December 15, 2012

Insecure Randomness

Yes, this is an HP Fortify bug!

Random foo = new Random();
int bar = foo.Next(42);

 
 

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/javascript/insecure_randomness.html is a write up on why it rotten for random password generation stuff. I found http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx online which suggests using Membership.GeneratePassword to beat the problem. The example in the link is:

string password = Membership.GeneratePassword(12, 1);

 
 

12 is the length and 1 is the MINIMUM number of characters that are not alphanumeric.

Guids for passwords?

This suggests that repurposing a Guid is a great way to craft a random password of strictly alphanumeric characters. Well, I tested the theory today and am pleased with what came to be. The code in black below could have just been left out, but I kept it for readability.

using System;
using System.Collections.Generic;
using System.Linq;
namespace EQL.Members
{
   public static class PasswordGenerator
   {
      public static string Generate(int lengthOfPassword)
      {
         Guid guid = Guid.NewGuid();
         string secret = guid.ToString().Replace("-", "");
         if (lengthOfPassword > 1 && lengthOfPassword < 32) secret = secret.Substring(0,
               lengthOfPassword);
         return RandomizeTheCaseOnLetters(secret);
      }
      
      private static string RandomizeTheCaseOnLetters(string secret)
      {
         char[] characterArray = secret.ToCharArray();
         char[] arrayForRandomizing = Guid.NewGuid().ToString().Replace("-",
               "").ToCharArray();
         List<bool> listForRandomizing = arrayForRandomizing.Select(c => ((int) c%2 == 0)
               
? true : false).ToList();
         int counter = 0;
         bool containsNumber = false;
         bool containsLetter = false;
         while (counter < characterArray.Length)
         {
            char character = characterArray[counter];
            int characterEncoding =
(int)character;
            if (characterEncoding > 49)
            {
               containsLetter = true;
               string stringifiedCharacter = character.ToString();
               if (listForRandomizing[counter])
               {
                  stringifiedCharacter = stringifiedCharacter.ToUpper();
               } else {
                  stringifiedCharacter = stringifiedCharacter.ToLower();
               }
               characterArray[counter] = stringifiedCharacter.ToCharArray()[0];
            } else {
               containsNumber = true;
            }
            counter++;
         }
         characterArray = EnsurePresenceOfBothOneDigitAndOneLetter(characterArray,
               containsNumber, containsLetter);
         return characterArray.Aggregate("", (current, c) => current + c.ToString());
      }
      
      private static char[] EnsurePresenceOfBothOneDigitAndOneLetter(char[]
            characterArray, bool containsNumber, bool containsLetter)
      {
         if (!containsNumber)
         {
            characterArray[0] = '0';
         }
         if (!containsLetter)
         {
            characterArray[0] = 'a';
         }
         return characterArray;
      }
   }
}

 
 

My tests:

using System.Text.RegularExpressions;
using EQL.Members;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EQL.Tests
{
   [TestClass]
   public class PasswordGeneratorTests
   {
      [TestMethod]
      public void GuidToAlphanumericPasswordConversionBehavesAsExpected()
      {
         string password = PasswordGenerator.Generate(31);
         Assert.AreEqual(password.Length, 31);
         Assert.IsTrue(Regex.IsMatch(password, @"^[A-Za-z0-9]+$"));
      }
      
      [TestMethod]
      public void PasswordsAlwaysHaveAtLeastOneNumberAndAtLeastOneLetter()
      {
         string password = PasswordGenerator.Generate(2);
         char[] characterArray = password.ToCharArray();
         int counter = 0;
         bool containsNumber = false;
         bool containsLetter = false;
         while (counter < characterArray.Length)
         {
            char character = characterArray[counter];
            int characterEncoding =
(int)character;
            if (characterEncoding > 49)
            {
               containsLetter = true;
            } else {
               containsNumber = true;
            }
            counter++;
         }
         Assert.IsTrue(containsNumber);
         Assert.IsTrue(containsLetter);
      }
   }
}

cast char type variables to their numeric encodings and back again

This test passes.

[TestMethod]
public void Whatever()
{
   char x = (char)77;
   int y = (int) x;
   Assert.AreEqual("M", x.ToString());
   Assert.AreEqual(77, y);
}

Alphanumeric characters are in the three ASCII ranges of 48-57, 65-90, and 97-122.

characters 0-1 equal integers 48-57
characters A-Z equal integers 65-90
characters a-z equal integers 97-122

Should I use using in tandem with try/catch instead of nesting a try/catch inside of a try/catch?

This suggests that the try/catch should probably sit within the using. I felt the temptation today to nest a try/catch in a try/catch and then I did some Googling and talked myself out of it.

In the name of using SqlParameter in an HP Fortify-friendly manner...

SqlParameter foo = bar.Parameters.AddWithValue("@Baz", qux);

...is copacetic while this isn't...

SqlParameter foo = bar.Parameters.Add("@Baz", SqlDbType.NVarChar, 42);
foo.Value = qux;

Friday, December 14, 2012

Make someone else God in SharePoint just like you.

Assuming you're an administrator...
  1. pick Site Permissions from Site Actions
  2. click Grant Permissions
  3. find a new God at the Select Users box by email address

maxOccurs

When fixing a "Unbounded Occurrences" bug for HP Fortify, there may be a place in a .xsd for a dataset (let's say the database is Foo.xsd) which looks likes so...

<xs:choice minOccurs="0" maxOccurs="unbounded">

 
 

...and must become like so:

<xs:choice minOccurs="0" maxOccurs="79228162514264337593543950335">

 
 

Where did 79228162514264337593543950335 come from? It came from a line in the Designer file which gives away the type used for maxOccurs:

any1.MaxOccurs = decimal.MaxValue;

 
 

Get a number from an appropriate type.

The "File Separator" HP Fortify bug is REALLY easy to hack around.

This posting is bad. It was pointed out to me that the following is a better way to address this:

string unfinishedPath = "C:\\\\fun";
string attachmentPath = unfinishedPath + "\\";
if (Directory.Exists(attachmentPath))
{
   Directory.Delete(attachmentPath, true);
}

 
 

...and you can get around it like so:

string unfinishedPath = "C:\\\\fun";
string attachmentPath = unfinishedPath;
if (Directory.Exists(String.Format("{0}{1}",attachmentPath,
      Path.DirectorySeparatorChar.ToString())))
{
   Directory.Delete(String.Format("{0}{1}",attachmentPath,
         Path.DirectorySeparatorChar.ToString()));
}

Thursday, December 13, 2012

hosts file

C:\Windows\System32\drivers\etc\ is where your host file lives. Run notepad as administrator and then open this file to force DNS to resolve for a particular A record to a particular IP (like, for example, the local IP of your laptop) like so:

10.152.6.108   support.tom.com

 
 

This is often vital for prepping web sites to run locally in IIS.

Delete the just-in-time junk files to get around those ASP.NET errors that are tied to your profile without being tied to a file.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files is where the Just-In-Time compiler for ASP.NET caches temporary files. Delete these files to get around goofy Ektron errors like this:

Share photos on twitter with Twitpic

Change the framework version of ASP.NET for an IIS web site at the Application Pools.

Duh.

Share photos on twitter with Twitpic

The "File Separator" HP Fortify bug is easy to hack around.

Something like this will give you the error:

string unfinishedPath = "C:\\\\fun";
string attachmentPath = unfinishedPath + "\\";
if (Directory.Exists(attachmentPath))
{
   Directory.Delete(attachmentPath, true);
}

 
 

...and you can get around it like so:

string unfinishedPath = "C:\\\\fun";
char seperator = (char)92;
List<char> characters = unfinishedPath.ToList();
characters.Add(seperator);
string attachmentPath = characters.Aggregate("", (current, c) => current + c.ToString());
if (Directory.Exists(attachmentPath))
{
   Directory.Delete(attachmentPath, true);
}

inner/nested partial classes

Another way inner/nested classes may be used is as partials. This would allow for the extension of a second partial elsewhere by the class wrapping the partial class. Maybe the Poop class does not normally hold a getsetter for IsCarryingParasites and it is extended for the Cat class like so:

namespace Whatever
{
   public class Cat {
      public Poop Poo { get; set; }
      public partial class Poop
      {
         public bool IsCarryingParasites { get; set; }
      }
   }
}

Wednesday, December 12, 2012

inner/nested

http://stackoverflow.com/questions/804453/using-inner-classes-in-c-sharp and http://stackoverflow.com/questions/454218/private-inner-classes-in-c-sharp-why-arent-they-used-more-often discuss how to approach inner/nested classes. These are a way to ensure a one-off helper class, for example an enum, is only used by the only class that needs it. This is pretty ghetto and breaks with a good convention of having one file for every one class (save for perhaps having editable partials separate from not-to-be-fucked-with code-generated classes) where the file has the save name as the class it holds.

Install configuration-specific config files

http://msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx offers that you may right-click on a Web.config file and select "Add Config Transforms" to make configuration-specific Web.config files for each variation in the Configuration Manager. If you add the "Configuration Transform" extension out of the Online Gallery at the Extension Manager under the Tools menu. (This is also where one finds jQuery grid.)

Ektron needs IIS to run locally.

Set up a site in IIS and then open the Fortify project as a web site in Visual Studio to run it.

SSIS cannot do SFTP by itself.

http://winscp.net/eng/docs/guide_ssis (WinSCP) might be a workaround.

SSIS has a file watcher.

The watcher should let you know if new files are introduced to a directory it is crawling.

xpcommandshell is one way to do File IO manhandling from within a sproc

Enough said.

MakeLogic's Tail

...is a window that reports lines added to a log to you as they are added.

HP Fortify for VS2012

...will be released in February of 2013

how files are nested below other files in a .csproj

Open a .csproj file in notepad to example the underlying XML...

   <ItemGroup>
      <Content Include="Web.Debug.config">
         <DependentUpon>Web.config</DependentUpon>
      </Content>
   </ItemGroup>
   <ItemGroup>
      <Content Include="Web.PROD.config">
         <DependentUpon>Web.config</DependentUpon>
      </Content>
   </ItemGroup>
   <ItemGroup>
      <Content Include="Web.DIT.config">
         <DependentUpon>Web.config</DependentUpon>
      </Content>
   </ItemGroup>
   <ItemGroup>
      <Content Include="Web.SIT.config">
         <DependentUpon>Web.config</DependentUpon>
      </Content>
   </ItemGroup>

Ctrl-K followed by Ctrl-C and Ctrl-E followed by Ctrl-U are the standard Visual Studio shortcuts for commenting and uncommenting code respectively.

I kinda prefer the Resharper way: Ctrl with forward slash for both

Tuesday, December 11, 2012

DBAmp sprocs

DBAmp does much of what it does via stored procedures and any MSSQL database that is going to have SalesForce data translated into it is going to need to have the DBAmp sprocs spliced into it.

fixing an HP Fortify bug to do with XmlReader

This was causing a "High" error in an HP Fortify scan.

XmlReader reader = XmlReader.Create(serializationStream);

 
 

I fixed it might this.

XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
XmlReader reader = XmlReader.Create(serializationStream, xmlReaderSettings);

 
 

I didn't even have to do something of substance like this.

XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(serializationStream, xmlReaderSettings);

HP Fortify Details pane in Visual Studio 2010

View > Other Windows > Fortify SCA Windows ...is where one may go to get the Fortify Details pane in Visual Studio 2010.

some SSIS notes

SQL Server Data Tools (SSDT) is the new BIDS. http://www.develop.com/sqlservertwelvedatatools is an article I found on it online suggesting that it may be downloaded at http://msdn.microsoft.com/en-us/data/hh297027. We were curious to see if WinSCP will "jive" with the new SSIS of Visual Studio 2012's SSDT. The first step in making a 2012 SSIS package is to create an Integration Services project per http://msdn.microsoft.com/en-us/library/ms141178.aspx and http://msdn.microsoft.com/en-us/library/ms137823.aspx touches on how to do so a little bit. http://msdn.microsoft.com/en-us/library/ms138028.aspx suggests that the Integration Services solution is only available via Microsoft SQL Server 2012 which may be downloaded at http://www.microsoft.com/en-us/download/details.aspx?id=29062.

to upgrade a project's Framework in Visual Studio

right-click on a project, pick "Properties," and then change the "Target Framework" at the "Application" tab

Does anyone know...

  1. Is there a way to grab a version number out of the compiler via C#?
  2. Does one have to have a copy of MSSQL Server 2012 installed to make an Integration Services solution in SSDT?

Monday, December 10, 2012

change the name of a navigation link in SharePoint (not the HDRI way)

Site Actions > Site Settings > Site libraries and lists > Customize "Whatever" > Title, description and navigation is not where I went at HDRI for making a change to the name of a link at the sidenav, but things were not the norm there. Julia Reynolds had SharePoint navigation administerable in a different manner.

Boost memory allocation for HP Fortify.

We have found the need to boost memory allocation for HP Fortify on our 32-bit systems. We can push it up to 1300 MB. The place where one finds this setting is pretty strange. From the "HP Fortify" menu in Visual Studio, one should go to "Options ..." which will spawn the "Fortify Options ..." dialog box. There should be three menu items of sorts at the left:

  1. Server Settings
  2. Rulepack Configuration
  3. Project Settings
Share photos on twitter with Twitpic

The last option will not appear if you do not have an solution open, and it is the last option that you will need. (You'll have to change the setting for every solution if every solution needs more memory allocation.) At the "Analysis Configuration" tab there will be a drop down for "SQL Type:" which should be changed to "TSQL." The 1300 value should be entered to the right of the drop down. It's a confusing locale for the setting.

get appSettings variable from app.config in a Console application

string whatever = (string)System.Configuration.ConfigurationManager.AppSettings["whatever"];

...is newer than...

string whatever = (string)System.Configuration.ConfigurationSettings.AppSettings["whatever"];

helpful links for creating Debug and Release config files

  1. http://blogs.msdn.com/b/webdev/archive/2009/05/04/web-deployment-web-config-transformation.aspx
  2. http://stackoverflow.com/questions/5811305/web-config-debug-release

There is danger in renaming an ASP.NET app.config file.

If you rename the app.config in a console app, you may really confuse your application. I had to run "Clean Solution" (right-click on the ASP.NET Solution and pick "Clean Solution") to get DataSet which should have been functioning properly to function properly on the other side of a the other side of swapping of app.config with another file called app.Debug.config with a renaming. Comedically, I was trying in vain to manually doctor up a DataSet today to fix an inability for the code to run. It was an interesting refresher on DataSets...

  1. make a dataset
  2. drag tables from the Server Explorer into the DataSet
  3. right-click on one of the tables drug into the DataSet and pick "View Code" to make a partial class

Friday, December 7, 2012

grab a ConnectionString out of the Web.config like so

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
namespace MyApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         string connectionString = System.Configuration.ConfigurationManager.
               ConnectionStrings["DefaultConnection"].ConnectionString;
         SqlConnection connection = new SqlConnection(@connectionString);
         SqlCommand command = new SqlCommand();
         SqlDataAdapter adapter = new SqlDataAdapter();
         DataSet dataSet = new DataSet();
         string query = "SELECT * FROM UserRole";
         command.CommandText = query;
         command.CommandType = CommandType.Text;
         command.Connection = connection;
         adapter.SelectCommand = command;
         adapter.Fill(dataSet);
         List<string> roleNames = new List<string>();
         foreach (DataRow dataRow in dataSet.Tables[0].Rows)
               roleNames.Add(dataRow[7].ToString());
         return View(roleNames);
      }
   }
}

 
 

...Bonus: I use my model like so in a view...

@model List<string>
<h2>roles out of UserRole</h2>
<ol>
   @foreach (var role in Model)
   {
      <li>@role</li>
   }
</ol>

how to encrypt the passwords in a Web.config file

So far, the best resource I've found online for a how to-guide for how to encrypt the passwords in a Web.config file has suggested, like every other blog posting, that one has to put some stuff in the top of the Web.config to make it work. However, most of the other postings I fought my way through suggested additions that just wouldn't compile!. The golden posting I saw here which now seems offline. Maybe it will return. At any rate, it suggests/suggested you start off a Web.config file like this:

<configuration>
   <configSections>
      <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.
                  Data.Configuration.DatabaseSettings,
                  Microsoft.Practices.EnterpriseLibrary.Data,
                  Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
   </configSections>
   <dataConfiguration defaultDatabase="MyDatabase">
      <providerMappings>
         <add databaseType="Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase,
                  Microsoft.Practices.EnterpriseLibrary.Data, Version=3.0.0.0, Culture=neutral,
                  PublicKeyToken=b03f5f7f11d50a3a" name="System.Data.SqlClient" />
      </providerMappings>
   </dataConfiguration>

 
 

Next, navigate to the folder holding a Web.config to encrypt with "Developer Command Prompt for VS2012" and then type something like this:

aspnet_regiis -pef connectionStrings . -prov DataProtectionConfigurationProvider

 
 

Sometimes the Web.config file will be redacted and sometimes a better copy of the Web.config file will be made one folder up. I'm sure there is a sane explanation for this, but I don't really care. Use appSettings here in lieu of connectionStrings to encrypt the appSettings section of the Web.config instead of the connectionStrings section. Also rename app.config to Web.config to make this trick work for app.config. You will then need to rename Web.config back to app.config. In the end, something like this:

<connectionStrings>
   <add name="DefaultConnection" providerName="System.Data.SqlClient"
         connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;
         Persist Security Info=True;User ID=foo;Password=bar" />
</connectionStrings>

 
 

...will become something like this:

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
   <EncryptedData>
      <CipherData>
         <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+
               sBAAAAD9WbcMcef0Onv4S9BkyQ5wQAAAACAAAAAAADZgAAwAAAABAA
               AAAKHRL+
               D1aOMuO5KNEwR9WcAAAAAASAAACgAAAAEAAAAHQKZ9aFFT7H
               SVTrvXdIzVgQAgAA9fg86jjjqufpllVijvAQvsbCIAYevcnasJ4LWh6YApj+
               nzlVQEMo4yAxgeIr4UzPxTH2LgPE89C/I+ZY6jG73q5y6Eb4T1g+STPPA+
               ezZW2e3hdFx9aT15RjPfzuS5yQjuhlg/ehuVrqqMkBLWGI4AmFDORgzWTb47Q
               O4xfmGV6HWh48Wd7GTaV1rrZ1sFCOfJ5I5l8jIRv4BESGzMTDVAr6clmblYET2
               6kXhTvcosw5G71caQO4s1Mp89RatzwxAmWeYbwAYgPp1y/
               Y/0/dN2AsBRyVr1m+
               wX+2K0Y1YIczcGaHJ/DSJnNAMCkjHL+QOpaf5i6n72zlsylPI7hF5qmBTVxpZP
               KgCsBsCNdvFVsTeAFBEJLJKaZq2K/tmJjMbxIBTy1hD+
               D0KsMT2P55zbBAKkYBMsqYl6ux+U3rczgdZM8bL8HglxZOcAC/
               GOqm04NmT36ctM/5qF48VPh3Jk2RYPJqXe+z/
               xH7OO1vya4BHPvKKunkvMqh9fsMhxI3A/
               IwqVkFCsWgkksnegzqAcBwuz5m6OhRiwam8oDBmbTULIZ8St8y+
               vDgbdQU2jCFhUULGe0tQf0tehA+lDOL1htSJ0GI0ypdfpZhEDej7YxxEDUnwJI
               66MFJIJmNAk7VjJzwFMDPf3DeTqwSXxKFfjKRLZctuWmBsfs9b2B7QS62K5TJ
               vVRnQfQriPHDGacKFAAAAAEv8R/zsGee0gAm1oPQy3v8rwrw</CipherValue>
      </CipherData>
   </EncryptedData>
</connectionStrings>

Thursday, December 6, 2012

install IIS at Windows 7

Control Panel > Programs > Turn Windows features on and off ...is where one may turn on IIS in Windows 7.

shared folders in Windows 7

To share a folder in Windows 7, right-click on the folder and pick "Share with" before finally giving a name for the share.

Wednesday, December 5, 2012

make a .bat file

Following this I made a .bat file by putting the following in a .txt file:

@echo off
echo Comparing two files: %1 with %2
   
if not exist %1 goto File1NotFound
if not exist %2 goto File2NotFound
   
fc %1 %2
if %ERRORLEVEL%==0 GOTO NoCopy
   
echo Files are not the same. Copying %1 over %2
copy %1 %2 /y & goto END
   
:NoCopy
echo Files are the same. Did nothing
goto END
   
:File1NotFound
echo %1 not found.
goto END
   
:File2NotFound
copy %1 %2 /y
goto END
   
:END
echo Done.

 
 

I then just renamed the .txt to .bat.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319 is where msbuild seemed to end up installed from after I downloaded msbuild from here.

msbuild FooFoo.sln /p:Configuration=Deploy is the command for making a Deploy-specific Web.config.

to get Ektron to compile...

Be sure the UI is set as the startup project (duh) and build the dependent projects first.

Crowdfunding

See: http://www.kickstarter.com/ and http://www.indiegogo.com/ may be worth a look.

make a database project

  1. make a "SQL Server 2008 Server Project" in Visual Studio
  2. right-click on the project that is made in the Solution Explorer and pick "Import Objects and Settings..."
  3. on the other side of a simple wizard, you will "import" a selected database, so to speak, as SQL scripts
  4. use HP Fortify Audit Workbench to run Fortify scans of these... I can't get the projects to compile

Tuesday, December 4, 2012

Scott Hanselman on multiple configuration files

http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx is a Scott Hanselman blog posting on having multiple configuration files for different environment. I am partway into playing around with this now. Did you know that you may hold CTRL and then click/drag a file in the Solution Explorer in Visual Studio to make a copy of a file? Hanselman's blog postings seem a lot like his talks. We are swept away on a bunch of wild tangents and we always somehow end up feeling better off for it instead of distracted.

EVERYTHING!

Everything is a freeware app that allows you to search directories for matches against partial file names in a manner much quicker than the clunky crawling of Windows Explorer. You have to be logged in to have it running as a service at a laptop or server. It will not show creation dates which is annoying. Perhaps there is a not-free version that is more feature-rich.

-2,147,483,648 to 2,147,483,647 is the range for Int32 types

Imagine raising two to the power of 32 and then making the 4294967296 you get "evenly" straddle the number zero.

decimal.MaxValue

decimal.MinValue and decimal.MaxValue are gonna giveya
-79228162514264337593543950335 and 79228162514264337593543950335 respectively.

unbounded maxOccurs

A Fortify bug for ASP.NET: An .xsd (dataset) file has maxOccurs="unbounded" in it. If this pops up, try giving the maximum decimal type value in lieu of "unbounded" which is: 79228162514264337593543950335

signing certificate error

This says the "Unable to find manifest signing certificate in the certificate store." error may be solved by going to the "Signing" tab in the project's properties and then clicking on any of these buttons:

  1. Select from Store...
  2. Select from File...
  3. Create Test Certificate...

create a new build configuration

At "Configuration Manager" you may create a build configuration beyond the canned "Build" and "Release" configurations that come with a project.

Share photos on twitter with Twitpic
  1. Select the option for a new configuration.
    Share photos on twitter with Twitpic
  2. Give the new configuration a name
    Share photos on twitter with Twitpic
Share photos on twitter with Twitpic

Monday, December 3, 2012

I seemed to lose the controls for forwarding an email from within Outlook.

It turned out that I had minimized the ribbon.

Tealeaf and Cast Iron

Cast Iron is a form of web analytics. Tealeaf is also a form of analytics, but it will moreover allows one to retrace the steps through a site that a user took to navigate to a particular outcome. If a 404 error is reported by Tealeaf, one will be able to tell how the user who got the error navigated the given site to be able to "find" the error.

Sunday, December 2, 2012

cubes

This suggests a data cube will collect star schema data by three dimensions. Example: product, years the product was sold in, markets the product was sold in

one of your solution's "projects" could be a compiled .dll

Of ASP.NET: When opening a new solution and ramping up on its ways, check to see if some of the references seem to be custom in-house libraries. I've seen a few solutions now wherein something I would have kept as a project within the solution has in fact been tucked away into a referenced .dll. I'm not in love with this sort of thing personally as it just makes the whole of the "solution" harder to understand, search, and navigate, but it is something I've run into twice now.