MtRock.cs Paradise 16

Qingshuan’s Programming Blog

use glui in VS

Posted by linuxprogram on August 18, 2008

glui in VC:
1. unzip glui-2.36.zip
2. build (i used batch build and selected all)
3. copy lib/glui32.lib  to %VS2005_DIR%\VC\platformSDK\Lib
4. copy include/glui.h to %VS2005_DIR%\VC\platformSDK\Include\GL. finish. (further  work for compiling projects):

Project->settings->General ->Microsoft Foundation Classes(DropList)->Select”Use MFC in a Shared DLL”

..

Errors Like:msvcrt.lib(MSVCRT.dll) : error LNK2005: _exit already defined in LIBC.lib (crt0dat.obj) Solution:ADD msvcrt.lib libc.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib

Posted in C/C++/C#, Computer Graphics | 2 Comments »

BOOST/CGAL/QT installation with Microsoft Visual Studio 2005

Posted by linuxprogram on August 18, 2008

Quoted from CGAL3.3安装过程介绍 by wiarw @Monday, August 18 2008

sfasafCGAL采用QT作为它的GUI,并利用了boost、GMP、TAUCS等库,因此在安装CGAL前需要配置好这些依赖库。这里我装的是CGAL3.3版本,平台是Windows XP sp2。

1. 安装Boost. boost的安装比较简单,我得到的是boost 1.33.1版本(http://sourceforge.net/project/showfiles.php?group_id=7586)由于是exe文件,直接运行即可。此时会添加“BOOSTROOT”环境变量。

2. 安装QT。CGAL3.3需要的是QT3,QT4和QT3相比在结构上存在较大改动,因此与CGAL并不兼容,这个问题可能在以后CGAL的更新版中会解决。如果想得到QT4可访问官网http://www.trolltech.com。QT3则需要通过http://webdev.cegit.de/snapshots/qtwin/得到。先将得到的qt-win-free-3.3-2007-06-07-src.tar.bz2解压至不包含空格的路径下某一目录中(比如D:\QT-3)。下面就是设置环境变量。在我的例子中,环境变量如下:

QTDIR = D:\QT-3

QMAKESPEC = win32-msvc2005

PATH= %QTDIR%\bin;%PATH%

然后更改VS2005的环境变量设置脚本vsvars32.bat(我的是在D:\Program Files\Microsoft Visual Studio 8\Common7\Tools\vsvars32.bat),其关键内容如下:

@set DevEnvDir=D:\Program Files\Microsoft Visual Studio 8\Common7\IDE
@set QTDIR=D:\qt-3
@set QMAKESPEC=win32-msvc2005

@set PATH=%QTDIR%\bin;D:\Program Files\Microsoft Visual Studio 8\Common7\IDE;D:\Program Files\Microsoft Visual Studio 8\VC\BIN;D:\Program Files\Microsoft Visual Studio 8\Common7\Tools;D:\Program Files\Microsoft Visual Studio 8\Common7\Tools\bin;D:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\bin;D:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;D:\Program Files\Microsoft Visual Studio 8\VC\VCPackages;%PATH%
@set INCLUDE=%QTDIR%\include;D:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE;D:\Program Files\Microsoft Visual Studio 8\VC\INCLUDE;D:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include;D:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\include;%INCLUDE%
@set LIB=%QTDIR%\lib;D:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB;D:\Program Files\Microsoft Visual Studio 8\VC\LIB;D:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib;D:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\lib;%LIB%
其中红色部分为要添加的内容。

然后打开VS2005提供的命令提示符工具Visual Studio 2005 Command Prompt,转至QT根目录下(我的是D:\QT-3),运行configure-msvc2005.bat,大概40分钟后即可安装完成。

3.安装CGAL。CGAL的安装过程相对简单,在Wizard中会要求填写Boost的根目录,并且会安装GMP和TAUCS的头文件和库文件。安装过程中需要保证网络畅通无阻,因为会从网络下载CGALCore、CGAL、CGALQt等对应VC80的库文件。

4.测试是否安装成功。在CGAL的安装目录下有很多的example和demo,打开某个.vcproj文件,经VS2005转换为.sln后,更改项目配置,将Linker->Input中的库qt-mt.lib改为qt-mt3.lib保存。在Tools->Options下,添加Boost的Include和Library路径。编译运行即可成功。

Posted in C/C++/C#, Computer Graphics | Leave a Comment »

A typo in “Triangulations in CGAL”

Posted by linuxprogram on August 8, 2008

P7 from “Triangulations in CGAL” by Jean-Daniel Boissonnat Olivier Devillers Sylvain Pion Monique Teillaud Mariette Yvinec:

Posted in Computer Graphics | Leave a Comment »

Pirate game

Posted by linuxprogram on July 14, 2008

Sometimes you find a puzzle really messy, and you just put it aside. Next time when you pick it up, however, it magically becomes all clear.

Computing people all heard of the pirate game, and the following is some kind of the solution.

 

1, (100)                               1s

2, (0 ,100)                           1a,2s

3, (1 ,0 ,99 )                        1s,2a,3s

4, (0 ,1 ,0 , 99)                    1a,2s,3a,4s

5, (1 ,0 ,1 , 0, 98)                1s,2a,3s,4a,5s

………………………………

 

So for Nth, his solution would be:

 

  1. (N)p    := 100 – (n-1)/2     // himself
  2. (N-1)p  := 0               // next to him
  3. For i from 0 to N-2

          i := 1 – (i+1)

  4. End

Posted in Algo | Leave a Comment »

[C#/.NET] Convert Integer to C# Enums

Posted by linuxprogram on March 5, 2008

Enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

DayOfWeek wednesday = (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Wednesday);

Posted in C/C++/C# | Leave a Comment »

[C#/.NET] Return in try block & Play in “finally”

Posted by linuxprogram on February 21, 2008

Code:

 

Output:

Initialized

Output i in
finally

j = Assignment in
return statement in
try / i = Assignment in Finally

Posted in C/C++/C# | Leave a Comment »

[C++/.NET] Wrapping Exceptions

Posted by linuxprogram on February 19, 2008

From:
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/dv_fxdesignguide/html/96b5277a-e256-48a4-83e2-43f833d4f66b.htm

To wrap an exception, you specify it as the inner exception of a new exception and then throw the new exception. This practice should be used only in situations where the original exception is not meaningful to the person who receives the exception, or the call stack for the exception is misleading or uninteresting. For example, consider a library that provides functionality for managing XML-based configuration files. Internally, the configuration file manager uses an XML reader to read files. If a configuration file is incorrectly formatted, the XML reader could throw an exception that includes a message and call stack details for the XML reader and its supporting types, which are meaningless to the application user. In this scenario it is appropriate for the configuration file manager to wrap the XML reader exception and re-throw a new exception that indicates the true nature of the problem.

The following guidelines help ensure that you wrap exceptions correctly and only when appropriate.

Consider wrapping specific exceptions thrown from a lower layer in a more appropriate exception, if the lower layer exception does not make sense in the context of the higher-layer operation.

This should be done rarely because it makes debugging more difficult. It is appropriate when you are certain that the lower layer is never the true source of the error.

Avoid catching and wrapping non-specific exceptions.

This practice should be avoided because it hides errors. Exceptions to this rule include cases where the wrapper exception communicates a severe condition that is much more interesting to the caller than the actual type of the original exception. For example, the TypeInitializationException exception wraps all exceptions thrown from static constructors.

Do specify the inner exception when wrapping exceptions.

This allows tools to display the underlying details of the problem and can aid in debugging code. The following code example demonstrates wrapping an exception.

C#  

Copy Code

public void SendMessages()

{

try

{

EstablishConnection();

}

catch (System.Net.Sockets.SocketException e)

{

throw new CommunicationFailureException(

“Cannot access remote computer.”,

e);

}

} 

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the “Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries” book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also

Concepts

Exception Throwing

Other Resources

Design Guidelines for Developing Class Libraries
Design Guidelines for Exceptions

Posted in C/C++/C# | 1 Comment »

[.NET] Create custom Exception in .NET

Posted by linuxprogram on February 15, 2008

Quoted from http://blog.gurock.com/articles/creating-custom-exceptions-in-dotnet/

Introduction

Although the .NET framework contains all kinds of exception types which are sufficient in most cases, it can make sense to define custom exceptions in your own applications. They can greatly simplify and improve the error handling and thus increase the overall code quality. Whatever your reasons are for using custom exceptions, this article shows you how to create them and what to pay attention to when it comes to serialization, .NET guidelines and analysis tools.

System or Application?

Any custom exception you create needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class. According to the .NET framework documentation, SystemException is meant only for those exceptions defined by the common language runtime whereas ApplicationException is intended to be used by user code:

“ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system.”

So, ApplicationException seems like a good choice as base class for custom exceptions at first. But there has been quite a lot of discussion about this topic and according to this posting by a Microsoft employee working on .NET, the usage of ApplicationException is no longer recommended. It seems that the current .NET framework and its documentation is already outdated when it comes to the ApplicationException class:

“We added ApplicationException thinking it would add value by grouping exceptions declared outside of the .NET Framework, but there is no scenario for catching ApplicationException and it only adds unnecessary depth to the hierarchy. […] You should not define new exception classes derived from ApplicationException; use Exception instead. In addition, you should not write code that catches ApplicationException.”

So, the ApplicationException exception class will eventually be deprecated. I therefore let the custom exceptions here in this article derive directly from the Exception class.

Minimal Exceptions Types

The absolute minimum a new custom exception class needs to have is a name. Let’s say you are designing the login mechanism for a database application and as part of this job you need to create a custom exception which is thrown if a login attempt fails. A good name for such an exception would be LoginFailedException. An absolute minimum implementation in C# then looks like:  

public class LoginFailedException: System.Exception{ }

As you can see, all you need to do to create a basic custom exception is to derive from the Exception class. There’s only one problem with this definition. Since C# unfortunately doesn’t inherit constructors of base classes, this new type only has the standard constructor with no parameters and is therefore relatively useless. So, we need to add at least one constructor which does something useful:

public class LoginFailedException: System.Exception

 {

    // The default constructor needs to be defined

    // explicitly now since it would be gone otherwise.

    public LoginFailedException()

    {

    }

    public LoginFailedException(string message): base(message)

    {

    }

 }

By now we can use our custom exception like most other exceptions. We can throw an instance of LoginFailedException and pass a message which describes the occurred error. But .NET exceptions can do more. You can normally pass a so called inner exception to one of the constructors which indicates that the created exception is a direct result of a previous one. This inner exception can then be retrieved via the InnerException property. This way you can build entire exceptions chains. Since this can be quite useful sometimes, we extend our existing implementation with this additional constructor:

public class LoginFailedException: System.Exception

 {

    // …

    public LoginFailedException(string message, Exception innerException): base(message, innerException)

    {

    }

 }

Looks good so far. We now have a working custom exception which is capable of handling error messages and inner exceptions. Great!

Serialization Basics

Let’s now have a look at what FxCop says to our exception type. In case you don’t know what FxCop is, it’s a nice analysis tool which checks .NET assemblies for conformance to the .NET framework design guidelines. FxCop doesn’t seem to like our exception yet:

  • Error for ImplementStandardExceptionConstructors:
    Add the following constructor:

    LoginFailedException(SerializationInfo, StreamingContext)

  • Error for MarkISerializableTypesWithSerializable:
    Add [Serializable] as this type implements ISerializable

Doesn’t look that great anymore, does it? However, the good news is that this can be fixed quite easily. Both errors deal with the serialization mechanism of .NET in some way. In case you don’t know what serialization is, it’s basically a way to convert an object into a form which can easily be transported or persisted. The counter part to serialization is the deserialization which is responsible for restoring the original object.

Let’s begin with the second error. Any class that is intended to be serializable needs to be marked with the Serializable attribute and since our base class Exception implements the ISerializable interface which is used to customize the serialization process, FxCop wonders why we didn’t add it. So, in order to comply with the serialization guidelines, we simply need to add the Serializable attribute and the second error is already fixed:

[Serializable]        

public class LoginFailedException: System.Exception

 {

    // …

 }

Correcting the first error is a bit more tedious. FxCop complains that we forgot to add an additional standard exception constructor. This constructor is used to customize the serialization process of objects. And since the base Exception class defines such a constructor and C# still lacks the support of constructor inheritance, we are better off adding such a beast:

[Serializable]

 public class LoginFailedException: System.Exception

 {

    // …

    protected LoginFailedException(SerializationInfo info, StreamingContext context): base(info, context)

    {

    }

 }

Looks good. FxCop keeps quiet now and we finally have a fully functional exception type which can be used like any predefined exception. It can handle simple error messages and inner exceptions and can even be serialized and deserialized correctly.

Customizing Serialization

Let’s pretend we want to extend our exception by being able to store no only the error message why the login attempt failed, but also which username caused the error. This is pretty straightforward. We just add a new field and a new property to our existing class:

 [Serializable]

public class LoginFailedException: System.Exception{
   private string fUserName;

   // …

   public string UserName{

      get { return this.fUserName; }

      set { this.fUserName = value; }

   }

}

We are now able to set and get the name of the user specified during the login sequence. So far so good, but what about the serialization now? Does it still work as expected, that is, will the username be preserved when being serialized and deserialized? Unfortunately, the answer is ‘no’. You need to take care of it yourself.

Before we extend our exception to do exactly this, I tell you how the customization of the serialization and deserialization works in general. At first, you need to implement the ISerializable interface. This interface contains a single method, named GetObjectData, which is responsible for storing object fields during the serialization process. To do this, you just need to populate a passed SerializationInfo object.

The deserialization process works exactly the other way round. When an object is being deserialized, the previously filled SerializationInfo object is passed to the constructor of your class in which you are responsible for restoring the original object fields. Translated to our example exception, this looks like:

[Serializable]

public class LoginFailedException: System.Exception

{
   private string fUserName;

   // …

   protected LoginFailedException(SerializationInfo info,

            StreamingContext context): base(info, context) {
      if (info != null){

         this.fUserName = info.GetString(“fUserName”);

      }

   }

   public override void GetObjectData(SerializationInfo info,

        StreamingContext context)    {

      base.GetObjectData(info, context);
      if (info != null) {

         info.AddValue(“fUserName”, this.fUserName);

      }
   }

}

Let’s begin with the serialization. Since our base Exception class already implements the ISerializable interface we can omit it in the list of implemented interfaces and base classes and only need to override and fill the GetObjectData method. At first, we call the GetObjectData method of the base class. This is needed to save the fields common to all exceptions, like the error message, stacktrace information or the inner exception. Then we simply store our username by adding it to the passed SerializationInfo object.

The deserialization works similarly. We just restore our username field in the constructor with the aid of the previously filled SerializationInfo object. To verify that our custom exception works like expected and to demonstrate how an entire serialization and deserialization process looks like, I wrote the following unit test:

using System.Runtime.Serialization.Formatters.Binary;


// …

[Test]    

public void TestUserName(){

   LoginFailedException e = new LoginFailedException();

   e.UserName = “dotnet user”;
   using (Stream s = new MemoryStream())

   {

      BinaryFormatter formatter = new BinaryFormatter();

      formatter.Serialize(s, e);

      s.Position = 0; // Reset stream position

      e = (LoginFailedException) formatter.Deserialize(s);

   }

   Assert.AreEqual(e.UserName, “dotnet user”);

}

// …

During the serialization and deserialization process, the username field is now preserved correctly and thus the Assert class remains silent and the test passes. That this is not the case if we haven’t customized the serialization process can be confirmed quite easily. Simply comment out the GetObjectData method and the call to GetString in the constructor, rerun the test and you’ll see it failing since the UserName property will now return null instead of the correct username.

Closing Words

Aside from the ApplicationException versus Exception discussion, this article has been written with the .NET 1.1 version in mind. However, I don’t expect upcoming versions of the .NET framework to differ (greatly) from the techniques described here in this article, so that the information given here should still be of value in the future. As usual, if you have any comments or questions feel free to contact me at tg@gurock.com. Oh, and by the way, you can download the source of the LoginFailedException class and its test here.

Posted in C/C++/C# | Leave a Comment »

Put your forward declaration inside the namespace symbol

Posted by linuxprogram on February 14, 2008

A stupid forward declaration made one of my whole day miserable.

At the time it says the class cannot be found, I put the forward declaration in the front of the header file. And that, turned out, still, not working. As a result of no result from googling, I put off all that-class-related method wrapping and continued on other part of my work.

Now the reason comes to surface. Stupid ME put the stupid forward declaration outside the namespace symbol. THAT is the reason, and that is THE reason, why I wasted that much time.

Stupid me, learn, and go forward.

Posted in C/C++/C# | Leave a Comment »

[C++/.NET] Conversion from System::String ^ to CString

Posted by linuxprogram on February 12, 2008

For conversion from System::String to CString:

Most Efficient:

using
namespace System::Runtime::InteropServices;

System::String^ str = “A test string.”;

char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);

CString target = str2;

Marshal::FreeHGlobal((IntPtr)str2);

Simplest but least Efficient

CString target2 = CString(str);

Posted in C/C++/C# | Leave a Comment »