Wednesday, August 22, 2012

Ads Appear in Lower Right of Browser


This problem may present itself as random redirects or as a big square ad appearing in the lower right corner of the web browser which when clicked, may lead to malicious sites.

  
This is usually an indication that the hosts file of the computer have been hijacked.
I've been able to fix this problem by resetting my hosts file manually or by using RogueKiller which is available via the following link:
http://www.sur-la-toile.com/RogueKiller/RogueKiller.exe

Friday, August 10, 2012

WCF: Username/Password Authentication using BasicHttpBinding


I was required to do this type of Authentication in one of my projects. I am documenting the steps that I did for future reference.

Create an X509 certificate

The username/password authentication requires the communication between the client and server to be encrypted.

A test certificate can be created using the Certificate Creation Tool (Makecert.exe) by Microsoft.
http://msdn.microsoft.com/en-us/library/bfsktky3(v=vs.80).aspx
  1. Open the Visual Studio command prompt
  2. Type the following command
Certificate Authority
makecert -n "CN=MMRootAuthority" -r -sv MMRootAuthority.pvk MMRootAuthority.cer
pvk2pfx -pvk MMRootAuthority.pvk -spc MMRootAuthority.cer -pfx MMRootAuthority.pfx -pi “YourPassword” -po “YourPassword”

Certificate Revocation List
makecert -crl -n "CN=MMRootCRL" -r -sv MMRootCRL.pvk MMRootCRL.crl
pvk2pfx  -pvk MMRootCRL.pvk -spc MMRootCRL.crl-pfx MMRootCRL.pfx -pi “YourPassword” -po “YourPassword”

Server Certificate
makecert -iv MMRootAuthority.pvk -n "CN=MMServerCertificate" -ic MMRootAuthority.cer -sr CURRENTUSER -ss My -sky exchange -eku 1.3.6.1.5.5.7.3.1 -pe  -sv MMServerCertificate.pvk MMServerCertificate.cer
pvk2pfx -pvk MMServerCertificate.pvk -spc MMServerCertificate.cer -pfx MMServerCertificate.pfx -pi “YourPassword” -po “YourPassword”

Client Certificate
makecert -iv MMRootAuthority.pvk -n "CN=MMClientCertificate" -ic MMRootAuthority.cer -sr CURRENTUSER -ss My -sky exchange -eku 1.3.6.1.5.5.7.3.2  -pe  -sv MMClientCertificate.pvk MMClientCertificate.cer
pvk2pfx -pvk MMClientCertificate.pvk -spc MMClientCertificate.cer -pfx MMClientCertificate.pfx -pi “YourPassword” -po “YourPassword”

Viewing certificates
If the command is successful, installed certificates can be viewed by
  1. Open command prompt, type in mmc and press enter.
  2. Select Add/Remove Snap-ins and select Certificates.

Configure IIS

The following article helps on how to enable SSL in IIS.
http://learn.iis.net/page.aspx/144/how-to-set-up-ssl-on-iis/



Here are the steps I did to enable SSL in IIS 
  1. Install the Root Certificate Authority in the Local Machine's Trusted Certificate Store. 
  2. Install the Server Certificate in the Local Machine's Personal Certificate Store. 
  3. Go to IIS and open web site properties/bindings, configure the port for SSL and the certificate to use.
Could not find base address that matches scheme https for the endpoint with binding MetadataexchangeHttpsBinding. Registered base address schemes are [http]

When running from inside Visual Studio, the likely culprit is the project not being configured to use the local IIS Web Server.


Ensure that the service is configured to use the local IIS Web Server under project properties/web tab.

Configure the Username/Password Authentication

I used the following steps to configure username/password authentication
  1. Navigate to configuration/system.serviceModel/bindings/basicHttpBinding/
  2. Add the following lines
    <binding name="usernameHttps">
       <security mode="TransportWithMessageCredential">
          <message clientCredentialType="UserName"/>                   
       </security>                   
    </binding>
  3. Change your endpoint to use the usernameHttps binding
    <endpoint binding="basicHttpBinding"
       bindingConfiguration="usernameHttps" name="BasicHttpEndpoint" contract="WcfService4.IService1" >   
    </endpoint>
    The mexHttpBinding will need to be changed to mexHttpsBinding
    The httpGetEnabled will need to be changed to httpsGetEnabled

  4. Implement a username/password validator by creating a class that inherits from UserNamePasswordValidator
    public class UsernNamePasswordValidator : UserNamePasswordValidator {
        public override void Validate(string userName, string password) {}}
    Ensure that System.IdentityModel and System.IdentityModel.Selectors are referenced.
  5. In the web.config file, goto to configuration/system.serviceModel/behaviors/serviceBehaviors/behavior
  6. Add the following line
    <userNameAuthentication userNamePasswordValidationMode="Custom"
    customUserNamePasswordValidatorType="WcfService4.UserNamePasswordValidator, WcfService4"/>

    The first parameter is the fully qualified name of the custom username/password validator class.
    The second parameter specifies the name of the assembly that the validator is located in.

To audit login attempts a serviceSecurityAudit node can be added
http://msdn.microsoft.com/en-us/library/ms731694.aspx


I used the following configuration.
<serviceSecurityAudit
auditLogLocation="Application"
serviceAuthorizationAuditLevel="Failure"

messageAuthenticationAuditLevel="Failure"
suppressAuditFailure="true" />

When security related problems are encountered, this setting will write to the event log of the machine where the service is hosted.

My web.config file

This is my web.config file with unrelevant sections ommitted
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>   
    <bindings>           
      <basicHttpBinding>     
        <binding name="usernameHttps">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName"/>                   
          </security>                   
        </binding>
      </basicHttpBinding>
    </bindings>   
    <services>                 
      <service name="WcfService4.Service1" behaviorConfiguration="DefaultBehavior">       
        <endpoint binding="basicHttpBinding"
          bindingConfiguration="usernameHttps" name="BasicHttpEndpoint" contract="WcfService4.IService1" >   
        </endpoint>
      </service>     
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
             customUserNamePasswordValidatorType="WcfService4.CustomUserNameValidator, WcfService4"/>
          </serviceCredentials>
        </behavior>         
      </serviceBehaviors>     
    </behaviors>       
  </system.serviceModel> 
</configuration>

I'll be creating an article on how to consume this service in my next post.

Wednesday, April 11, 2012

Inheriting from a DataRow


I needed to implement a custom data row in one of my projects which made me result to the following code.
Create a custom class which inherit from a DataRow. Add a constructor which accepts a DataRowBuilder.

public class CustomDataRow : DataRow {
   internal CustomDataRow(DataRowBuilder rowBuilder) : base(rowBuilder) { }

}

Override the NewRowFromBuilder method. Inside this method, call the CustomDataRow's constructor passing in the DataRowBuilder.

public class CustomDataTable : DataTable {
   public CustomDataTable(){ }

   protected override DataRow NewRowFromBuilder(DataRowBuilder builder) {

      return new CustomDataRow(builder);

   }
}

This will enable each row created by the CustomDataTable to be of CustomDataRow.

Thursday, March 29, 2012

C# Converting PT0H0M0S to TimeSpan


I was working on importing Microsoft Project data into one of my projects when I encountered a problem where the MSP's TimePhasedData value is using the format PT0H0M0S to represent date values. I needed to convert the PT0H0M0S string to a double representing the total hours. I'm posting this code just in case someone is looking for something similar.

public static double StringToTimeSpan(string source)
   int hours = 0; int minutes = 0; int seconds =0;
   string number = string.Empty ;
   for (int index = 0; index < source.Length; index++) {
      char current = source[index];

      if ("1234567890".Contains(current)) number += current;

      else
{
         if (current.Equals ('H')) hours += int.Parse(number);
         if (current.Equals ('M')) minutes += int.Parse(number);
         if (current.Equals ('S')) seconds += int.Parse(number);
         number = string.Empty ;
      }
   }
   return new TimeSpan (hours, minutes, seconds).TotalHours;

}

Tuesday, March 20, 2012

ComponentOne FlexGrid columns with checkboxes

When working with ComponentOne's FlexGrid bounded to a boolean column, setting the Editor property of that boolean column will make it difficult to change the value of the column.

DataTable table = new DataTable();
table.Columns.Add("Selected", typeof(bool));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(false, "Row 1");
flexGrid.DataSource = table;Column column = flexGrid.Cols[0];
column.Editor = new CheckBox();

In the example above, once the editor property of the column is set to an instance of a checkbox, changing the value of the selected column will take several tries.

I just skipped the setting the editor for boolean columns as a result and let C1FlexGrid manage it. If anyone knows of an explanation or a better way to set an editor of a C1FlexGrid column, just send me a message.


Friday, February 3, 2012

Ideablade License Exceptions when running Applications using DevForce


When running code in Visual Studio which uses Ideablade Devforce, you might encounter the following exception.


An error occurred while processing your product license: This product is not registered or the key may no longer be valid. Please contact your IdeaBlade representative to obtain a new key or email sales@ideablade.com.
Check the messages in the debuglog preceding this error for more information, since this error can occur in some high-security configurations. If your product key is no longer valid or you cannot resolve the problem, please contact IdeaBlade.

The three most common causes of this error include:
  1. An Invalid License key. When this occurs, contact ideablade and make sure that the license key is valid for the version of DevForce you have installed.
  2. The probing assembly is invalid. Check the Ideblade.config file and ensure that the probing assembly points to the assembly that contains your entity model.

  3. A change in one of the files that is used by the Ideablade license logic. When this occurs, simply regenerate the model. That is, open the Ideablade Object Mapper and save.
    The Ideablade license information is found in EntityRelations.cs. If the Ideblade Devforce assemblies are recently upgraded, regenerating the model ensures that this file contains the valid license information.
    [assembly: IdeaBladeLicense("aseriesofcharacters")] 
These findings are found with help from Ideablade support.

Thursday, January 12, 2012

Aspose.Tasks and Task Types


Task dates may be automatically calculated by the MSP's scheduling engine which may cause a task's start and finish dates to shift depending on the task type setting.


Task task = new Task("Name");
task.Type = TaskType.FixedUnits ;

The following is a very useful post by Chris Woodill explaining each of the TaskTypes:
http://chriswoodill.blogspot.com/2009/03/how-to-use-microsoft-project-task-type.html

Aspose.Tasks in MS Project Resource Uids


When using Aspose.Tasks to generate an XML file for Microsoft Project, if one of the resource’s uid is set to 0 and it has been used on an assignment, the assignment will not be shown once the xml file is opened in Microsoft Project. To prevent this, always set the resource.uid to a positive non zero integer value.
Aspose.Tasks.Resource resource = new Aspose.Tasks.Resource("Name");      
resource.Uid = resourceIDCounter++;

Note that a function call to CalcResourceUids of the Aspose.Tasks.Project will reset the Uid value.
_project.CalcResourceUids();

Booking individual periods in TimePhaseData in MS Project using Aspose.Tasks


The following code will allow booking of individual periods in the TimePhaseDetail of MSP.
I've used the following tools/languages for this demo.
  • Aspose.Tasks version: 4.0.0.0
  • Microsoft Visual Studio 2010 C#
  • Microsoft Project 2007
The _tasks and _resources is just a collection of Tasks and Resources respectively.
In the example below, all resources are being assigned to each task and are given a 1 or 2 value depending on the flag variable.

foreach (Task task in _tasks.Values) {
   foreach (Aspose.Tasks.Resource resource in _resources.Values) {

      ResourceAssignment resourceAssignment = new
      ResourceAssignment();
      resourceAssignment.Task = task;
      resourceAssignment.Resource = resource;

      resourceAssignment.Start = task.ActualStart;
      resourceAssignment.Finish = task.ActualFinish;
      resourceAssignment.Units = 1;
      resourceAssignment.HasFixedRateUnits = true;
      resourceAssignment.LevelingDelayFormat = TimeUnitType.ElapsedHour;
      resourceAssignment.Uid = _project.NextResourceAssignmentUid;
      resourceAssignment.WorkContour = WorkContourType.Contoured;
     
      DateTime date = task.ActualStart;
      bool flag = true;
      while (date < task.ActualFinish) {

         TimephasedData timephaseData = new TimephasedData();
         timephaseData.Start = date;
         timephaseData.Unit = TimeUnitType.Hour;
         date = date.AddDays(1);
         timephaseData.Finish = date;
         timephaseData.Uid = _project.ResourceAssignments.Count ;

         timephaseData.TimephasedDataType = TimephasedDataType.AssignmentActualWork ;

         if (flag) timephaseData.Value = "PT1H0M0S";

         else timephaseData.Value = "PT2H0M0S";
         flag = !flag;
         resourceAssignment.TimephasedData.Add(timephaseData);
      }
      _project.ResourceAssignments.Add(resourceAssignment);
   }
}


This is the resource usage view in MSP 2007. Notice that the resource Alien 1 is assigned to all projects with an alternating value.




I needed this requirement in the task I was working on and found that there were no existing examples on how to do it yet so this is just from my research.

Thursday, December 8, 2011

Unit test tips

Automated unit tests provide a safety net to enhance application so that we wont be afraid to make a change without introducing defects and it also makes an application more maintainable.
Unit test names must be robust; They should be named after the functionality that they are testing. A recommended way to name unit tests is to use the Noun+should+verb pattern.

A body of a test method should be arranged using the AAA pattern (arrange, act, assert).
-          Arrange: This section contains code that sets up the variables that will be used by the unit test.
-          Act : This section execercises the unit under testing and capture the results.
-          Assert: This section verifies the results of the unit test against expectations.

Avoid tests that do too much. Verify only a single concept to make it easier to pinpoint the cause of failures.

A good point is to have only a single assert statement in a test method. If you have multiple asserts, make sure that they are verifying the same concept.

Unit testing with a real database brings a number of challenges:
1.       It significantly slows down the execution time of unit tests.The longer it takes to run the tests, the less likely you will run them frequently. Ideally you would want unit tests to run in seconds- something you do naturally as compiling the project.
2.       It complicates the setup and cleanup logic within the tests. You want each unit test to be isolated and independent of the others with no side effects or dependencies. When working against a real database, you have to be also mindful of state and reset the values between the tests.
To overcome this challenge, it is recommended to use the dependency injection design pattern.

Dependency Injection
Dependencies, like repository classes are no longer implicitly created within the classes that use them. This will allow us to test specific scenarios without requiring a connection to the database.

Thursday, September 22, 2011

Cobra Log Analyzer


The Cobra Log Analyzer is a tool I’ve developed that assists in analyzing xml log files from Cobra.
It can consolidate multiple Cobra xml log files into a single window where it can be viewed, filtered and analyzed.
Opening Log Files
This is the main window for Cobra Log Analyzer.

Click on the open button to open a cobra log file.
Select one or more log files to process and click on Open.
Files can also be drag and dropped from explorer into the main window.
This works similar to opening a file via the open dialog.
The Cobra Log Analyzer is optimized to open massive log files.
Multiple threads are spawned to quickly process multiple files asycnhronously.
Grouping and Filtering

The information presented in the main grid can be grouped by simply dragging the desired column into the header band.

The visible cells can also be filtered via the filter icon for every column.
Search
Click on the search icon to bring up the search dialog.
The value specified shall be used to search the content column in the grid.

Sunday, September 18, 2011

Concatenating Strings Efficiently


StringBuilders should be reserved when the number of concatenations is unknown or large. 
Strings are immutable (not allowed to be changed). 

Dim sampleString As String = "I think the vegetables are : " _
sampleString &= "Tasty"

In the above example, the compiler will create a new string, allocate memory, copy the data from the original string and then copying the new data at the end of the existing string.

For a large number of concatenations, this operation is inefficient.


The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A string concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data.


Dim sampleString As String = "I think the vegetables are : " _
& "Tasty"


The string class is preferable if a fixed number of string objects are concatenated. Individual concatenation operations might be optmized by the compiler into a single operation.

 

Public Function Reproduce(
ByVal source As String,
ByVal iterations As Integer) As String
      Dim sampleStringBuilder As New System.Text.StringBuilder()
        For index As Integer = 0 To iterations
            sampleStringBuilder.Append(source)
        Next
      Return sampleStringBuilder.ToString()
End Function


A StringBuilder implementation is preferred when a large or unknown number of strings needs to be concatenated.


Resources:

http://www.yoda.arachsys.com/csharp/stringbuilder.html

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

Query Engine


The Query Engine is a utility I’ve developed that can connect to and perform queries against SQL Server or Oracle databases.

Connecting to  a Data Source
The Query Engine connects to an Oracle or a SQL Server data source via the File->Connect.
This brings up the Data Link properties dialog where connection parameters for either an Oracle or a SQL Server data source may be specified.

The Data Link properties dialog may also be invoked by clicking on the “Connect” icon in the Query Engine toolbar.


Querying Data Objects
Once connected to a database instance, the Query Engine will display all tables found in the specified data source in the table list located at the left.
Double clicking any of these entries will create an SQL select query in the command window and display the corresponding results in the query results grid.


The command window may also be used to specify more advanced SQL Queries.
These queries get executed once the Run command is clicked in the Query menu.
An alternative to this is the F5 button in the keyboard or the Run icon in the toolbar menu.

The Query results are retrieved asynchronously using a background thread.
This operation can be stopped by clicking on the stop icon in the toolbar.

Selecting Columns in Database Objects
Shift Double Clicking on an item in the table list will display the column names that can be selected prior to generating a query in the command window.

The select all button checks all columns for the selected table.
The de-select all button unchecks all columns for the selected table.
The select specified columns will create an SQL select statement which contains all the checked columns in the select columns dialog.

Search values inside Data Objects
Click on the magnifier icon to bring up the search dialog.
The search box accepts an alphanumeric string which is used to evaluate columns of its occurrence.
The search button initiates the search using the specified search string.
The close button closes the search dialog.

The search is asynchronous.
When a search is in progress, the table name and the column where it is found are dumped in the results grid.
Double click on any of the entries in the results grid to issue an automatic query in the command window of the Query Engine form.
This can be done even if a search is currently in progress.

The next button skips the current table and jumps to the next available data object to scan.
There can only be one active search at a time.
The current search needs to be cancelled via the abort button for a new search to be made.
You can also invoke the search dialog via Ctrl+F or via the Tools menu of Query Engine.

Viewing in Card View

Card view allows viewing of records with a large number of columns vertically.

To view records in card view, right click on the grid and then select Card View.


Grouping Records
The Query Engine can group records using a particular column.
This can be enabled via the tools menu.


Once enabled, a band will appear in the grid where columns can be dragged for grouping.
Dragging a column into this band will group the records using that column.

Freezing Columns
A column can be frozen by clicking on the freeze icon. This is the right-most icon beside the column name.


Filtering Rows
Query results can be filtered by specifying the filter condition in a column. To specify a filter condition, click on the filter icon which is the second icon to the right of the column name.

A dropdown appears with a list of choices in which the records may be filtered.
To specify a more complex filter condition, click on the Custom item in the filter dropdown.


Adding Summaries

To add a summary, click on the summary icon for the column that needs to be summarized.
From the dialog, select one or more methods on how to summarize the column.

Clicking the ok button will apply the selection on the column.

Exporting to Excel
To export a query result to excel, click on the Export to excel button in the Query Engine toolbar.
Specify a file name and click on save.
Configuring Query Engine
Clicking on the Tools->Configure menu will bring up the Query Engine configuration screen.
The working directory points to the location that will be used by Query Engine for its processes.
The displayed rows setting controls the maximum rows displayed per query.
This prevents massive datasets from being accidentally loaded to Query Engine.
This can be turned off by specifying a value of 0.
The recommended value is 200,000 rows.

The font setting controls the font that is used for the query editor and the Query Engine grid.
To modify the font, click on the Change button beside the font field.

Clicking Ok will apply the settings to the query editor and the grid.