Tuesday, March 27, 2012

Learning to Code - C# Hello World

Links:
Learning to Code - Introduction

Start

Open Notepad on your windows operating system of choice.
Type the following code into your Notepad window:

 class HelloWorld  
 {  
   static void Main()  
   {  
     System.Console.WriteLine("Hello, world!");  
   }  
 }  

Now save this file as HelloWorld.cs

Now you have a "program" it is a really simple console application that will show the words "Hello, world!" when it is run.  But the first thing we have to do is to convert the human readable file (Specifically in the Microsoft .Net C# language) to one that can be read and executed by a machine (Binary Code, think lots or 1's and 0's strung together).  This is called "Compiling" and the program that is used to compile this is called CSC.exe.

The compiler can be found at the following location(s) on your computer depending on what version of the .Net compiler is installed :

The x86 locations are...
C:\Windows\Microsoft.NET\Framework\v2.0.50727
C:\Windows\Microsoft.NET\Framework\v3.5
C:\Windows\Microsoft.NET\Framework\v4.0.30319

The 64bit locations are...

C:\Windows\Microsoft.NET\Framework64\v2.0.50727
C:\Windows\Microsoft.NET\Framework64\v3.5
C:\Windows\Microsoft.NET\Framework64\v4.0.30319

Open up either a DOS window, or if your a power user you can open a Powershell window.
Change to the directory where your HelloWorld.cs file is, for example on my machine I would type:

CD D:\jp\prj\HelloWorld

Then call the csc.exe file at the location you chose with one paramater which is the name of your C# Helloworld file for example:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe HelloWorld.cs

This will compile your file into a file that can be executed from your DOS console. It will be named HelloWorld.exe

Now you can run your first C# console application


HelloWorld.exe
Hello, world!

Next we will examine just what that code is doing.









Monday, March 26, 2012

Learning to code - Introduction

So you want to be a 1337 HAX0R with MAD SK1LZ? (Whats this?)

Want to create a simple family website with simple tools?

Want to create a more complex website with more advanced tools?

Want a deeper understanding about what "Programming" or "Coding" is all about?

Well hopefully this series of articles will help you out.

The Approach

Personally, I am fairly new to blogging so I will be learning new blogging tricks along the way.  When I want to learn some new technology, I appreciate simple blogs with lots of examples so this is how I will approach teaching how to write code.  However I will intersperse the article with helpful links that may explain a given subject in more detail for those that wish it.  But if you just want your computer to be able to "do stuff" you should be able to get up and running in no time.

For these articles, the most accessible language and environment I can think of is the Microsoft .Net platform. It supports multiple languages and can be used with a simple Notepad editor to start creating programs right away.  It also has a free version of its IDE (Integrated Development Environment) that can be downloaded and take writing software to the next level.

Lets Start - Hello World

The classic program that all software developers use when starting a new language is "Hello World". This is simply getting enough knowledge of a new language that you can output the words "Hello World" to the computer screen. (Geeky History of HelloWorld)  (HelloWorld in a variety of Languages)

I want to follow the C# coding path

I want to follow the HTML (web sites) coding path

Thursday, October 20, 2011

Javascript JQuery passing events weirdness

Back in the day I wrote some pretty cool Javascript, but I got more into a middle layer software world and had not touched UI for a long time.

In the meantime Javascript came a long way with the new JQuery language so I thought I would take a crack at it.
So I found this site http://docs.jquery.com/How_jQuery_Works and started to work on the example and I immediately discovered something that I am sure is understandable, but I don't understand how it works.

The example given is this:

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
     });
   </script>
 </body>
 </html>


Which worked but I immediately wanted to refactor those anonymous functions to make it more readable so I created this:


function ClickIt()
{
$("a").click(AlertIt(event));

}

function AlertIt(event)
{
alert("As you can see, the link no longer took you to jquery.com");
event.preventDefault();
}

$(document).ready(ClickIt());


The problem was the when I ran the new version the "event" object passed into the AlertIt(event) was null.  Odd, so after much playing around I finally discovered that I needed to call AlertIt  with no paramaters and it worked. So why is that ?  Feel free to comment.



Thursday, June 9, 2011

Protect your site from Phishing and Pharming

These are suggestions for developers to protect against phishing attacks that may use your site to target your users for phising attacks.

Phishing attacks are a social engineering attack that targets the users of your site. At its simplest the phisher will send an email to your users that appears to be from you, and requests they click on a link that will take them to another site, that looks like your site, and asks them to update or verify their personal information. Once that is collected the user then becomes a victim of identity theft by the criminals.

So the main defense involves educating the users on how they can avoid being tricked into responding to these type of attacks.

On your website
Policies
Create a policy that defines precisely what you will do and NOT do during communications with the user. Make the policy as easy to understand as possible, no legalese.  Make sure the policy is easily visible on the website.

Encourage end users to install and update anti-virus and anti-spyware software.

Make it easy for users to report possible scams involving your site through a feedback forum or email address.
Place a warning on website that you will prosecute phishers and scammers.
Provide help to users that have been victimized.

Coding
Do not use popups and inform the user you will never use a popup and to inform you if it happens.
Prevent sites that may frame your site
Use the TARGET directive to create a new window
<a href=”http://www.yoursite.com/” target=”_top”>
Check the DOM model to reject any access from frames.
Do a referrer check on your web page, this will stop links from emails.
Protect your site from XSS attacks.
Always use the domain name and not ip addresses for your site.
Disable unused accounts.


Protect your data
Don't store or display data that is not needed by the user.
Don't ever display the password.
Validate that data is internally consistent, for example a florida address with a california zip could be a warning sign..
Setup daily access limits for unverified customers.
Consider only shipping to a users billing address.
When updateing an email or physical address, send notification to both addresses.
Never display passwords, use a one time limited password to recover passwords.
Consider emailing activity logs to user to confirm valid activity.
Limit transactions from a single user in a given time period.
Check for multiple addresses using the same shipping address.








Forensics
Use watermarked images and change the watermarks often, this can give a time frame of when the image was used on a phishing site.
Investigate web logs for spiders that go through all you web pages and images, note ip addresses.




Communicating with users
In emails dont provide links to click if possible, and explain to the users that they should type the url into their browser.
Use consistent branding and a single url for users to access to reduce confusion.
Always inform them that you will never ask for any personal information through email.
Reduce information in email, direct users to your website where you can provide the information.
Consider text only email rather than HTML
Don't use shortened url services, always use our base URL
Don't send email that an account lockout has occurred, simply provide email or phone number for them to call. Or even better phone the person directly.


More information:

Anti-phishing working group
http://www.antiphishing.org/

Thursday, May 12, 2011

Debug Powershell C# Cmdlet

Now that I am able to create and load a C# Cmdlet as a module, the next thing I want is the ability to debug it.

Originally I wanted to be able to press the F5 key in Visual Studio and have it bring up a powershell window and attach to the process automatically.  That would have been elegant.  Alas it was not to be.  Turns out if you add a powershell.exe command to the Project Properties - Debug - Start External Program line you get this error.

External Program Path:
The external program cannot be found. Please enter a valid executable file.

You can actually ignore that message and attempt a debug anyways. I don't advice it because what happens is it sends the command to a non-interactive cmd.exe shell and sits and waits for a response, hanging the Visual Studio instance.

Next I tried this little gem:
cmd /c "start "newshell" powershell.exe  -nologo -noexit -noprofile"

This actually pops up an interactive shell and starts powershell.exe, but once again Visual Studio hangs until you exit that shell, never going into debug mode.

I tried the same thing using the post build events, with the same results.

So, to make things at least a little easier I created this powershell script to copy my files from my Visual Studio environment to the modules directory, then import the module into a new instance of Powershell.


Copy-Item C:\prj\PowershellCmdlets\PowershellCmdlets\bin\Debug\*.* "C:\Documents and Settings\<yourlogin>\My Documents\WindowsPowershell\modules\PowershellCmdlets" -Force
Import-Module PowershellCmdlets

So to debug:

  • Execute a build in Visual Studio
  • From a  Powershell window run the script file which will start up a fresh Powershell instance within the existing Powershell instance.
  • In Visual Studio debug menu attach to the Powershell process.
  • Set breakpoints in your code.
  • Go back to you Powershell window and run one of your new modules cmdlets.
  • Voila, your break point should be hit and you can begin debugging.


Once your done debugging you can go to the powershell window and type 'exit' and that will kill the thread and return Visual Studio to edit mode.

I will update this post if I find something more elegant.

Wednesday, May 11, 2011

Write your first powershell Cmdlet in C#

Once I get more organized in this whole blogging world, I may take a moment to elucidate my reasoning for even wanting to write a Powershell cmdlet in C#. But for now, I just wasted a morning in learning how to do it, and the internet just wasn't very helpful on getting started (including MSDN). So, for now I will just dive into the steps I eventually found, with the hope that someone else can use this information.

What I used:
 Powershell v2.0
Windows XP
Visual Studio 2010
Windows SDK

If you don't have the Windows SDK, it is apparently the way you can get the libraries for Powershell that will be needed for your Cmdlet project. So download and install that first. I used the version 6 flavor, though there are newer ones for more modern OS's than XP.

Fire up Visual Studio.
Create a new Class Library for C#. I named it PowershellCmdlet.

Replace the code with this sample from MSDN


using System.Management.Automation;
 
namespace PowershellCmdlets
{
 // Declare the class as a cmdlet and specify and 
 // appropriate verb and noun for the cmdlet name.
 [Cmdlet(VerbsCommunications.Send, "Greeting")]
 public class SendGreetingCommand : Cmdlet
 {
  // Declare the parameters for the cmdlet.
  [Parameter(Mandatory = true)]
  public string Name
  {
   get { return name; }
   set { name = value; }
  }
  private string name;
 
  // Overide the ProcessRecord method to process
  // the supplied user name and write out a 
  // greeting to the user by calling the WriteObject
  // method.
  protected override void ProcessRecord()
  {
   WriteObject("Hello " + name + "!");
  }
 }
}


You will notice that the only "using" statement is for "System.Management.Automation.  This is not part of the built in System.Management namespace so you will need to add in one of the libraries that got installed with the Windows SDK. It should install to:

C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll

(The keen observer will see that the folder name is "v1.0". What the? turns out there are a lot of places in the Powershell v2.0 folders are still labeled v1.0. Comment if you know why please.)

Add a reference to that library to your project.

Now you should be able to build your project and generate a .dll file of the same name.

Now where I wasted a bunch of time. I have a C# Cmdlet for Powershell, but how do I get the darn thing loaded.  It appears the old school way was to create a PSSnapin. Which required creating some more code to handle the "snapping in" and dealt with registry settings etc. Sub-Optimal. What I wanted was the new Modules for Powershell v2.0, which supposedly would make it a breeze! For a nice explanation of Modules vs. Snap-ins check out Thomas Lee's blog.

So here is the trick to releasing your shiny new .dll file as a Cmdlet Module.

First understand that their is a default path where Powershell will search for modules that is stored in the PSModules environment variable:


PS > get-content Env:\PSModulePath
C:\Documents and Settings\<yourlogin>\My Documents\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\M
odules\

(You can add your own directory to this path, but for simplicity I just left the defaults.)


It turns out that on a fresh install of Powershell you may not actually have a "Modules" sub-directory, if that is the case, go create one in your user directory at the end of the path given above.

Next create a subdirectory under your Modules directory, and here is the trick, Name it the same name as  your .dll file.  If the folder is a different name from your .dll name, it seems to not recognize the Module.

Now you need to create a Manifest Module for your .dll file. Powershell 2.0 provides a tool for this called "New-ModuleManifest".
Start this command with a path to your new PowershellCmdlet subdirectory you just created. It will ask you a series of cryptic questions that don't make much sense at first. Here is how you should answer them.


PS > New-ModuleManifest "C:\Documents and Settings\<yourlogin>\My Documents\WindowsPowershell\modules\PowershellCmdlets\something.psd1"

cmdlet New-ModuleManifest at command pipeline position 1

Supply values for the following parameters:
NestedModules[0]:
Author: Your Name
CompanyName: Your Company
Copyright: 2011
ModuleToProcess: PowershellCmdlets.dll
Description:
TypesToProcess[0]:
FormatsToProcess[0]:
RequiredAssemblies[0]:
FileList[0]:

PS >


Now it is supposed to be as simple as using the Import-Module command like so:


PS > import-module PowershellCmdlets
Import-Module : Could not load file or assembly 'file:///C:\Documents and Settings\<yourlogin>\My Documents\WindowsPowerShell\Modules\PowershellCmdlets\PowershellCmdlets.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
At line:1 char:14
+ import-module <<<<  PowershellCmdlets
    + CategoryInfo          : NotSpecified: (:) [Import-Module], BadImageFormatException
    + FullyQualifiedErrorId : System.BadImageFormatException,Microsoft.PowerShell.Commands.ImportModuleCommand


What the?  I then went back to my Visual Studio and retargeted my solution to .net 3.5, then .net 2.0 with the same results.  Finally I found this article, which while not directly related to my problem actually provided the solution.

When Powershell runs it can read from a Powershell.exe.config file that can adjust some of the settings Powershell uses.  So to solve the "newer runtime" problem we can create a Powershell.exe.config file in the following directory:

C:\WINDOWS\system32\WindowsPowerShell\v1.0

With these contents:


<?xml version="1.0"?>
<configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0.30319"/>
        <supportedRuntime version="v2.0.50727"/>
    </startup>
</configuration>


Restart your Powershell instance and you should be able to execute the following commands to run you Cmdlet.


PS > import-module PowershellCmdlets -verbose
VERBOSE: Loading module from path 'C:\Documents and Settings\<yourlogin>\My Documents\WindowsPowerShell\Modules\PowershellCmdlets\PowershellCmdlets.dll'.
VERBOSE: Importing cmdlet 'Send-Greeting'.

PS > Send-Greeting -name Bob
Hello Bob!




Hope this helps.













MSDN Starting point for cmdlet creation.