Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

Sunday, January 4, 2015

Git: Setup and run Git Server on Windows 8.1 and with VS2010

This post introduce how to setup Bonobo git server on Windows 8.1 and how to use VS2010 to perform source control with Git.

Section 0: Install IIS on Windows 8.1

Enter "Turn Windows features on or off" in the "Search" box to launch the dialog.

In the "Windows Features" dialog, select the features as shown in the following figure.



Click "OK" and restart the computer.

Before we proceed further, we also need to allow the IIS through the windows firewall so that another computer can access the git server for source control. To this end, enter "allow an app through windows firewall", and in the dialog opened, scroll to the bottom to locate "World Wide Web Services (HTTP)" and check the option boxes next to it, and click OK.

Section 1: Install Bonobo Git Server in IIS


Download the Bonobo git server from the following link:

https://github.com/jakubgarfield/Bonobo-Git-Server

Unzip and copy the unzipped content (i.e. the "Bonobo.Git.Server" folder) under "C://inetpub/wwwroot" folder.

Enter "Internet Information Services (IIS) Manager" in the "Search" box to launch the IIS Manager.

In the IIS Manager, select "Sites->Default Web Site->Bonobo.Git.Server" tree node in the left panel, right-click the "Bonobo.Git.Server" node and select "Convert to Application", and click OK in the dialog opened.

In the IIS Manager, select the "Bonobo.Git.Server" node again and right-click to select "Edit Permissions ...". In the properties dialog popup, select the "Security" tab, select "IIS_IUSRS" and click "Edit" button. Check "Ready & Execute" option.

In the IIS Manager, select Bonobo.Git.Server->App_Data node and right-click to select "Edit Permissions ...". In the properties dialog popup, select the "Security" tab, select "IIS_IUSRS", check the "Write" and "Read" options.

Close the IIS Manager, and launch a web browser, enter http://localhost/Bonobo.Git.Server

In the http://localhost/Bonobo.Git.Server, login using default username and password (both default to "admin").

Create a repository (said, "HelloWorld"), and copy its url (which should be something like "http://localhost/Bonobo.Git.Server/HelloWorld.git")

Section 2: Install VS2010 extension for Git 

Download and install Git Extension from the following link:

https://code.google.com/p/gitextensions/

Download and install Git Source Control Provider from the following link:

http://gitscc.codeplex.com/releases/view/46589

Launch Visual Studio 2010, select "Tools->Options" from its menu.

Select "Source Control" in the left panel, and set the "Current Source Control plugin" combobox selection to "Git Source Control Provider"

Section 3: Commit and Push using Git

Now open a C# solution "HelloWorld.sln" in Visual Studio 2010, and right-click the solution to select "Create Git Repository".

Right-click the solution in VS2010 again and select "git(master)->push", in the settings page appear, click OK. The next dialog appeared is the push dialog, select the "url" option and enter "http://localhost/Bonobo.Git.Server/HelloWorld.git", then click "OK".

Enter the username and password (of http://localhost/Bonobo.Git.Server/) in the prompts.

Right-click the solution in VS2010 again and select "git(master)->commit", enter some comments for the commit, and then click "Commit and Push". (if asked to stage and commit all files, click Yes / OK). Alternatively you can go to "Pending changes" -> enter comment -> commit, and then do the push.

Section 4: Useful Links:

http://bonobogitserver.com/install/
http://blog.discountasp.net/using-git-with-visual-studio-2010-an-introduction-2/

Saturday, August 24, 2013

VS IDE Post-build Event: Copy Files

The following line (specified in the "Post-build event command line" under "Build Events" of the project property) will copies the dll generated in a Visual Studio project to a folder "Libs" in the solution directory:


xcopy $(TargetDir)*.dll "$(SolutionDir)Libs" /D /Y

Monday, July 22, 2013

Open a Folder Browser with Create Button in MFC

Below is the code snippet that implements a C++ function to open a folder browser in MFC with a Create Folder button, and return the path to the selected folder.


#include "StdAfx.h"
#include "shlobj.h"

CString CAppUtilManager::BrowseForDirectory() const
{
 int MAX_PATH=256;
 TCHAR display_name[MAX_PATH];
 TCHAR path[MAX_PATH];
    BROWSEINFO bi = { 0 };
    bi.lpszTitle = _T("Select an existing or created folder");
 bi.pszDisplayName=display_name;
 bi.ulFlags |= BIF_NEWDIALOGSTYLE;
    LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

 CString directory_path(_T(""));

    if(pidl != 0)
    {
        // get the name of the folder and put it in path
        SHGetPathFromIDList (pidl, path);

        //Set the current directory to path
        directory_path=path;

        // free memory used
        IMalloc * imalloc = 0;
        if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
        {
            imalloc->Free ( pidl );
            imalloc->Release ( );
        }
    }

 return directory_path;
}

Performing Statistical Hypothesis Test in C++ using AlgLilb: Student's t-test and Wilcoxon

Sometimes when comparing the performance of two algorithms such as in control, optimization, machine learning, etc. the comparison is done by running a number of simulations run on a set of benchmark problems for these algorithms, the statistical performance metrics are then derived from these simulation runs to compare their performances. However, it is usually not sufficient to claim one algorithm/method is better simply based on the average values of the performance metrics. In other words, performance comparison should also consider statistical hypothesis tests such as Student's t-test and Wilcoxon. Details of these methods can be found here:

https://en.wikipedia.org/wiki/Student's_t-test
http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test

This post is about how to do statistical hypothesis test in C++ using alglib

Step 1: Download AlgLib

Download the AlgLib from the following link:

http://www.4shared.com/zip/ZWXFztx-/alglib-250cpp.html

Step 2: Add AlgLib to C++ project

In this case, I am using VS2008 C++ IDE, unzip the downloaded AlgLib to the project solution folder, and add it to the C++ project by the following properties configuration:

1) Properties->Configuration Properties->C++->General->Additional Include Directories->$(ProjectDir)alglib-2.5.0.cpp\out
2) Properties->Configuration Properties->Linker->General->Additional Library Directories->$(ProjectDir)alglib-2.5.0.cpp\out
3) Properties->Configuration Properties->Linker->Input->libalglib.lib

Step 3: Student's t-test in C++
Suppose you implement your code in a source file main.cpp, define the Student's t-test as shown below in

#include "studentttests.h"
//data1: vector containing simulation results of a performance metric (say MetricA) for algorithm 1
//data2: vector containing simulation results of a performance metric (say MetricA) for algorithm 2
//if left-tail is less than the confidence threshold, left-tail rejected, and we have MetricA (algorithm 1) > MetricA (algorithm 2)
//if right-tail is less than the confidence threshold, right-tail rejected, and we have MetricA (algorithm 1) < MetricA (algorithm 2)
void ComputeStudentT(const std::vector<double>& data1, const std::vector<double>& data2, double& bothtails, double& lefttail, double& righttail)
{
 if(data1.empty() || data2.empty())
 {
  return;
 }

 ap::real_1d_array x;
 ap::real_1d_array y;
 
 int n=static_cast<int>(data1.size());
 x.setlength(n);
 for(int i = 0; i != n; i++)
 {
  x(i) = data1[i];
 }

 int m=static_cast<int>(data2.size());
 y.setlength(m);
 for(int i=0; i != m; ++i)
 {
  y(i)=data2[i];
 }

 /*************************************************************************
 Two-sample unpooled test

 This test checks three hypotheses about the mean of the given samples. The
 following tests are performed:
  * two-tailed test (null hypothesis - the means are equal)
  * left-tailed test (null hypothesis - the mean of the first sample  is
    greater than or equal to the mean of the second sample)
  * right-tailed test (null hypothesis - the mean of the first sample is
    less than or equal to the mean of the second sample).

 Test is based on the following assumptions:
  * given samples have normal distributions
  * samples are independent.
 Dispersion equality is not required

 Input parameters:
  X - sample 1. Array whose index goes from 0 to N-1.
  N - size of the sample.
  Y - sample 2. Array whose index goes from 0 to M-1.
  M - size of the sample.

 Output parameters:
  BothTails   -   p-value for two-tailed test.
      If BothTails is less than the given significance level
      the null hypothesis is rejected.
  LeftTail    -   p-value for left-tailed test.
      If LeftTail is less than the given significance level,
      the null hypothesis is rejected.
  RightTail   -   p-value for right-tailed test.
      If RightTail is less than the given significance level
      the null hypothesis is rejected.

   -- ALGLIB --
   Copyright 18.09.2006 by Bochkanov Sergey
 *************************************************************************/
 
 unequalvariancettest(x, n, y, m, bothtails, lefttail, righttail);
}

For ComputeStudentT() method, the parameter data1 is a vector containing simulation results of a performance metric (say MetricA) for algorithm 1, which is obtained from simulation runs on a benchmark problem (suppose there are 30 simulation runs, then data1 is a vector of length 30), while data2 is a vector containing results of MetricA for algorithm 2, which is obtained from simulation runs on the same benchmark problem.

Below shows how one can use the CompareStudentT() in the coding

RunSimulationsToObtainMetricAForAlgorithm1();
RunSimulationsToObtainMetricAForAlgorithm2();

std::vector<double> data1;
LoadMetricAForAlgorithm1IntoVector(data1);

std::vector<double> data2;
LoadmetricAForAlgorithm2IntoVector(data2);

double bothtails=0, lefttail=0, righttail=0;

double p_threshold=0.05; //set p threshold to 0.05 for 95% confidence level

ComputeStudentT(data1, data2, bothtails, lefttail, righttail);

/*
* two-tailed test (null hypothesis - the means are equal)
* left-tailed test (null hypothesis - the mean of the first sample  is
  greater than or equal to the mean of the second sample)
* right-tailed test (null hypothesis - the mean of the first sample is
  less than or equal to the mean of the second sample).
*/
if(bothtails < p_threshold)
{
 //null hypothesis rejected, the mean of data1 is either greater or less than tat of data2
 if(lefttail < p_threshold && righttail > p_threshold)
 {
  std::cout << "The true mean of MetricA(algorithm1) is smaller than tat of MetricA(algorithm2)" << std::endl;
 }
 else if(lefttail > p_threshold && righttail < p_threshold)
 {
  std::cout << "The true mean of MetricA(algorithm1) is greater than tat of MetricA(algorithm2)" << std::endl;
 }
 else
 {
  std::cerr << "error: t stat failed" << std::endl;
  exit(0);
 }
}


Step 4: Wilcoxon test in C++ 

Below shows the Wilcoxon test method in C++, the interface and usage of ComputeWilcoxon() method is same as ComputeStudentT() method

#include "wsr.h"

//if left-tail is less than the confidence threshold, left-tail rejected, and we have data1 > data2
//if right-tail is less than the confidence threshold, right-tail rejected, and we have data2 < data1
void ComputeWilcoxon(const std::vector<double>& data1, const std::vector<double<& data2, double& bothtails, double& lefttail, double& righttail)
{
 if(data1.empty() || data2.empty())
 {
  return;
 }

 ap::real_1d_array x;
 ap::real_1d_array y;
 
 int n=static_cast<int>(data1.size());
 int m=static_cast<int>(data2.size());

 if(n > m)
 {
  n=m;
 }

 x.setlength(n);
 for(int i = 0; i != n; i++)
 {
  x(i) = (data1[i] - data2[i]);
 }

 double assumed_median=0; //the given value

 /*************************************************************************
 Wilcoxon signed-rank test

 This test checks three hypotheses about the median  of  the  given sample.
 The following tests are performed:
  * two-tailed test (null hypothesis - the median is equal to the  given
    value)
  * left-tailed test (null hypothesis - the median is  greater  than  or
    equal to the given value)
  * right-tailed test (null hypothesis  -  the  median  is  less than or
    equal to the given value)

 Requirements:
  * the scale of measurement should be ordinal, interval or  ratio (i.e.
    the test could not be applied to nominal variables).
  * the distribution should be continuous and symmetric relative to  its
    median.
  * number of distinct values in the X array should be greater than 4

 The test is non-parametric and doesn't require distribution X to be normal

 Input parameters:
  X       -   sample. Array whose index goes from 0 to N-1.
  N       -   size of the sample.
  Median  -   assumed median value.

 Output parameters:
  BothTails   -   p-value for two-tailed test.
      If BothTails is less than the given significance level
      the null hypothesis is rejected.
  LeftTail    -   p-value for left-tailed test.
      If LeftTail is less than the given significance level,
      the null hypothesis is rejected.
  RightTail   -   p-value for right-tailed test.
      If RightTail is less than the given significance level
      the null hypothesis is rejected.

 To calculate p-values, special approximation is used. This method lets  us
 calculate p-values with two decimal places in interval [0.0001, 1].

 "Two decimal places" does not sound very impressive, but in  practice  the
 relative error of less than 1% is enough to make a decision.

 There is no approximation outside the [0.0001, 1] interval. Therefore,  if
 the significance level outlies this interval, the test returns 0.0001.

   -- ALGLIB --
   Copyright 08.09.2006 by Bochkanov Sergey
 *************************************************************************/
 wilcoxonsignedranktest(x, n, assumed_median, bothtails, lefttail, righttail);
}


Access SQLite using C++

This is a description of accessing SQLite using C++

Step 1: Download the CppSQLite

For me, I have been using the version which can be downloaded from:

http://www.4shared.com/zip/aNL2EdT_/sqlite.html

Step 2: Build the CppSQLite library

In this example, I am using VS2008 C++ IDE,

1) Extract the downloaded content to the folder sqlite
2) Open sqlite\SQLite_Static_Library\SQLite_Static_Library.sln
3) You may need to change the runtime libraries of the project to match those of the executable that will include the libraries, in order to avoid linker errors.
4) Build the library.

Step 3: Add the CppSQLite to your project

1) copy the sqlite folder to your solution folder
2) Include the library directory in your application (Project->Properties->Configuration Properties->Linker->General->Additional Library Directories->["$(ProjectDir)sqlite\SQLite_Static_Library\release"])
3) Include the static library built in step 2 (Project->Properties->Configuration Properties->Linker->Input->Additional Dependencies->[SQLite_Static_Library.lib])
4) Add the C++ wrapper to your project.  It's in the sqlite root dir:

      CppSQLite3.h
      CppSQLite3.cpp

Step 4: Implement code to access SQLite

The following a simple singleton class written in C++:

#ifndef _H_DB_MANAGER_H
#define _H_DB_MANAGER_H

#include <sstream>
#include <ctime>
#include "CppSQLite3.h"

class DBManager
{
public:
 virtual ~DBManager()
 {
  
 }

private:
 DBManager()
 {
  
 }

 DBManager(const DBManager& rhs) { }
 DBManager& operator= (const DBManager& rhs) { return *this; }

public:
 void record_data(int attr1_value, const std::string& attr2_value, int attr3_value)
 {
  std::ostringstream oss;
  oss << "INSERT INTO demo_table (attr1, attr2, attr3) VALUES (" << attr1_value << ", '" << attr2_value << "', " << attr3_value << ");" ;
  try{
   mDB.execDML(oss.str().c_str());
  }catch(CppSQLite3Exception& e)
  {
   std::cerr << e.errorCode() << ": " << e.errorMessage() << "\n";
  }
 }

public:
 static DBManager* getSingletonPtr()
 {
  static DBManager theInstance;
  return &theInstance;
 }

public:
 void open(const char* dbname)
 {
  try{
   remove(dbname);
   mDB.open(dbname);

   mDB.execDML("CREATE TABLE demo_table (id INTEGER PRIMARY_KEY, attr1 INTEGER, attr2 TEXT, attr3 INTEGER);");
  
  }catch (CppSQLite3Exception& e)
  {
   std::cerr << e.errorCode() << ":" << e.errorMessage() << "\n";
  }
 }
 void close()
 {
  mDB.close();
 }

private:
 CppSQLite3DB mDB;
};
#endif

Below is a simple explanation of the database manager class
  • The open() method recreate the database, and then create a datatable "demo_table" in the database file with three fields: attr1, attr2, attr3, attr1 and attr3 are INTEGER while attr2 is a TEXT. 
  • The record_data() method record a single row into the database "demo_table" 
  • The close() method should be called at the end of database operation to create database connection


To use the singleton class above, it is very easy, below is a simple example:
#include "DBManager.h"
DBManager::getSingletonPtr()->open("demo.db");
DBManager::getSingletonPtr()->record_data(1, "Hello World", 2);
DBManager::getSingletonPtr()->close();

Thursday, July 18, 2013

ERROR: Unable to update the dependencies of the project.

Today, out of blue, my vs2010 setup project is not working, keep telling me errors like:

ERROR: Unable to update the dependencies of the project. The dependencies for the object ‘assembly_name’ cannot be determined."

I searched online, it is said the error is due to "VS2010 QFE: Setup project compilation fails with command line" and find this hotfix from microsoft to fix the problem:

http://archive.msdn.microsoft.com/KB2286556/Release/ProjectReleases.aspx?ReleaseId=4994

Thursday, July 11, 2013

Compile and run Taucs on Windows

Taucs (http://www.tau.ac.il/~stoledo/taucs/) is a library of sparse linear solvers, which was frequently used in computational geometry and mesh processing. I have built the Taucs on Windows and made a small demo program for using Taucs in VS2010, which will run on Windows platform and solve a set of linear equations. The package can be downloaded from:

http://www.4shared.com/zip/b35JMBfc/Taucs.html

The process of building and test-running Taucs on Windows is as follows: after download the package from the link above, cd to the taucs_full folder, and enter the following command:

$"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat"
$configure.bat
$nmake
$bin\win32\direct -mesh2d 400 -log stdout -snmf
$cl -c -Isrc -Ibuild\win32 -EHsc test_taucs.cpp
$cl test_taucs.obj libtaucs.lib libmetis.lib liblapack.lib libf77blas.lib libcblas.lib libatlas.lib vcf2c.lib -link -LIBPATH:lib\win32 -LIBPATH:external\lib\win32
$test_taucs.exe

To start a C++ project that uses Taucs, copy the Taucs_full to the solution folder, then add the following settings to the C++ project properties page.

IncludePath:
$(SolutionDir)taucs_full\build\win32
$(SolutionDir)taucs_full\src

LibPath:
$(SolutionDir)taucs_full\external\lib\win32
$(SolutionDir)taucs_full\lib\win32

Additional Lib:
libtaucs.lib
libmetis.lib
liblapack.lib
libf77blas.lib
libcblas.lib
libatlas.lib
vcf2c.lib
blas_win32.lib

The above details of these configurations and settings can be found in the RunTaucs project in the package from the above link.


Tuesday, July 9, 2013

Step-by-step Setup of log4net with bug fixes for working with VS2010

Step 1: Download log4net
I used log4net for logging in my C# application, however, the log4net version downloaded from the official website at the time has a number of bugs, I have removed those bugs and have it running smoothly with my C# application within the VS2010, the bug-fixed package can be downloaded from:

http://www.4shared.com/zip/VkND-sg4/log4net-1211.html

Step 2: Configure log4net in C# application
To configure log4net, after downloading the bug-fixed version from the above link and unzip it, add the project to your VS2010 solution in the IDE, then double-click your app.config from your VS2010 IDE to open it. Replace its content with the following:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
  <appSettings file="">
    <clear />
    <add key="log4net.Internal.Debug" value="true" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <log4net>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="log-file.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
  </log4net>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

The above configuration works with .net 4.0 and log the errors and events to the file named log-file.txt. Next open the Program.cs and add the following line as the first in the Main() method:

log4net.Config.XmlConfigurator.Configure();

Step 3: Use log4net to do the logging
Now open one of your class (e.g. let's say the class name is Animal and has a method called Bark()), add the following line to where you declare your member variables:

private static ILog log = LogManager.GetLogger(typeof(Animal));

Now in the method Animal.Bark(), add the following line to log event:

log.Log("some message");

or the following line to log error:

log.Error("some error");

Monday, February 14, 2011

The designer could not be shown for this file because none of the classes within it can be designed

I encountered this bug in vs2008 winform C# programs after messing around with installing vs6, vs2005, vs2008 and vs2010 installation. the bug caused the winform not able to render itself during the design time and throws the following error message:


The designer could not be shown for this file because none of the classes within it can be designed




After doing much google search and found not working solution, it happens to me that maybe the .Net 3.5 version in my PC is corrupted. I therefore download the .net cleaning utility from
http://blogs.msdn.com/b/astebner/archive/2008/08/28/8904493.aspx
and after running the tool to clean .Net 3.5 from my computer and reinstalling the vs2008. everything works!

Friday, January 14, 2011

System.Resources.MissingManifestResourceException" error message

Today i encountered this nusty error message when i was doing refactoring of my C# project in which i downgrade the original vs2010 project to vs2005 project and separate the project into a class project and a winform project. During the design time the winform partial class code its designer partial class code does not appear under the same subtree in the vs2005 explorer view. and after compile and build, the application runs into this error when run in debug mode. The problem is due to i create a folder and copy the code over from the original project within the vs2005. This problem is finally solved by creating the folder, then copy the codes manually from the original project folder, then select from the menu "Project->Show All Files", now the folder created will show up in the vs2005 explorer viewer, right-click the folder and select "Include in the Project". Now the winform partial class code will automatically attached with the designer partial class code and the error message will go away.

Wednesday, January 12, 2011

Multiple subreport appear even when they don't have any data

In my case, i have five subreports, each from a different business object list. Due to the initial mass-up, one business object dataset is copied into the rdlc subreport of the other 4. As a result, when this particular subreport has data, the other 4 subreport showed up as well even though they don't have data. The problem is solved by removing that particular object's dataset from the other 4 subreports

Monday, January 3, 2011

Regular Expression Replacement in Visual Studio

Text replacement in visual studio using Regular Expression can be very handy during refactoring in large projects.

E.g. to find "new DoubleFieldEntry(Convert.ToString(_obj.[Text to Keep]));" and replace with "new DoubleFieldEntry(_obj.[Text to Keep]);"

The find regular expression is "new DoubleFieldEntry\(Convert.ToString\({_obj.*}\)\);" and the replace regular expression "new DoubleFieldEntry\(\1\);"


The above replacement in the figure replaces codes in the current project such as "new IntFieldEntry(Convert.ToString(_obj.SaleID))" to "new IntFieldEntry(_obj.SaleID)"