You may be think that writing your first kernel module is going to be a long, painful, grueling task, but really it is only slightly harder than writing your first program, Hello World!, in C or C++.
Lets break this into nice easy steps.
Prerequisites
It is assumed you have installed FreeBSD already. If not, follow the instructions below with one change: Install the FreeBSD source during the “Choose Distribution” section.
A FreeBSD kernel module is written in C. This is going to be only a slightly harder than writing hello world in C. We are going to create a single text file with a .c extension and put some C code in it.
Create a folder to hold you project. I used this directory:
/usr/home/jared/code/kernel/hwm
Create the file to hold your code. I named my file this:
hello_world_kmod.c
Edit the file with you favorite editor, vi, vim, emac, ee. I used easy editor (ee):
ee hello_world_kmod.c
Add the following code to the file.I have broken the code of the simplest kernel module into four parts or steps:
Add four required #include statements.
Create the kernel load/unload event handler.
Create a struct to name the module and point to the event handler function.
Call the DECLARE_MODULE macro.
/*
* Step 1 - Add the four needed libraries to include
*/
#include <sys/param.h>
#include <sys/module.h>
#include <sys/kernel.h>
#include <sys/systm.h>
/*
* Step 2 - Handle the load/unload event
*/
static int EventHandler(struct module *inModule, int inEvent, void *inArg)
{
// Set return code to 0
int returnCode = 0;
switch (inEvent)
{
case MOD_LOAD:
uprintf("Hello, World! \n");
break;
case MOD_UNLOAD:
uprintf("Bye, World! \n");
break;
default:
returnCode = EOPNOTSUPP;
break;
}
return(returnCode);
}
/*
* Step 3 - Name the module and the event hander function
* This is done using a struct of type moduledata_T
*/
static moduledata_t moduleData = {
"hello_world_kmod", // Module Name
EventHandler, // Event handler function name
NULL // Extra data
};
/*
* Step 4 - Declare the module
* This is done with the DECLARE_MODULE macro
*/
DECLARE_MODULE(hello_world_kmod, moduleData, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
Save and close the file.
Step 2 – Create a Makefile
Creating a Makefile to build a kernel module is quite easy because almost all the work is done for you. FreeBSD has a file that you include, /usr/src/share/mk/bsd.kmod.mk, that does most of the work for you and all you have to do is include it.
In the same directory where you put your .c file, create a new text file called Makefile.
There are three basic parts to the kernel module Makefile:
Module name
Source files
Include of bsd.kmod.mk
# Module Name
KMOD = hello_world_kmod
# Source files
SRCS = hello_world_kmod.c
# Include <bsd.kmod.mk>
.include <bsd.kmod.mk>
Save and close the file.
Step 3 – Run make to build the module
In the command prompt, in the directory where you have created your code and make file, run make.
Loading and unloading kernel modules must be done as root. If you have sudo installed, use it, otherwise install it (Configuring sudo on FreeBSD) or su to root.
Use kldload to load the module and kldunload to unload the module.
Since XAML is going to be used in Windows 8 as well, it is not going away any time in the next decade. Also, declarative UI will improve in the future, not disappear. So there is job security in this.
You may have already done this when reading the previous post, if not do so now.
Go to https://github.com/jozefizso/SystemWrapper and download the latest dll or the latest source or add the SystemWrapper.Interfaces and SystemWrapper.Wrappers By jozef.izso
Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory).
Add references to these two dlls in your release code.
Add a reference only to SystemInterface.dll in your Unit Test project.
Step 2 – Change your code to use Interfaces and Wrappers
Ok, so here we are going to start with an example. Here is an object that I wrote myself that uses the registry to check on which versions of .NET Framework are installed. It is currently using Registry and RegistryKey directly.
using System;
using Microsoft.Win32;
namespace SystemInfo
{
public class DotNetFramework
{
#region Constant members
public const string REGPATH_DOTNET11_VERSION = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v1.1.4322";
public const string REGPATH_DOTNET20_VERSION = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v2.0.50727";
public const string REGPATH_DOTNET30_VERSION = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0";
public const string REGPATH_DOTNET35_VERSION = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
public const string REGPATH_DOTNET40_VERSION_CLIENT = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client";
public const string REGPATH_DOTNET40_VERSION = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full";
#endregion
#region Properties
/// <summary>
/// This returns true if .NET 4 Full is installed.
/// </summary>
public bool FoundDotNet4
{
get { return HasDotNetFramework(REGPATH_DOTNET40_VERSION, 0); }
}
/// <summary>
/// This returns true if .NET 4 Client is installed.
/// </summary>
public bool FoundDotNet4Client
{
get { return HasDotNetFramework(REGPATH_DOTNET40_VERSION_CLIENT, 0); }
}
/// <summary>
/// This returns true if .NET 3.5 with SP1 is installed.
/// </summary>
public bool FoundDotNet35SP1
{
get { return HasDotNetFramework(REGPATH_DOTNET35_VERSION, 1); }
}
/// <summary>
/// This returns true if .NET 3.5 is installed.
/// </summary>
public bool FoundDotNet35
{
get { return HasDotNetFramework(REGPATH_DOTNET35_VERSION, 0); }
}
/// <summary>
/// This returns true if .NET 3.0 with SP2 is installed.
/// </summary>
public bool FoundDotNet30SP2
{
get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 2); }
}
/// <summary>
/// This returns true if .NET 3.0 with SP1 is installed.
/// </summary>
public bool FoundDotNet30SP1
{
get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 1); }
}
/// <summary>
/// This returns true if .NET 3.0 is installed.
/// </summary>
public bool FoundDotNet30
{
get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 0); }
}
/// <summary>
/// This returns true if .NET 2.0 with SP2 is installed.
/// </summary>
public bool FoundDotNet20SP2
{
get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 2); }
}
/// <summary>
/// This returns true if .NET 2.0 with SP1 is installed.
/// </summary>
public bool FoundDotNet20SP1
{
get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 1); }
}
/// <summary>
/// This returns true if .NET 2.0 is installed.
/// </summary>
public bool FoundDotNet20
{
get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 0); }
}
/// <summary>
/// This returns true if .NET 1.1 is installed.
/// </summary>
public bool FoundDotNet11
{
get { return HasDotNetFramework(REGPATH_DOTNET11_VERSION, 0); }
}
#endregion
public bool HasDotNetFramework(string dotNetRegPath, int expectedServicePack)
{
bool retVal = false;
try
{
RegistryKey localKey = Registry.LocalMachine.OpenSubKey(dotNetRegPath);
if (localKey != null)
{
int? isInstalled = localKey.GetValue("Install") as int?;
if (isInstalled != null)
{
if (isInstalled == 1)
{
if (expectedServicePack > 0)
{
if ((int)localKey.GetValue("SP") >= expectedServicePack)
retVal = true;
}
else
{
retVal = true;
}
}
}
}
return retVal;
}
catch
{
return retVal;
}
}
}
}
Find any place in your code where you use touch the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32.
Hint: Use the search feature in your IDE.
Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code,
SystemInterface.Microsoft.Win32
SystemWrapper.Microsoft.Win32In the DotNetFramework.cs file above, there is a using statement to Microsoft.Win32. Our new using statements will be:
using System;
using SystemInterface.Microsoft.Win32;
using SystemWrapper.Microsoft.Win32;
For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects.In the DotNetFramework.cs file, there is only one single line that needs to change to do this, line 113.
This line…
IRegistryKey localKey = new RegistryWrap().LocalMachine.OpenSubKey(dotNetRegPath);
Step 3 – Allow for replacing the IRegistryKey objects
Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked.
This is done for you to some extent for registry access by using the IAccessTheRegistry interface.
Implementing the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. You can add the following code to the DotNetFramework object.
#region IAccessTheRegistry Members
public IRegistryKey BaseKey
{
get
{
if (null == _BaseKey)
_BaseKey = new RegistryWrap().LocalMachine;
return _BaseKey;
}
} private IRegistryKey _BaseKey;
public void ChangeBaseKey(IRegistryKey inBaseKey)
{
_BaseKey = inBaseKey;
}
#endregion
Note: Notice that the Property is read only. Instead of enabling the set ability, a function is created to allow you to change the IRegistryKey instance. This is by design and keeps you from making a mistake such as BaseKey = BaseKey.OpenSubkey(“…”) and replacing the BaseKey.
Note: You may want to look into the “Factory” design pattern.
Step 4 – Download and Reference RhinoMocks in your Unit Test
You may have already done this when reading the previous post, if not do so now.
In this step you need to download RhinoMocks and reference it with your Unit Test project. If you don’t have a test project, create one. Your release project won’t need it.
Unit Tests should be fast and simple and they should not touch the system. What we mean by touching the system is any code that actually changes the file system or registry of the build system that runs the Unit Tests. Also any code that touches a remote system such as a database or a web server as these remote system should not have to exist during a Unit Test.
Question: What if you are using some one elses code, such as standard C# libraries in the System or Microsoft namespaces?
Answer: Imagine you need to unit test code that touches the registry. You must do the following steps:
Create an interface for accessing the registry that matches Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (and you may have to create an interfaces for each object they need as well).
Create a wrapper that wraps the Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (again, you have to create a wrapper for each objects they need as well).
Change your production code to use the interfaces and the wrappers instead of using the system code. For example, if dealing with the Registry this involves Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey directly.Don’t use these objects directly, instead you use these objects:
SystemInterface.Microsoft.Win32.IRegistry
SystemInterface.Microsoft.Win32.IRegistryKey
SystemWrapper.Microsoft.Win32.RegistryWrap
SystemWrapper.Microsoft.Win32.RegistryKeyWrap
Provide a method in your production code for replacing anywhere you use IRegistry or IRegistryKey with any object that implements the interface.
In your Unit Test, mock any neededIRegistry and IRegistryKey objects.
However, since Microsoft hasn’t done this, you have to do it yourself. But all of this probably takes more time than your project will allow you to take, so I am going to try to get you there faster.
Step 1 and Step 2 are done for you, all you have to do is download the dll or source from here: http://SystemWrapper.codeplex.com
Step 3 and 4 are not done for you but there are examples in the SystemWrapper project.
Step 5 can be done extremely quickly with a free (BSD Licensed) tool called RhinoMocks.
So the new steps become these:
Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory).
Add references to these two dlls in your release code.
Add a reference only to SystemInterface.dll in your Unit Test project.
Step 2 – Change your code to use Interfaces and Wrappers
Find any place in your code where it touches the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32.
Hint: Use the search feature in your IDE.
Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code,
SystemInterface.Microsoft.Win32
SystemWrapper.Microsoft.Win32
For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects.
Step 3 – Allow for replacing the Interface-based objects
Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked.
Here is an example of how to do this when mocking a RegistryKey object using IRegistryKey.
Implement the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. Here is a sample implementation that uses lazy property injection:
#region IAccessTheRegistry Members
public IRegistryKey BaseKey
{
get { return _BaseKey ?? (_BaseKey = new RegistryWrap().LocalMachine); }
internal set { _BaseKey value; }
} private IRegistryKey _BaseKey;
#endregion
Notice that the setter is internal. This is because unit tests can usually access an internal method with InternalsVisibleTo. The internal set is hidden for code not in the same assembly and not included in InternalsVisibleTo.
Note: You may want to look into the “Factory” design pattern.
Step 4 – Download and Reference RhinoMocks in your Unit Test
In this step you need to download RhinoMocks and reference it with your Unit Test project. Your release project won’t need it.
This MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out.
MS = Microsoft
V = Visual
C = C++
R = Redistributable
If you create a C++ project in Visual Studio 2011, this file is probably needed.
MSVCR110D.dll
The MSVCR110D.dll is almost the same file only the D at the end stands for Debug. This file has debugging enabled.
Why the error?
Ok, so recently I switched to Visual Studio 2011. I had a C++ application that worked perfectly in Visual Studio 2008. Once I compiled it with Visual Studio 2011 and ran it on a clean 2008 server (fully patched but otherwise clean), it failed to run with the following error.
TestWin32.exe – System Error
The program can’t start because MSVCR110.dll is missing from your computer. Try reinstalling the program to fix this problem.
Here is the screen shot:
The same things happens with the debug version of the file, only it is a the debug version of the same DLL as noted by the fact that the DLL name ends with D.
Autorun – System Error
The program can’t start because MSVCR110.dll is missing from your computer. Try reinstalling the program to fix this problem.
The screen shot is identical except for the D in the dll name.
I create a new project in Visual Studio 2011 using the project type of C++ Win32 Project and without making a single change to the default project, I built the file and tested it on my clean machine and the same issue occurred.
So obviously that is not acceptable. It seems like this should just not happen by default, but unfortunately it does.
Solution
It was actually really easy to resolve for my one project.
Here is what I did.
You can solve this any of the following ways:
Statically link to the dll files so they are compiled into my executable instead of referenced as separate dll files.
Included the dll in the same directory as the exe (I actually didn’t try this but I assume it would work).
Forced everyone to install the VC++ Runtime Redistributable before running the app.
The first option seems the most stable and robust and easiest for a single executable. So that is the one I am going to use.
The second option doesn’t really make sense to me and I would probably never do it. Maybe if I had dozens of executable files that all required the same DLL and I didn’t have an installer, and I wanted to conserve size, which probably wouldn’t happen for me since I am pretty good at creating a quick installer. Though you might be in this a situation.
The third option would make sense if I was planning on running my executable after an install. During the install I could include the VC++ Runtime Redistributable and all would be fine.
Statically Linking the DLLs
Make sure you resolve it for both Release and Debug. The steps are slightly different.
Release
In Visual Studio, I went to the project Properties.
I changed my Configuration to Release.
I went under Configuration Properties | C/C++ | Code Generation
Look at the Runtime Library setting. It is set to this: Multi-threaded DLL (/MD)
Change it to this: Multi-threaded (/MT)
Rebuild.
Debug
Almost exactly the same as release.
In Visual Studio, I went to the project Properties.
I changed my Configuration to Debug.
I went under Configuration Properties | C/C++ | Code Generation
Look at the Runtime Library setting. It is set to this: Multi-threaded Debug DLL (/MDd)
Change it to this: Multi-threaded Debug (/MTd)
Rebuild the debug
It might be a good idea for me to figure out how to change the project so when I create a new project of this type, those settings are the default.
Security is important and there is a lot to learn. I am reading the book Security in Computing and trying to memorize the RSA algorithm.
Prerequisite Math Knowledge
You must understand the following mathematical principles to understand this algorithm and if you don’t understand these principles, look them up first (I had to look up the last one, the Euler totient function, as I had never heard of it):
Exponentials
Prime numbers
Prime factorization
Greatest Common Denominator (GCD)
Modular arithmetic
Euler totient function
This is also going to have development in mind, so you maybe should also understand: binary, char, bits, ascii, UTF-8, etc..
The book is good. However, it can be quite annoying for me when it shows algorithms using one character variables. This may be the mathematical way but I prefer to use a developer style where variables are named clearly. I need to make sure I understand how RSA works so I am going to write about it.
Here is an example of how they use just one character:
The RSA algorithm uses two keys, d and e, which work in pairs, for decryption and encryption, respectively. A plaintext message P is encrypted to ciphertext C by
C = Pe mod n
The plaintext is recovered by
P = Cd mod n
Because of symmetry in modular arithmetic, encryption and decryption are mutual inverses and commutative. Therefore,
P = Cd mod n = (Pe)d mod n = (Pd)e mod n
This relationship means that one can apply the encrypting transformation and then the decrypting one, or the one followed by the encrypting one.1
I would never write code this way and looking at this, it might leave one who is not an expert wondering what do the variables P, C, d, e, n represent again? And is there a reason P, C are capitalized and d, e, n are lower case? Lets rewrite these with nice developer variable names where the name comments itself based on the what it really is. In the quoted text above each variable is defined clearly except what “mod n” really represents, I had to read on to determine this. Also, where to get the values for each variable is not defined, again, I had to read on to determine this, and this led to more equations to add to the list.These are the equations, in order
Equation List
ProductOfPrime1Prime2 = Prime1 * Prime2
Totient = (Prime1 – 1) * (Prime2 -1)
(Totient * AnyInteger) + 1 = 1 mod Totient
EncryptPrime * DecryptPrime = 1 mod Totient
EncryptPrime * DecryptPrime = (Totient * AnyInteger) + 1 where (Totient * AnyInteger) + 1 has exactly prime factors
CipherText = PlainTextEncryptPrime mod ProductOfPrime1Prime2
PlainText = CiphertextDecryptPrime mod ProductOfPrime1Prime2
PlainText = CiphertextDecryptPrime mod ProductOfPrime1Prime2 = (PlainTextEncryptPrime)DecryptPrime mod ProductOfPrime1Prime2 = (PlainTextDecryptPrime)EncryptPrime mod n
Some of the values above you get to “choose” or if you were writing this algorithm in code, you would probably not “choose” so much as generate the value at random. So if we get to choose, then lets learn how to choose.
Step 1 – Choose two prime numbers, Prime1 and Prime2 to get the ProductOfPrime1Prime2 variable
So our Equation List above starts out with this simple math equation:
Prime1 * Prime2 = ProductOfPrime1Prime2
Ok, so where do you get Prime1 and Prime2 to start? You simply choose the two primes yourself. Find or generate or a list of primes and choose two. Close your eyes and point or pull them out of a hat. It doesn’t matter just choose two primes numbers.
Of course, there are recommendations for choosing primes in production use. Here are a two basic recommendations:
Prime1 and Prime2 should be very large prime numbers, at minimum 100 digits long but as larger is more secure and less efficient.
Prime 1 and Prime2 should not be the same prime number
Even though Prime1 and Prime2 should be very large, I want to keep this simple, so for example’s sake, let’s use two primes from the list below:
So we can choose any primes we want, for this example, I will choose these two: 19, 31
ProductOfPrime1Prime2 = Prime1 * Prime2
ProductOfPrime1Prime2 = 19 * 31 = 589
ProductOfPrime1Prime2 = 589
Step 2 – Find the Totient of ProductOfPrime1Prime2
You can search the internet and to study to figure out how to get the totient, but it is pretty easy to get. Totient uses a weird symbol that looks like the letter ‘p’ but is not:
So I guess you don’t really need to know about a totient, you can just trust me, right? Ok, mathematicians are big on proofs and not just trusting someone so, go learn totient. Anyway, the equation is as simple as this:
Totient = (Prime1 -1) * (Prime2 – 1)
So we already chose Prime1 as 19 and Prime2 as 31 in Step 1, so we have this:
Totient = (19 – 1) * (31 – 1) = 18*30 = 540
Totient = 540
Step 3 – Get a list of possible integers that result in 1 mod Totient
So we have our third and fourth equations in the Equation List:
EncryptPrime * DecryptPrime = 1 mod Totient
(Totient * AnyInteger) + 1 = 1 mod Totient
Notice that in both equations, the right sides are the same: 1 mod Totient
We get the fifth equation in our Equation List by simply merging these equations three and four:
EncryptPrime * DecryptPrime = (Totient * AnyInteger) + 1 where (Totient * AnyInteger) + 1 has exactly two prime factors
In step 2 we determined the totient is 540, so we have this:
EncryptPrime * DecryptPrime = 1 mod 540
So here is where you need to understand modular arithmetic. There are many possible values that equal 1 mod 540. It is a series. The series can be created with this function:
(Totient * AnyInteger) + 1 = 1 mod Totient
(540 * AnyInteger) + 1 = 1 mod 540
AnyInteger is just what it sounds like, it is any integer: 1, 2, 3, 4, 5, …, 100, …, ∞
540 * 1 + 1 = 541
540 * 2 + 1 = 1081
540 * 3 + 1 = 1621
540 * 4 + 1 = 2161
540 * 5 + 1 = 2701
…
540 * 100 + 1 = 54001
Or we make a list of these possible values that equal 1 mod 540 (which as you can see goes on for infinity)
541, 1081, 1621, 2161, 2701, …, 54001, … , ∞
Step 5 – Choose a 1 mod Totient value with exactly two prime factors: EncryptPrime and DecryptPrime
Now that we have a list, we apply the where clause to it:
{ 541, 1081, 1621, 2161, 2701, …, 54001, …, ∞ } where (Totient * AnyInteger) + 1 has exactly two prime factors
Now is when you need to understand Prime Factorization. There are three possibilities for factors and only the second one matches our where clause.
The integer is a prime (has only one factor, itself)
The integer has two prime factors
The integer has more than two prime factors
So let’s get the factors of the integers in our list.
541 = Prime
1081 = 23 × 47
1621 = Prime
2161 = Prime
2701 = 37 × 73
…
54001 = Prime
So from the short list (and remember the list is infinite, we just selected a few) we have two possible representations of 1 mod Totient.
(We didn’t even see any values with more than two prime factors but don’t worry, with bigger numbers you will find them.)
Here is another place where we get to choose. Once again, close your eyes and point or pull them out of a hat. It doesn’t matter just choose.
Again, there is a recommendation:
For EncryptPrime choose a prime larger than (p – 1) or (q – 1).
For this example, I have chosen 37 × 73 even though they don’t meet the above recommendation, however, I can make either EncryptPrime or DecryptPrime, they are interchangable.
So I will make the bigger value EncryptPrime.
EncryptPrime = 73
DecryptPrime = 37
Step 6 – Encrypt
We now have everything we need to Encrypt and Decrypt.
CipherText = PlainTextEncryptPrime mod ProductOfPrime1Prime2
Lets say we have an ascii character ‘A’ or 65. We already know what all the variables except for the CipherText are.
PlainText = 65
EncryptPrime = 73
ProductOfPrime1Prime2 = 589
So lets put these values into our equation. This can be done with a simple calculator.
CipherText = 6573 mod 589 = 179
CipherText = 179
Step 6 – Decrypt
Now lets decrypt this.
PlainText = CiphertextDecryptPrime mod ProductOfPrime1Prime2
We already know what all the variables are. Normally the PlainText is not known before hand as it is known in this example.
CipherText = 179
DecryptPrime = 37
ProductOfPrime1Prime2 = 589
Lets put these values into our equation and make sure they return ‘A’ or 65.
PlainText = 17937 mod 589 = 65
PlainText = 65
How does this apply to Public/Private key security (your PC to an HTTPS web server)
It is simple. A public and private key are created on the server. When you hit a web server, the web server sends you the public key.
PublicKey contains: EncryptPrime and ProductOfPrime1Prime2
You are never sent the PrivateKey.
PrivateKey = DecryptPrime and ProductOfPrime1Prime2
This works because you cannot derive EncryptPrime from DecryptPrime and ProductOfPrime1Prime2
You encrypt everything you send to the web server with the PublicKey and they encrypt everything they send you with the PrivateKey. You can decrypt what the server sends you, but only the server can decrypt what you send back. So when you type in your Password into a your bank’s web page, your password is sent encrypted so only the server can decrypt it.
1. Pfleeger, Charles P.; Pfleeger, Shari Lawrence (2007-01-23). Security in Computing (4th Edition) (Kindle Locations 19886-19887). Prentice Hall. Kindle Edition.
Xml serialization is almost becoming a standard requirement for a language these days and so as I have been taking an Android class and I couldn’t find an Xml Serialization library as part of Android by default, I set out in search of one.
I came across a java XML Serialization project called Simple.
So here is a quick entry-level example of how to use Simple in an Android development project.
Note: This walk-thru assumes you are using Eclipse.
Copy the jar file called simple-xml-2.6.2.jar to the libs directory you just created.Note: Be aware your version may be newer than 2.6.2.
In Eclipse, right-click on simple-xml-2.6.2.jar (if it doesn’t show up refresh) and choose Build Path | Add to Build Path.
Step 4 – Create an Serializeable object
Right-click on your package and choose New | Class.
Provide a class name and click ok.
The following is an example Person class:Person.java
package org.jaredbarneck.cs6890;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root
public class Person
{
public Person()
{
}
public Person(String inFirstName, String inLastName)
{
SetFirstname(inFirstName);
SetLastname(inLastName);
}
@Element
private String FirstName;
public String GetFirstName()
{
return FirstName;
}
public void SetFirstname(String inFirstName)
{
FirstName = inFirstName;
}
@Element
private String LastName;
public String GetLastName()
{
return LastName;
}
public void SetLastname(String inLastName)
{
LastName = inLastName;
}
@Override
public boolean equals(Object inObject)
{
if (inObject instanceof Person)
{
Person inPerson = (Person)inObject;
return this.FirstName.equalsIgnoreCase(inPerson.FirstName)
&& this.LastName.equalsIgnoreCase(inPerson.LastName);
}
return false;
}
}
Step 5 – Serialize and Deserialize in your main Activity
Add the following code to your main Activity:Note: Code should be clear and is commented.PersonActivity.java
package org.jaredbarneck.cs6890;
import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import android.app.Activity;
import android.os.Bundle;
public class PersonActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a Person object
Person person1 = new Person("John", "Johnson");
// Create a file to save to and make sure to use the path provided from
// getFilesDir().getPath().
File xmlFile = new File(getFilesDir().getPath() + "/Person.xml");
// Serialize the Person
try
{
Serializer serializer = new Persister();
serializer.write(person1, xmlFile);
}
catch (Exception e)
{
e.printStackTrace();
}
// Create a second person object
Person person2 = null;
// Deserialize the Person
if (xmlFile.exists())
{
try
{
Serializer serializer = new Persister();
person2 = serializer.read(Person.class, xmlFile);
}
catch (Exception e)
{
e.printStackTrace();
}
}
boolean b = person1.equals(person2);
}
}
Go ahead and try this in your Android emulator and step through it with a debugger.
You have now successfully implemented Xml Serialization in Java on Android using Simple.
Design and architect and write your software solution so that its different pieces can be independent in the following ways:
Develop Independently
Build Independently
Install Independently
Test Independently
Refactor/Replaced Independently
Don’t just separate the concerns in one way and call it good. Separate your concerns all the ways listed above.
What will this do for your project?
It will make it so it can be easily unit tested.
It will make it so it can be easily built.
It will make it so it can be easily installed.
It will make it so it can be easily changed: Patched, Refactored, or Replaced.
Wow, all that sounds great, why doesn’t everyone do this?
Because the one area that is harder is the initial development. You have to design a lot more. You have to code different. It can be hard.
However, it is the easiest way overall, just not the easiest way at the start developing.
How do I separate my code into pieces?
There is a though among many that a software tool should do one thing only, but it should do it really well. When you think of your entire project, that should be kept in mind.
The smallest item in a project is the likely the “object”.
The term object is very abstract. It is like the work “thing” in that it can be anything.
So look at it from a high level view. Imagine your software has four pieces.
Ok, how do these pieces interact? Can you build each piece without having to link to another piece? You should be able to do this.
However, you have to link to something in someway in order to use its code so what do you link to?
Interfaces.
Ok, so you double the size of your pieces by having a piece and an interface for it. These could be eight separate dlls.
If Piece1 needs Peice2, it should link to IPiece2 and not to Piece2. This allows for Piece2 to be:
Any version of Piece2 that implements the interface.
Refactored without breaking the Piece1 build.
Replaced by a completely different implementation
Mocked for testing (really the same as three but used for Unit tests)
Real life example
In real life, applications are database driven. So what if your Piece2 is a database tool and Peice1, Piece3, and Piece4 all need to access the database using Piece2.
If you link directly to Piece2, you have a problem where you must have a real database in order to test your code in Piece1, Piece3, and Piece4.
This is a huge testing burden. This prevents your tests from running as Unit Tests and instead they must be run as Functional Tests.
However, by designing properly using interfaces, you can get back to Unit Tests for Piece1, Piece3, and Piece4 by mocking Piece2.
You use IPiece2 to create a new block called Mock2, which is just a Mock of Piece2, which can be run during a Unit Test. Now all the other blocks are testable.
Lets look at our Independent Architecture rules and see if this design works.
Yes – It will make it so it can be easily unit tested.
Yes – It will make it so it can be easily built.
Yes – It will make it so it can be easily installed.
Yes – It will make it so it can be easily changed: Patched, Refactored, or Replaced.
If you have a large application, this is one design pattern you should look at.
This simple project can also easily be compiled without a Makefile using this command line.
g++ -o HelloWorld Main.cpp HelloWorld.cpp
However, even with only three files you can start to see how it is much easier to type make than the lengthening command above.
Makefile
all:
g++ -o HelloWorld Main.cpp HelloWorld.cpp
This is not perfect however, as this compiles both files every time make is run. If changes are made only to Main.cpp there is no reason to recompile HelloWorld.cpp. We can accomplish this by compiling HelloWorld.cpp to a HelloWorld.o module.
Now only the libraries that have been modified will be recompiled when you run make. This can save significant build time when the project size increases.
Using variables in your Makefile
Mistakes are annoying. Having to type the same thing in multiple places often leads to mistakes and typos. If you look at the above, there is duplication that is unnecessary.
Think about it. Right now you only have one build command, but someday on a huge project you may have dozens and possibly hundreds. Could you imaging changing the CXXFLAGS everywhere? We don’t even have one listed yet, but of course, with the variable you only have to change it once in one place and it will work everywhere you used it.
Adding make clean to your Makefile
It is very common to want to delete all build files and build again. This is often done with the make clean command. But to get make clean to work you have to create a section or label in the make file called clean.
Because we already have variables, it is easy to configure the Makefile to support make clean.
Notice we set LDFLAGS but we never actually call it. It is a special variable that is called automatically by the linker when creating the objects. Yes it must be capitalized.
Ok, so adding a menu that pops up from the bottom when the menu button is clicked is very common and quite easy to do.
Note: This assumes you have the Android SDK, Emulator, and Eclipse all working already.
Step 1 – Create your Android project
In Eclipse, select File | New Project | Android | Android Project.
Give your project a Name.
I named this project “HelloAll”.
Select the Build Target (the minimum version of Android).
I selected Android 2.2.
Enter a Package name.
Package name is like a namespace, it can be anything you want, but you should actually choose a name as carefully as you choose and the name of an object. I named the package this: org.rhyous.
Click Finish.
Your project is now created.
Step 2 – Add an XML file for the menu
Expand the res directory in your project.
Right-click on the layout folder and choose New | Other.
Add strings for each menu item.
Make sure you use the same id strings you used in the menu.xml for the title of each menu item.
Your strings.xml should now look like this:
You now have a menu and strings for each menu item.
Step 4 – Overload onCreateOptionsMenu
Open your Activity.
Mine is src\org.rhyous\HelloAllActivity.java.
It should look like this:
package org.rhyous;
import android.app.Activity;
import android.os.Bundle;
public class HelloAllActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle inSavedInstanceState) {
super.onCreate(inSavedInstanceState);
setContentView(R.layout.main);
}
}
Add code to override onCreateOptionsMenu and add code to inflate the menu.
You can now build your application and test that the menu pops up. However, the menu doesn’t do anything yet.
Step 5 – Overload onCreateOptionsMenu
Add code to override onOptionsItemSelected and add code to inflate the menu.
Use a switch statement with the inItem.getItemId() function to perform the appropriate action for each menu item.
@Override
public boolean onOptionsItemSelected(MenuItem inItem) {
switch (inItem.getItemId()) {
case R.id.menu_item_1:
// Do something here
return true;
case R.id.menu_item_2:
// Do something here
return true;
default:
// Should never get here
return false;
}
Based on the item clicked, the appropriate code will run.
Hope you enjoyed this simple Android development example.
Ghost 2.5 is a BSD desktop distribution based on FreeBSD. This version is keeping up with the latest FreeBSD 9 release. This is both a live distribution as well as an installer for FreeBSD 9.
It is exciting for a lot of BSD users who didn’t really have an out-of-the-box GNOME option on FreeBSD to have a distribution where GNOME is the focus.
The DVD ISO in 64 bit is only 1.3 GB, though there is a “lite” version that is on a single CD.
It is nice that they are using pcsysintall for their installer, though they are in early stages as the installer is a text installer and not for an Ubuntu user yet. 😉
If you are excited about this project go ahead and give them a donation. I just tossed them $5. http://ghostbsd.org/donate/
Hey all, I wrote a C++ object that gets the prime factors of any number and thought I would share it.
The comments should help you and the variables have very clear names, so it should be self-documenting.
PrimeFactorsOfCalculator.h
#pragma once
#include <vector>
using namespace std;
class PrimeFactorsOfCalculator
{
public:
PrimeFactorsOfCalculator(void);
~PrimeFactorsOfCalculator(void);
long GetNumber();
void SetNumber(long inNumber);
vector<int> GetPrimeFactors(bool inAllowDuplicates = false, bool inForceRecalculate = false);
private:
long Number;
vector<int> PrimeFactors;
bool IsPrime(long inNumber);
long MultiplyPrimes();
};
PrimeFactorsOfCalculator.cpp
#include "PrimeFactorsOfCalculator.h"
#include <math.h>
#include <algorithm>
using namespace std;
PrimeFactorsOfCalculator::PrimeFactorsOfCalculator(void)
{
}
PrimeFactorsOfCalculator::~PrimeFactorsOfCalculator(void)
{
}
long PrimeFactorsOfCalculator::GetNumber()
{
return Number;
}
void PrimeFactorsOfCalculator::SetNumber(long inNumber)
{
Number = inNumber;
PrimeFactors.clear();
}
//
// Gets the prime factors of Number. 100 return 2,5.
//
// inAllowDuplicates - Allow duplicates, for example, 100 has prime
// factors of 2 and 5,but in order to get 100, you need 2*2*5*5. So
// instead of returning 2,5 the return array will be 2,2,5,5.
//
// inForceRecalculate - By default the values are stored at first
// calculation and only recalcuated when needed. this is for efficiency.
vector<int> PrimeFactorsOfCalculator::GetPrimeFactors(bool inAllowDuplicates, bool inForceRecalculate)
{
// Don't recalculate if already calculated.
if (PrimeFactors.size() > 0 && !inForceRecalculate)
return PrimeFactors;
PrimeFactors.clear();
// Calculate
if (Number % 2 == 0 && Number >= 2)
{
PrimeFactors.push_back(2);
}
for (int i = 3; i < Number/3; i++)
{
if (Number % i == 0 && IsPrime(i))
PrimeFactors.push_back(i);
}
// Allow duplicates, for example, 100 has prime factors of 2 and 5,
// but in order to get 100, you need 2*2*5*5. So instead of returning
// 2,5 the return array will be 2,2,5,5.
if (inAllowDuplicates)
{
while (MultiplyPrimes() != Number)
{
long multipliedVal = MultiplyPrimes();
long val = 0;
if (multipliedVal != 0)
val = Number / multipliedVal;
if (IsPrime(val))
{
PrimeFactors.push_back(val);
continue;
}
else
{
// recursion
PrimeFactorsOfCalculator calc = PrimeFactorsOfCalculator();
calc.SetNumber(val);
vector<int> duplicateFactors = calc.GetPrimeFactors();
for (size_t i = 0; i < duplicateFactors.size(); i++)
{
PrimeFactors.push_back(duplicateFactors.at(i));
}
}
}
}
sort(PrimeFactors.begin(), PrimeFactors.end());
return PrimeFactors;
}
bool PrimeFactorsOfCalculator::IsPrime(long inNumber)
{
// Get square root as that is the highest possible factor
// and add one in case precision is screwy.
long highestPossibleFactor = (long)(sqrt((double)inNumber) + 1);
// Handle 2 separatly then no other even has to be checked
if (inNumber % 2 == 0)
return false;
// See if the value is divisible by any odd number
// if so it is not prime
for (int i = 3; i < highestPossibleFactor; i+=2)
{
if (inNumber % i == 0)
return false;
}
return true;
}
long PrimeFactorsOfCalculator::MultiplyPrimes()
{
if (PrimeFactors.size() == 1)
return PrimeFactors.at(0);
else if (PrimeFactors.size() > 1)
{
int minVal = PrimeFactors.at(0);
for (size_t i = 1; i < PrimeFactors.size(); i++)
{
minVal *= PrimeFactors.at(i);
}
return minVal;
}
else return 1; // 1 is always a prime
}
And last here is a sample main function that uses this.
Unit Testing is the idea of writing additional code, called test code, for the purpose of testing the smallest blocks of production code to the full extent possible to make sure those blocks of code are error free.
Code is usually designed into Classes or Objects. The term “Class” and the term “Object” are usually used interchangeably. Classes are made up of variables and functions that include Constructors, Methods, and Properties but they may also include sub-classes.
For each Object in code, you should have a Unit Test for that object. For each method in an Object, the correlating Unit Test should have a test. In fact, a test should exist that makes sure that every line of your code functions as expected.
Code Coverage
Unit Tests are about making sure each line of code functions properly. A Unit Test will execute lines of codes. Imagine you have 100 lines of code and a Unit Test tests only 50 lines of code. You only have 50% code coverage. The other 50% of you code is untested.
Most Unit Test tools, MSTest, MBUnit, NUnit, and others can provide reports on code coverage.
Cyclomatic Complexity
Cyclomatic Complexity is a measurement of how complex your code is. This usually comes up in Unit Testing because in order to get 100% code coverage, one has to tests every possible path of code. The more your code branches, the more complex the code is.
If you have to write twenty tests just to get 100% coverage for a single function, you can bet your cyclomatic complexity is too high and you should probably break the function up or reconsider the design.
Parameter Value Coverage
Parameter Value Coverage is the idea of checking both expected and unexpected values for a given type. Often bugs occur because testing is not done on an a type that occurs unexpectedly at run time. Often a value is unexpectedly null and null was not handled, causing the infamous null reference exception.
Look at this function. Can you see the bug?
public bool CompareStrings(String inStr1, String inStr2)
{
return inStr1.Equals(inStr2);
}
A System.NullReferenceExecption will occur if inStr1 is null.
How can we find these bugs before a customer reports them? A unit test can catch these bugs. We can make lists of anything we can think of that might react differently.
For example, imagine a function that takes a string. What should we try to test:
An actual string: “SomeText”;
An uninitialized string: null;
A blank string: “”
A string with only whitespace: ” “;
Now imaging a function takes an object called PersonName that has a string member for FirstName and LastName value. We should try to test some of the above.
A PersonObject but nothing populated: new PersonName();
A PersonObject but everything populated: new PersonName() {FirstName=”John”, LastName=”Johnson”};
A PersonObject but partially populated: new PersonName() {LastName=”Johnson”} || new PersonName() {FirstName=”John”};
An uninitialized PersonName object: null;
Here is a test that will check for null in the compare strings code.
Note: There is a decision to make here. If comparing two string objects and both are null, do you want to return true, because both are null so they match? Or do you want to return false, because neither are even strings? For the code below, I’ll assume two null strings should not be considered equal.
Now your unit test is going to encounter a System.NullReferenceExecption. Assuming you write Unit Tests before you release your code to a customer, you will catch the bug long before the code reaches a customer and fix it.
Here is the fixed function.
public bool CompareStrings(String inStr1, String inStr2)
{
// If either input values are null, return false
if (null == inStr1 || null == inStr2)
return false;
return inStr1.Equals(inStr2);
}
Unit Test Example
Here is an example object called PersonName. We tried to make it have a little more meat to this object than just a FirstName, LastName password.
PersonName.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace PersonExample
{
///<summary>
/// An Ojbect representing a Person
/// </summary>
public class PersonName : IPersonName
{
#region Constructor
public PersonName()
{
}
#endregion
#region Properties
/// <summary>
/// The persons first name.
/// </summary>
public String FirstName { get; set; }
/// <summary>
/// The persons Middle Name(s). Some people have multiple middle names.
/// So as many middle names as desired can be added.
/// </summary>
public List MiddleNames
{
get
{
if (null == _MiddleNames)
_MiddleNames = new List();
return _MiddleNames;
}
set { _MiddleNames = value; }
} private List _MiddleNames;
public String LastName { get; set; }
#endregion
#region Methods
/// <summary>
/// Converts the name to a string.
/// </summary>
public override string ToString()
{
return ToString(NameOrder.LastNameCommaFirstName);
}
///<summary>
/// Converts the name to a string.
/// </summary>
///
///
private String ToString(NameOrder inOrder)
{
switch (inOrder)
{
case NameOrder.LastNameCommaFirstName:
return LastName + ", " + FirstName;
case NameOrder.LastNameCommaFirstNameWithMiddleNames:
return LastName + ", " + FirstName + " " + MiddleNamesToString();
case NameOrder.FirstNameSpaceLastname:
return FirstName + " " + LastName;
case NameOrder.FirstNameMiddleNamesLastname:
return FirstName + MiddleNamesToString() + LastName;
default:
return LastName + ", " + FirstName;
}
}
/// <summary>
/// Converts the list of middle names to a single string.
/// </summary>
/// String
private String MiddleNamesToString()
{
StringBuilder builder = new StringBuilder();
bool firstTimeThrough = true;
foreach (var name in MiddleNames)
{
if (firstTimeThrough)
firstTimeThrough = false;
else
builder.Append(" ");
builder.Append(name);
}
return builder.ToString();
}
/// <summary>
/// Compares the object passed in to see if it is a Person.
/// </summary>
///
/// True if FirstName and LastName and MiddleNames match, False if the object
/// is not a Person or FirstName and LastName and MiddleNames do not match
public override bool Equals(object inObject)
{
PersonName p = inObject as PersonName;
if (null == p)
return false;
else
return Equals(p);
}
/// <summary>
/// Compares one PersonName to another PersonName.
/// </summary>
public bool Equals(IPersonName inPersonName)
{
return inPersonName.FirstName.Equals(FirstName, StringComparison.CurrentCultureIgnoreCase)
&& inPersonName.LastName.Equals(LastName, StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// Compares a string to see if it matches a person.
/// </summary>
public bool Equals(String inString)
{
string tmpLastNameCommaFirstName = ToString(NameOrder.LastNameCommaFirstName);
string tmpLastNameCommaFirstNameWithMiddleNames = ToString(NameOrder.LastNameCommaFirstNameWithMiddleNames);
string tmpFirstNameSpaceLastname = ToString(NameOrder.FirstNameSpaceLastname);
string FirstNameMiddleNamesLastname = ToString(NameOrder.FirstNameMiddleNamesLastname);
return tmpLastNameCommaFirstName.Equals(inString, StringComparison.CurrentCultureIgnoreCase)
|| tmpLastNameCommaFirstNameWithMiddleNames.Equals(inString, StringComparison.CurrentCultureIgnoreCase)
|| tmpFirstNameSpaceLastname.Equals(inString, StringComparison.CurrentCultureIgnoreCase)
|| FirstNameMiddleNamesLastname.Equals(inString, StringComparison.CurrentCultureIgnoreCase);
}
///
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region Enums
/// <summary>
/// The order of the names when converted to a string.
/// </summary>
public enum NameOrder
{
LastNameCommaFirstName = 0,
LastNameCommaFirstNameWithMiddleNames,
FirstNameSpaceLastname,
FirstNameMiddleNamesLastname
}
#endregion
}
}
Ok, so in a separate test project, the following corresponding test class can be created.
PersonNameTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PersonExample;
namespace PersonExample_Test
{
/// <summary>
///This is a test class for PersonNameTest and is intended
///to contain all PersonNameTest Unit Tests
///</summary>
[TestClass()]
public class PersonNameTest
{
#region PersonName()
/// <summary>
///A test for PersonName Constructor
///</summary>
[TestMethod()]
public void PersonName_ConstructorTest()
{
PersonName person = new PersonName();
Assert.IsNotNull(person);
Assert.IsInstanceOfType(person, typeof(PersonName));
Assert.IsNull(person.FirstName);
Assert.IsNull(person.LastName);
Assert.IsNotNull(person.MiddleNames);
}
#endregion
#region Equals(Object inObject)
/// <summary>
///A test for Equals(Object inObject) with matching first and last names
///</summary>
[TestMethod()]
public void Equals_Obj_Test_Matching_First_Last_Names()
{
PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
object inObject = new PersonName() { FirstName = "John", LastName = "Johnson" };
bool expected = true;
bool actual = target.Equals(inObject);
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Equals(Object inObject) with different last name
///</summary>
[TestMethod()]
public void Equals_Obj_Test_Matching_Different_Last_Names()
{
PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
object inObject = new PersonName() { FirstName = "John", LastName = "Jameson" };
bool expected = false;
bool actual = target.Equals(inObject);
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Equals(Object inObject) with different first name
///</summary>
[TestMethod()]
public void Equals_Obj_Test_Matching_Different_First_Names()
{
PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
object inObject = new PersonName() { FirstName = "James", LastName = "Johnson" };
bool expected = false;
bool actual = target.Equals(inObject);
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Equals(Object inObject) when a null is passed in.
///</summary>
[TestMethod()]
public void Equals_Obj_Test_Null()
{
PersonName target = new PersonName();
object inObject = null;
bool expected = false;
bool actual;
actual = target.Equals(inObject);
Assert.AreEqual(expected, actual);
}
#endregion
#region Equals(String inString)
/// <summary>
///A test for Equals(String inString) where inString is null
///</summary>
[TestMethod()]
public void Equals_String_Test_null()
{
PersonName target = new PersonName() { FirstName = "Tom", LastName = "Tomison" };
string inString = null;
bool expected = false;
bool actual;
actual = target.Equals(inString);
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Equals(String inString) where inString is a match using
///PersonName.NameOrder.FirstNameSpaceLastname
///</summary>
[TestMethod()]
public void Equals_String_Test_FirstNameSpaceLastname_Match()
{
PersonName target = new PersonName() { FirstName = "Tom", LastName = "Tomison" };
string inString = "Tom Tomison";
bool expected = true;
bool actual;
actual = target.Equals(inString);
Assert.AreEqual(expected, actual);
}
/// <summary>
///A test for Equals(String inString) where inString is a match using
///PersonName.NameOrder.LastNameCommaFirstName
///</summary>
[TestMethod()]
public void Equals_String_Test_LastNameCommaFirstName_Match()
{
PersonName target = new PersonName() { FirstName = "Tom", LastName = "Tomison" };
string inString = "Tomison, Tom";
bool expected = true;
bool actual;
actual = target.Equals(inString);
Assert.AreEqual(expected, actual);
}
#endregion
// TODO: Finish testing this object
}
}
For more learning, answer the following questions:
What functions are Unit Tested?
What is the code coverage of this Unit Test? (What percent of the Code is Unit Tested?)
You have an enum with twenty items in it. One function has a switch on the enum with all twenty possibilities. The cyclomatic complexity appears to be high and is causing a red flag? Should you change your code? Why or Why not?
Assume you finish the unit test so that the code is 100% covered. What reasons exist for needing still more tests on that code?
If you are messing with IIS in C# code, you can do quite a bit if you System.DirectoryServices and the DirectoryEntry object. This can be extended if you know the name of the items in a the DirectoryEntry’s property collection. You can get these as follows:
using System;
using System.Collections.Generic;
using System.DirectoryServices;
namespace FindIISLogWithCSharp
{
class Program
{
static void Main(string[] args)
{
List<string> AvailableProperties = new List<string>();
DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC");
PropertyCollection pc = folderRoot.Properties;
foreach (PropertyValueCollection p in pc)
{
AvailableProperties.Add(p.PropertyName);
}
// Sort alphabetically
AvailableProperties.Sort();
foreach (String prop in AvailableProperties)
{
Console.WriteLine(prop);
}
}
}
}
Of course, different DirectoryEntry objects can have different lists. However, this exact one created the following list on a Windows 2008 R2 64-bit Server with IIS installed and configured.
My first Android homework was to write a little program that would add sequential numbers such as 1 to 100. I call it a Sequential Sum, but I couldn’t find the exact mathematical name.
In code, you could of course loop through 1 through 100 and += them into a value but there is a more efficient way and most everyone in my class mentioned that is what they did, so I guess I was unique in choosing this solution.
Or you could use the following equation that provides you the answer to get the sum of all numbers between 1 and the end value, n.
n(n+1)/2
Now what if you aren’t starting at 1? What if you want to add the numbers between 50 and 150? Well, this is easy. The last number before the start value of 50 is 49 or 50 – 1 = 49. We can get the value of 1 to 49 and subtract it from the value of 1 to 150.
n(n+1)/2 – s(s+1)/2
While this is for Android, it is basically just java and there is nothing Android specific here. Here is my class.
package org.jaredbarneck.cs6890;
import java.security.InvalidParameterException;
/**
* @author Jared
*
*/
public class SequentialSum {
// Member variables
private int _LowValue = 0;
private int _HighValue = 0;
// Constructors
public SequentialSum(int inLowValue, int inHighValue) {
SetHighValue(inHighValue);
SetLowValue(inLowValue);
}
// Getters and Setters
public int GetLowValue() {
return _LowValue;
}
public int GetHighValue() {
return _HighValue;
}
public void SetLowValue(int inValue) {
if (inValue < 0)
throw new InvalidParameterException(
"Value must be greater than zero!");
if (inValue > _HighValue)
throw new InvalidParameterException(
"High value must be lower than the high value!");
_LowValue = inValue;
}
public void SetHighValue(int inValue) {
if (inValue < 0)
throw new InvalidParameterException(
"Value must be greater than zero!");
if (inValue < _LowValue)
throw new InvalidParameterException(
"High value must be greater than the low value!");
_HighValue = inValue;
}
// Methods
public int Sum() {
int sumToSubtract = 0;
if (_LowValue > 1) {
int tmpVal = _LowValue - 1;
sumToSubtract = tmpVal * (tmpVal + 1) / 2;
}
return (_HighValue * (_HighValue + 1) / 2) - sumToSubtract;
}
}
So if I ever need to get the sum of all values between a sequential list of numbers, I can come back and use this class again.
Note: No, I don’t follow java syntax rules and no, I don’t plan too either. I don’t start anything with lower case that is not a local variable. My member variables start with an underscore _ and then an uppercase letter. Everything else starts with upper case. I don’t conform my style to a specific language’s style, instead I try to use the same style in all languages.