More servicesWindows Live
HomeHotmailSpacesOneCare
 
MSN
Sign in
 
 
Spaces home  蒋晟(JIANG,Sheng), a Micro...PhotosProfileFriendsMore Tools Explore the Spaces community
Thanks for visiting!

蒋晟(JIANG,Sheng), a Microsoft MVP @Austin, Texas

So proud to be re-awarded Microsoft Most Valuable Professional!
October 05

Type 'System.Web.UI.WebControls.Parameter' does not have a public property named 'DbType'

In Visual C# 2005 SP1, I added an object data source to a web page that uses my business class as the select method. The method has one parameter of type Guid. The data source wizard generates code like this

<asp:Parameter DbType="Guid" Name="rowId" />

Although the web server has .Net 2.0 SP1 installed (I checked the registry), it still throws an error

Type 'System.Web.UI.WebControls.Parameter' does not have a public property named 'DbType'

The walk around is easy:

<asp:Parameter Type="Object" Name="rowId" />

September 08

When Microsoft Office Live Meets Google Chrome

To use Microsoft Office Live, your computer must meet one of the following requirements:

Microsoft Internet Explorer 6 or 7, running on Microsoft Windows XP, Windows Server 2003 or Windows Vista. You can download Internet Explorer from the Windows Internet Explorer page.
Mozilla Firefox running on Windows XP, Windows Server 2003, Windows Vista, or Mac OS X 10.2.x and later. You can download Firefox from the Firefox download page.

April 07

MFC Feature Pack发布

Visual C++项目组今天发布了Visual C++ 2008 Feature Pack。这个Feature Pack包含了一些以前需要付费给BCG Soft才可以使用的控件,例如BCG著名的窗口布局和风格自定义功能,不过也有一些有用的控件,例如文件夹列表文件夹树属性窗格等等。

这个Feature Pack也包含从Dinkumware获得授权的一些对STL的扩展,实现了TR1草案。这包含新的随机算法、集合类和正则表达式支持。关于TR1的更多信息,可以参考Dinkumware的网站

安装了这个Feature Pack之后,生成的应用程序在发布时需要同时发布新版本的MFC和CRT组件。预计对这个Feature Pack的技术支持策略会和VC6中从Dinkumware获得授权的STL库会是一个级别,也就是说,BCG Soft、Dinkumware和微软都会提供技术支持。如果在安装了这个Feature Pack之后需要安装Windows SDK 6.1,那么在安装完SDK之后需要修复Visual Studio 2008以保持文件是最新的。

目前发布的这个补丁只支持英文版的Visual Studio 2008 标准版或更高版本,其他语言版的Visual Studio 2008 要获得这些新的功能的话,需要等到Visual Studio 2008 SP1发布。Visual Studio 2008会包含这个Feature Pack。

March 24

Detect if a MSI component is installed

A C# program for those who don't know MSI SDK or C++. C++ programmers can find the API inside the msi.h  file in Windows SDK.

class Program
{
    static int Main(string[] args)
    {
        uint pathSize = 0;
        try
        {
            foreach (string componentId in args)
            {
                MsiInstallState state = MsiLocateComponent(
                    componentId, null, ref pathSize);
                if (state != MsiInstallState.Local)
                {
                    return ERROR_UNKNOWN_COMPONENT;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            return ERROR_MOD_NOT_FOUND;
        }
        return 0;
    }
    [DllImport("msi.dll", CharSet = CharSet.Auto)]
    extern static internal MsiInstallState MsiLocateComponent(string component, string path, ref uint pathSize);
    /// <summary>Enumeration of MSI install states.</summary>
    internal enum MsiInstallState : int
    {
        Local = 3
    }
    const int ERROR_MOD_NOT_FOUND = 126;
    const int ERROR_UNKNOWN_COMPONENT = 1607;
}

March 17

Hard Drive broke

The first 3 Dell support technicians tried to persuade me to clean the temp files, to remove unnecessary startup programs and to reinstall Windows. It does not help if the computer complains an error during self test. I keep saying a self test error can not be solved by twisting the OS, but they won't listen. After educating the representatives for a week I finally got one that has better experience (and better English) to examine my computer. A full system test shows bad sectors on the hard drive, and totally toasted the hard drive. Luckily I just bought the computer for 6 months so I asked for a replacement. Dell sent me one in 2 days and I sent back the broken one.

Now my back up hard drive started to fail ... Time to call Seagate.

January 09

Smart harddrive error

In case anyone is googling this message
Hard Drive SELF MONITOR SYSTEM has reported that a parameter has exceed its normal operating range
Dell recommends that you back up your data regularly
Press F1 to continue, Press F2 to enter setup
 
Run event log and look for warning messages. I have several messages looked like this
C:\Program Files\Microsoft Windows OneCare Live\Database\WinSS_st.edb (3612) C:\Program Files\Microsoft Windows OneCare Live\Database\WinSS_st.edb: A request to read from the file "C:\Program Files\Microsoft Windows OneCare Live\Database\WinSS_st.edb" at offset 180224 (0x000000000002c000) for 4096 (0x00001000) bytes succeeded, but took an abnormally long time (60 seconds) to be serviced by the OS. In addition, 0 other I/O requests to this file have also taken an abnormally long time to be serviced since the last message regarding this problem was posted 0 seconds ago. This problem is likely due to faulty hardware. Please contact your hardware vendor for further assistance diagnosing the problem.
 
msnmsgr (2980) \\.\C:\Users\jiangsheng\AppData\Local\Microsoft\Messenger\<windows live id>\SharingMetadata\Working\database_8E6C_5899_6C58_7E41\dfsr.db: A request to write to the file "\\.\C:\Users\jiangsheng\AppData\Local\Microsoft\Messenger\<windows live id>\SharingMetadata\Working\database_8E6C_5899_6C58_7E41\fsr.log" at offset 19456 (0x0000000000004c00) for 512 (0x00000200) bytes succeeded, but took an abnormally long time (75 seconds) to be serviced by the OS. This problem is likely due to faulty hardware. Please contact your hardware vendor for further assistance diagnosing the problem.
 
The reaction is obvious: contact Dell Customer Support.
 
thankfully, I have dialy incremental backup and weekly full system backup, but my dialy backup has been failing. So I will lose a week's data, not a big deal.
January 07

MFC更新Beta版

一个面向Visual C++ 2008的MFC更新测试版已经发布,同时也提供了文档的下载。这个版本包含新的界面的特性,例如Office Ribbon、2003和XP风格,Visual Studio风格和MDI标签。另外,这个版本也包含部分TR1的实现,例如正则表达式、更加丰富的集合和智能指针。

另外,在下载页面居然说这个版本还不支持Visual Studio 2008 Service Pack 1的Beta版,正式版才出来几天SP1的测试版就出来了?

September 18

科学,我的信仰?

花が咲き そして散る
Flowers open out and then they fade
花开,然后花落
星が輝き やがていつかは消える
Stars shine and later or sooner they go off
星光闪耀,不知何时熄灭
この地球も 太陽も 銀河系 大いなる宇宙も いつか死するときがくる
Both this Earth, the Sun, the Milky Way, and even for the big Universe which is growing, later or sooner the time to die will come
这个地球,太阳,银河系,甚至整个宇宙也总会有消失的时候
人間の一生などそれらに比べれば瞬きほどの僅かなものであろう
And compared to these things, human life is insignificant.
人的生命和那些相比只不过是一瞬间吧
その僅かなひとときに 人は生まれ
In that little moment, a man is born
在那一瞬间中,人诞生
笑い 涙し 戦い 傷つき 喜び 悲しみ 誰かを憎み 誰かを愛し
Laughs, cries, fights, is injured, feels joy and feels sadness, loves someone, hates someone
微笑,哭泣,战斗,伤害,喜悦,悲伤,憎恨谁,喜欢谁
全ては刹那の邂逅
Everything is random and in a instant
所有的一切都是刹那间的邂逅
そして誰しもが死という永遠の眠りに包まれる
And, in the end, covered by an eternal sleep called Death.
谁都不能逃脱死亡的长眠
——沙加在沙罗双树涅磐时的遗言,引自《圣斗士·冥王篇·沙罗双树下之卷》
昨天有位朋友问我,你到底信仰什么,我当时的回答是科学;我不信仰一切把自然科学解释不了的现象归类于一个超自然的存在的宗教。我当时的逻辑是超自然是无法被定义的。这是因为你可以定义一个东西是什么,但是你不能定义一个东西为不是什么,因为定义是确定的,而定义的反面(不是什么)的范围是无法确定的。后来想想,我自己对我的信仰下的定义也不是很准确,因为科学是在不断发展的。
毕达哥拉斯曾认为万物之源是数,但是他对数的定义仅限制于有理数。当他的学生希帕索斯用毕达哥拉斯定理发现当两个直角边长度都是1时斜边的长度是不是一个有理数的时候,这个发现震撼了整个毕达哥拉斯学派的根基。在传说中,希帕索斯被愤怒的毕达哥拉斯学派的人沉到海中淹死了。现在我们知道除了无理数之外还存在复数,在高维空间内我们还有超复数。人的信仰,即使是一个数学伟人的信仰,也阻挡不了数学发展的脚步。
再举一个例子。几何学是基于一系列假设(数学上叫做公理)的。在欧几里得的《几何原本》中,被称为平行公理的第五条公理(或者其等价命题)表述如下:
    通过一个不在直线上的点,有且仅有一条不与该直线相交的直线。 
这个定理只在证明第二十九个命题中才用到,以后再也没有用到。也就是说,看起来欧几里得几何中此定理的地位可有可无。关于第五公理的地位争论了两千多年,终于在十九世纪二十年代得到解决。俄国数学家罗巴切夫斯基试图用反证法证明这个命题。他用一个和第五公理冲突的公理替代了第五公理,然后试图推导出一个自相矛盾的理论体系。和他的预期相反,他推导出了一门新的几何学,在后来被称为罗巴切夫斯基几何。如果认为空间的曲率是可以变化的,那么第五公里就可以被去掉,而欧几里德几何和罗巴切夫斯基几何成为鲍耶提出的绝对几何在常曲率空间的特例。
我们上学的时候都学过,太阳系有九大行星。然而在2006年,国际天文家联合会将冥王星从行星中除名,太阳系只剩下八大行星。如果客观真理可以这样更改的话,究竟什么才是科学?建立在科学方法上的主流意见就是科学么?我们都知道哥白尼这个反例了。另外,科学真的可以用科学手段来验证么?像恒星的演化这样的课题,短命的人类永远只能用理论来解释观测到的现象,没有人能有足够的寿命来验证恒星演化论的真伪。科学,不过是人类对有限的世界的解读而已。
我对这个问题没有答案。我对那个朋友的回答可能需要更改一下,我可能信仰客观唯心主义。我认为物质的存在不能用客观的方式来证明,而只能用主观的理论来表述。我认为科学是建立在一系列假设上的,也只能描述基于这些假设的世界。科学越发展,可以描述的现象就越多,但是——引用一下哥德尔第二条定理——任何相容的形式体系不能用于证明它本身的相容性,科学是不能用科学方法来验证的。
August 05

AutoComplete with DataSource

Download the code for this article (22KB)

.Net 2.0 introduced autocompletion in TextBox and ComboBox. It is obvious that autocomplete is not very useful when the number of options is small. However, when your option becomes too many, pre-filling of all options to an AutoCompleteStringCollection becomes impractical, especially when your data comes from a remote computer. An alternative is to replace the AutoCompleteCustomSource in a TextChanged event, however, users are getting random AccessViolationException when trying to replace it.  In this article I will demonstrate another alternative, using a BindingSource as the data source of options and bypassing the .Net framework and call the underline Windows API directly.

The first thing I need to do is to port the APIs to managed code. The autocompletion API is exposed as a COM object, so I need to write managed version of its interfaces:

    [ComImport]
    [InterfaceType(ComInterfaceType::InterfaceIsIUnknown)]
    [Guid("EAC04BC0-3791-11D2-BB95-0060977B464C")]
    [SuppressUnmanagedCodeSecurity]
    interface  class IAutoComplete2
    {
             [PreserveSig] int Init(
            HandleRef hwndEdit,
            IEnumString^ punkACL,
             String^ pwszRegKeyPath,           
            String^ pwszQuickComplete
        );
        void Enable( [MarshalAs(UnmanagedType::Bool)] bool value);

        int SetOptions(int dwFlag);

        void GetOptions([Out]IntPtr pdwFlag);
    };
Second, I need to create the autocomplete object and query the IAutoComplete2 interface:

       Type^ autoCompleteType = Type::GetTypeFromCLSID(CLSID_AutoComplete);
        try{
            autoComplete2 =(IAutoComplete2^)(Activator::CreateInstance(autoCompleteType));
        }
        catch(Exception^ e)
        {
            Marshal::ReleaseComObject(autoComplete2);
            autoComplete2 = nullptr;
        }

Third, I need to bind it to an TextBox control:

    bool AutocompleteBindingSource::Bind()
    {
        if (nullptr==this->autoComplete2)
            return false;
        try
        {
            this->autoComplete2->SetOptions((int)ControlToBind->AutoCompleteMode);
            this->autoComplete2->Init(
                HandleRef(ControlToBind,ControlToBind->Handle),
                this,
                String::Empty
                ,String::Empty);
            return true;
        }
        catch(Exception^e)
        {
            return false;
        }

    }

Finally, I need to implement IEnumString to provide a list of options. Luckily, .Net has declared this interface, so I don't need to port it to managed code, however, I still need to write my binding code in my implementation of IEnumString.

    void AutocompleteBindingSource::Reset()
    {
        this->current = 0;
        if(BindingSource!=nullptr)
            this->size=BindingSource->Count;
    }

        int AutocompleteBindingSource::Next(
        int celt, [Out, MarshalAs(UnmanagedType::LPArray, ArraySubType=UnmanagedType::LPWStr, SizeParamIndex=0)] array<String^>^ rgelt, IntPtr pceltFetched)
    {
        if (celt < 0)        {
            return E_INVALIDARG;
        }
        int index = 0;
        while ((this->current < this->size) && (celt > 0))
        {
            Object^ item=this->BindingSource->default[this->current];

            bool useDisplayMember=false;

            if(!String::IsNullOrEmpty(DisplayMember))
            {
                ICustomTypeDescriptor^ customTypeDescriptor=dynamic_cast<ICustomTypeDescriptor^>(item);
                if(customTypeDescriptor!=nullptr)
                {
                    PropertyDescriptorCollection^ propertyDescriptorCollection=
                        customTypeDescriptor->GetProperties();
                    if(propertyDescriptorCollection!=nullptr)
                    {
                        PropertyDescriptor^ propertyDescriptor=propertyDescriptorCollection->default[DisplayMember];
                        if(propertyDescriptor!=nullptr)
                        {
                            rgelt[index] = propertyDescriptor->GetValue(item)->ToString();
                            useDisplayMember=true;
                        }
                    }
                }
            }

            if(!useDisplayMember)
            {
                if(item!=nullptr)
                {
                    rgelt[index] = item->ToString();
                }
            }
            this->current++;
            index++;
            celt--;
        }
        if ((pceltFetched != IntPtr::Zero))
        {
            Marshal::WriteInt32(pceltFetched, index);
        }
        if ((celt != 0))
        {
            return 1;
        }
        return 0;

    }

Here the DisplayMember property is the name of the property in the data source to be displayed. If the property specified by the value of the DataMember property does not exist, I use ToString to get a text representation of the current item in the data source.

You may want to ask, where is the filtering code? Well, that is implemented by BindingSource class.

       System::Void FormTest::textBoxDemo_TextChanged(System::Object^  sender, System::EventArgs^  e)
    {
        static bool inThisFunction=false;
        if(!inThisFunction)
        {
            inThisFunction=true;
            if(String::IsNullOrEmpty(textBoxDemo->Text))
                bindingSourceAutoComplete->Filter=nullptr;
            else
            {
                System::String^ addText=textBoxDemo->Text+"og/NextElement";
                dataSetDemo->Tables[0]->DefaultView->Sort="Text";
                if(dataSetDemo->Tables[0]->DefaultView->FindRows(addText)->Length==0)
                {
                    System::Data::DataRow^ row=dataSetDemo->Tables[0]->NewRow();
                    row->default[0]=addText;
                    dataSetDemo->Tables[0]->Rows->Add(row);
                }
                bindingSourceAutoComplete->Filter=
                    String::Format("{0} LIKE '{1}%'"
                    ,dataSetDemo->Tables[0]->Columns[0]->Caption
                    ,textBoxDemo->Text);
            }
            if(textBoxDemo->SelectionStart>0)
            {
                autocompleteBindingSource1->Reset();
                autocompleteBindingSource1->Bind();
                String^ text=textBoxDemo->Text;
                int selectionStart=textBoxDemo->SelectionStart;
                int selectionLength=textBoxDemo->SelectionLength;
                textBoxDemo->SelectionStart=0;
                textBoxDemo->SelectionLength=0;
                textBoxDemo->SelectAll();            
                System::Windows::Forms::SendKeys::SendWait("{BACKSPACE}");
                textBoxDemo->Text=text;
                textBoxDemo->SelectionStart=selectionStart-1;
                textBoxDemo->SelectionLength=selectionLength+1;
                System::Windows::Forms::SendKeys::SendWait(textBoxDemo->SelectedText);
            }
            inThisFunction=false;
        }
    }

Somehow Windows caches the result. If I don't clear the text, my IEnumString implementation won't be asked again for candidate strings (pointed out by Andy Gilman). 

The BindingSource class checks the data source to see if they support the IBindingListView. If IBindingListView is supported, the BindingSource class delegates sorting and filtering to the data source.  In this sample, the data source of the BindingSource object is a DataSet, and the DataMember of BindingSource object is the name of the first table , so BindingSource creates a DataView as its data source. The DataView class implements IBindingListView and filters its data using expressions parsed from the filter string. In reality, the data source could be a business object that implements IBindingListView and supports filtering and sorting with stored procedures.

This sample does not consider compound autocomplete object support. If you want to get your options from multiple sources, you need to use IObjMgr to add sources to the autocomplete object.

Reference

View more entries
 
View space
betty
View space
星宿·鬼·门
View space
叶叶茶
View space
bigqiang
View space
苗苗
View space
Joanna
View space
View space
Na Lei
View space
微笑的猫
View space
蝈蝈俊.net
View space
黄际洲
View space
Big Apple
View space
茜茜
View space
Tina :/ の ィ氐 言周
View space
点点
View space
Suvendu

Jiangsheng

View spaceSend a message
Occupation:
Age:
Interests:
JIANG,Sheng, a Microsoft Most Valuable Professional in Visual C++ since 2004, became a Visual C++ programmer at 1999. He activeson several online Visual C++ forums ,blogs and newsgroups Command what is yours, counquer what is not.