Welcome to MSDN Blogs Sign in | Join | Help

All-In-One Code Framework (CodeFx) lands on MSDN China homepage

CodeFx lands on MSDN China homepage to benefit Chinese developers. As the MSDN headline reads, “CodeFx makes learning and using Microsoft technologies easy and productive”. You can download the latest release of CodeFx on http://cfx.codeplex.com/Release/ProjectReleases.aspx.

Posted by MSDNTST | 0 Comments
Filed under:

All-In-One Code Framework

 

Dear Friends. Have you ever needed a quick understanding of a technique, e.g. ActiveX or VSX, but been daunted by the few or too many samples and documents that are available on the Internet? Have you ever downloaded or created a good sample, e.g. a named pipe sample for IPC, but forgotten where the sample was placed after a few days? Have you ever wanted a simple test environment, e.g. a COM object or a DLL, but become tired of frequently creating such projects and naming them as "ClassLibrary1", "ClassLibrary2", "ClassLibraryABC"?

 

If your answer is YES to any one of these questions, this All-In-One Code Framework will be of assistance to you.

 

We recently created a sample-code project All-In-One Code Framework (codename CodeFx) on CodePlex.

 

All-In-One Code Framework delineates the framework and skeleton of most Microsoft development techniques (e.g. COM, Data Access, IPC) using typical sample codes in different programming languages (e.g. Visual C#, VB.NET, Visual C++). For instance, the code example ATLActiveXDll shows the skeleton of an ATL ActiveX DLL as its name implies. Each example is elaborately selected, composed, and documented to demonstrate one frequently-asked, tested or used scenario based on our experience as support engineers. If you are a software developer, you can fill the skeleton with blood, muscle and soul. If you are a software tester or a support engineer like us, you may extend the sample codes a little to fit your specific test scenario or refer your customer to this project if the customer's question coincides with what we collected.

 

Project Scope

 

The target of the project is to sketch the skeleton of most Microsoft development techniques using typical sample codes that are frequently-asked, tested or used. You can imagine each technique as a building. The foundation of the building (the basics of the technique) and the facilities inside the building (the details of the technique) are not in the scope. Instead, you fill find the structure of the building (the framework and skeleton of the technique) in the scope.

 

Features

 

All-In-One

 

All examples for all Microsoft development techniques are in one Visual Studio solution. All source codes, documents, and reference materials can be viewed or tested in one instance of Visual Studio.

 

Uniform

 

·      All examples follow a uniform naming convention. The convention applies to the name of the projects, variables, methods, types, etc.  

·      All examples have a uniform style of coding, commenting and documentation. For instance, each code example has a ReadMe.txt file that documents the example. The content of ReadMe.txt follows this structure: Use (the purpose of the example), Project Relation (the relation between the current example and the rest), Build (how to build the example), Creation (the detailed steps to create such an example) and References (the reference materials).

·      All examples of the same technique manage to provide a uniform output or export. For instance, ATLActiveXDll, ATLActiveXExe, CSDllCOMServer, VBDllCOMServer, MFCActiveX, MFCSafeActiveX, CSActiveX, VBActiveX are COM components in different forms. However, they export a uniform set of methods, properties and events.

 

Mutually Dependent

 

The code examples are mutually dependent or related, and many are efficiently reused by other examples to demonstrate the techniques. For instance, CppDllExport is a sample C++ DLL that exports the symbols of data, functions and classes. CppImplicitlyLinkDll depends on CppDllExport to demonstrate the implicit link of a DLL; CppDelayloadDll delay-loads the DLL; CppLoadLibrary dynamically loads the DLL; CSPInvokeDll uses CppDllExport to show the use of .NET Platform Invocation Service.

 

Source of Examples

 

The sample codes are refined out of our supports for developers in the newsgroups and the forums. You can think of the project as a collection of most frequently requested test scenarios in contrast with FAQs.

 

The above four features are highlighted because most sample code sites like www.codeproject.com and MSDN lack them. Besides, the code examples in All-In-One Code Framework are typical, extensible, structured, complete, and easy to understand.

 

Current Stage

 

In the pilot phase of the project, we focus on five techniques: COM, Library, IPC, Office and Data Access. Today is March 8, 2009. There have been 36 code examples in the project. The collection currently grows at a rate of seven examples per week.

 

The following examples are the epitome of CodeFx on 2009-3-1. For an up-to-date list, please refer to All-In-One Code Framework Examples.

 

Examples for COM and ActiveX:

 

COM and ActiveX 

 

Name

Description

CSDllCOMServer

A COM server written in C#

VBDllCOMServer

A COM server written in VB.NET

ATLActiveXDll

An in-process ATL COM Server

ATLActiveXExe

An out-of-process ATL COM Server

MFCActiveX

A MFC ActiveX Control

MFCSafeActiveX

A MFC ActiveX Control Safe for Scripting and Initialization

CSActiveX

A C# ActiveX Control

VBActiveX

A VB.NET ActiveX Control

CppCOMClient

Use COM servers in a C++ application

CSCOMClient

Host ActiveX controls use COM servers in C#

VBCOMClient

Host ActiveX controls and use COM servers in VB.NET

MFCCOMClient

Host ActiveX controls and use COM servers in MFC

HTMLEmbedActiveX

Host ActiveX controls in HTML

 

Examples for Data Access:

 

Data Access 

 

Name

Description

CSUseADO

Use ADO in a C# application

CppUseADO

Use ADO in a C++ application

CSUseADONET

Use ADO.NET in a C# application

CppUseADONET

Use ADO.NET in a C++ application

 

Examples for Library:

 

Library

 

Name

Description

CppDllExport

A C++ dynamic library export symbols

CppImplicitlyLinkDll

C++ implicitly links a DLL

CppDelayloadDll

C++ delay-loads a DLL

CppLoadLibrary

C++ dynamically loads a DLL

CSLoadLibrary

C# dynamically loads a native DLL

CSPInvokeDll

C# P/Invokes a native DLL

CSClassLibrary

A C# Class Library

CppHostCLR

C++ hosts CLR and loads a .NET assembly

CSReflection

C# dynamically loads and uses the types of a .NET assembly

CSEmitAssembly

C# emits an assembly with types in runtime

CppStaticLibrary

A C++ Static Library

CppStaticallyLinkLib

C++ statically links a static library

Examples for IPC and RPC:

Name

Description

CppNamedPipeServer

A named-pipe server written in C++

CppNamedPipeClient

A named-pipe client written in C++

CSNamedPipeServer

A named-pipe server written in C#

CSNamedPipeClient

A named-pipe client written in C#

CppMailslotServer

A mailslot server written in C++

CppMailslotClient

A mailslot client written in C++

CppFileMappingServer

Create shared memory in C++

CppFileMappingClient

Access shared memory in C++

CSRemotingServer

A .NET Remoting server written in C#

CSRemotingClient

A .NET Remoting client written in C#

VBRemotingServer

A .NET Remoting server written in VB

VBRemotingClient

A .NET Remoting client written in VB

 

Feedback

We look forward to hearing your feedback. Please post your suggestions and ideas in Discussions or contact us directly. Your comments on this project are appreciated. 

 

Thank you!

Posted by MSDNTST | 2 Comments
Filed under:

How to bind a DataGridView column to a second-level property of a data source

This is a frequently asked question. Suppose that we have a class Person which has a property of type Address(another class). The class Address has its own properties. Now we create a collection of Person objects, e.g. List<Person> and would like to bind a DataGridView to the collection.

 

The following is the code for class Person and Address.

 

class Person

{

         private string id;

         private string name;

         private Address homeAddr;

         public string ID

         {

                   get { return id;}

                   set { id = value;}

         }

         public string Name

         {

                   get { return name;}

                   set { name = value;}

         }

         public Address HomeAddr

         {

                   get { return homeAddr;}

                   set { homeAddr = value;}

         }       

}

 

class Address

{

         private string cityname;

         private string postcode;

         public string CityName

         {

                   get { return cityname;}

                   set { cityname = value;}

         }

         public string PostCode

         {

                   get { return postcode;}

                   set { postcode = value;}

         }

}

 

As we all know, DataGridView columns could only be bound to the first-level properties of class Person, e.g. the ID, Name or HomeAddr properties. The following is the code to bind a DataGridView to a collection of Person objects.

 

List<Person> persons = new List<Person>();

// add some Person objects to the collection

...

dataGridView1.DataSource = persons;

dataGridView1.Columns[0].DataPropertyName = "ID";

dataGridView1.Columns[1].DataPropertyName = "Name";

dataGridView1.Columns[2].DataPropertyName = "HomeAddr";

 

When a DataGridView column is bound to the HomeAddr property, the name of the class Address will be displayed under the column, i.e. projectname.Address.

 

If we set the DataPropertyName property of a DataGridView column to "HomeAddr.CityName", an empty text will be displayed under the column, because DataGridView could not find a property called "HomeAddr.CityName" in the class Person.

 

Is there a way to bind a DataGridView column to the CityName or PostCode property of the HomeAddr property? The answer is YES!

 

.NET Framework 1.x can implement ICustomTypeDescriptor interface for the class Person. When a Person object in the collection is going to be displayed in a control, data binding calls ICustomTypeDescriptor.GetProperties method to get the object's properties. When implementing ICustomTypeDescriptor.GetProperties method, we could create PropertyDescriptor instances for the second-level properties and return them with the original PropertyDescriptor instances of class Person.

 

There're two problems here. One problem is that if there's no object in the collection, the ICustomTypeDescriptor.GetProperties method won't be called so that DataGridView couldn't 'see' secondary-level properties of class Person. The other problem is that it requires modifying the class Person because the class Person needs to implement the ICustomTypeDescriptor interface.

 

To work around the first problem, we could resort to ITypedList interface, i.e. implement the ITypedList interface for the collection. If a data source has implemented the ITypedList interface, data binding calls ITypedList.GetItemProperties to get the properties available for binding. In the ITypedList.GetItemProperties method, we could create an instance of class Person and then call TypeDescriptor.GetProperties(component) method passing the Person instance as the parameter, which in turn calls ICustomTypeDescriptor.GetProperties of the class Person implementation.

 

.NET Framework 2.0 way is to make use of TypeDescriptionProvider and CustomTypeDescriptor classes, which expand support for ICustomTypeDescriptor. It allows you to write a separate class that implements ICustomTypeDescriptor (for convenience, we could derive the class directly from CustomTypeDescriptor which provides a simple default implementation of the ICustomTypeDescriptor interface) and then to register this class as the provider of description for other types.

 

Even if a type is added a TypeDesciptionProvider, data binding won't call the custom type descriptor's GetProperties method to get the object's properties. So we still need to implement ITypedList interface for the collection and in the ITypedList.GetItemProperties method, call TypeDescriptor.GetProperties(type) which in turn calls the custom type descriptor's GetProperties method.

 

To take advantage of this new functionality, we first need to create a TypeDescriptionProvider, which simply derives from TypeDescriptionProvider and overrides its GetTypeDescriptor method. GetTypeDescriptor returns the ICustomTypeDescriptor implementation or the derived CustomTypeDescriptor that TypeDescriptor should use when querying for property descriptors.

 

When creating providers that are only intended to augment or modify the existing metadata for a type, rather than completely replace it, a recommended approach is to call 'TypeDescriptor.GetProvider' method in the new providers' constructor to get the current provider for the specified type. This base provider can then be used whenever you need to access the underlying type description.

 

As for PropertyDescriptor, it is an abstract class that derives from another abstract class, MemberDescriptor. MemberDescriptor provides the basic information for each property, and PropertyDescriptor adds functionality related to changing a property's value and determining when that value has changed. To create a PropertyDescriptor on the class Person for each second-level property, we first need to create a custom class that derives from PropertyDescriptor. Pass the original PropertyDescriptor of the second-level property in the new PropertyDescriptor class's constructor, and then use the original PropertyDescriptor whenever we need to query the information of the second-level property.

 

The following is the code of a custom class that derives from PropertyDescriptor.

 

public class SubPropertyDescriptor : PropertyDescriptor

{

        private PropertyDescriptor _subPD;

        private PropertyDescriptor _parentPD;

 

        public SubPropertyDescriptor(PropertyDescriptor parentPD,PropertyDescriptor subPD,string pdname)

            : base(pdname,null)

        {           

            _subPD = subPD;

            _parentPD = parentPD;

        }

 

        public override bool IsReadOnly { get { return false; } }

        public override void ResetValue(object component) { }

        public override bool CanResetValue(object component) { return false; }

        public override bool ShouldSerializeValue(object component)

        {

            return true;

        }

 

        public override Type ComponentType

        {

            get { return _parentPD.ComponentType; }

        }

        public override Type PropertyType { get { return _subPD.PropertyType; } }

 

        public override object GetValue(object component)

        {

           return _subPD.GetValue(_parentPD.GetValue(component));

        }

 

        public override void SetValue(object component, object value)

        {           

            _subPD.SetValue(_parentPD.GetValue(component), value);

            OnValueChanged(component, EventArgs.Empty);

        }

}

 

The following is the code of a derived CustomTypeDescriptor class.

 

public class MyCustomTypeDescriptor : CustomTypeDescriptor

{      

        public MyCustomTypeDescriptor(ICustomTypeDescriptor parent)

            : base(parent)

        {

        }

 

        public override PropertyDescriptorCollection GetProperties()

        {

            PropertyDescriptorCollection cols = base.GetProperties();

 

            PropertyDescriptor addressPD = cols["HomeAddr"];

            PropertyDescriptorCollection homeAddr_child = addressPD.GetChildProperties();

          

            PropertyDescriptor[] array = new PropertyDescriptor[cols.Count + 2];

            cols.CopyTo(array, 0);

            array[cols.Count] = new SubPropertyDescriptor(addressPD,homeAddr_child["CityName"],"HomeAddr_CityName");

            array[cols.Count + 1] = new SubPropertyDescriptor(addressPD, homeAddr_child["PostCode"], "HomeAddr_PostCode");

 

            PropertyDescriptorCollection newcols = new PropertyDescriptorCollection(array);

            return newcols;           

        }    

  }

 

The following is the code of the custom TypeDescriptorProvider.

 

public class MyTypeDescriptionProvider : TypeDescriptionProvider

{

        private ICustomTypeDescriptor td;

 

        public MyTypeDescriptionProvider()

           : this(TypeDescriptor.GetProvider(typeof(Person)))

        {           

        }

        public MyTypeDescriptionProvider(TypeDescriptionProvider parent)

            : base(parent)

        {

        }

        public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)

        {

            if (td == null)

            {

                td = base.GetTypeDescriptor(objectType, instance);

                td = new MyCustomTypeDescriptor(td);

            }

            return td;

        }       

}

 

At the end, we adorn TypeDescriptionProviderAttribute to the class Person.

 

[TypeDescriptionProvider(typeof(MyTypeDescriptionProvider))]

class Person

{...}

 

Then we could bind a DataGridView column to the second-level properties in the class Person as follows:

 

dataGridView1.Columns[2].DataPropertyName = "HomeAddr_CityName";

dataGridView1.Columns[3].DataPropertyName = "HomeAddr_PostCode";

 

 

Linda Liu

Posted by MSDNTST | 20 Comments

What’s new in Microsoft Visual SourceSafe 2005?

As you all know, Microsoft Visual SourceSafe 6.0(VSS 6.0) was first shipped in 1998. Although there are 4 versions from 6.0a to 6.0d, it had been about 7 year before the next version VSS 2005(VSS 8.0) was released. You may be curious on how many things have been changed in this big step. Here, I listed some major ones.

1.       Internet Access

 

The most obvious and vital change might be the Internet Access. This feature enables you to connect to VSS database when you’re outside your office. It’s normally much faster that connecting through VPN. VSS 2005 can expose web service to perform most of the work we do in the LAN. In the 6.0 version, we can only achieve this by using some 3rd party tools like SourceOffSite from SourceGear.

 

 

 

Since it is a web service, it requires that you have IIS installed on your machine. Here is an MSDN article about detailed steps of how to setup this web service.

http://msdn2.microsoft.com/ko-kr/library/ms181057(VS.80).aspx

 

In Visual Studio 2005, you can specify the source control provider from Tools/Options dialog in the main menu.

 

 

However, in VS.NET 2003 and older versions, there is no integrated way for us to set the active provider. We have to do this by manually registering the source control provider .dll file: regsvr32.exe RemoteVsScc.dll or you can use some 3rd party tools like Scc Switcher.

http://www.codeproject.com/tools/sccswitcher.asp

 

Of course, manually modifying the registry key will be another option. Here is a KB article with detailed steps to do this.

http://support.microsoft.com/default.aspx?scid=kb;en-us;319318

 

2.       LAN Booster Service

 

Another improvement is called LAN Booster Service.

http://msdn2.microsoft.com/en-us/library/ms181058(VS.80).aspx

 

After enabling it with the steps shown in the above link, a new service SSService.exe will be running under the LocalSystem account on the server machine. This service compresses all the files that are going to be transferred through the network on the wire, which will improve performance at about 3-5 times. However, from name of it, we can know that this service is only available for LAN provider. (NOT for internet provider)

 

 

 

3.       Better Visual Studio Integration.

 

Now VSS 2005 has better integration with Visual Studio. An obvious example is that users don’t need to select “Open From Source Control” to open solutions from VSS database. This function has been put into the Open Project/Solution dialog.

 

 

 

4.       Migration Tools Needed?

 

The database format is not changed from VSS 6.0 to VSS 2005. So no migration tool is needed for you to upgrade databases. You can simply copy them to the new server.

 

5.       Asynchronously File Retrieval

 

When you get files in VS.NET IDE, there will be a dialog box popped up, indicating that files will be retrieved from server asynchronously. This means if you have a large solution/project, you can start working when some of the files have been retrieved. And file transfer from server will not block your IDE.

 

 

 

6.       Programming Interfaces(Automation)

 

Like previous versions, VSS 2005 has a complete set of interfaces (known as SCC API) developed for us to program on it. It also has been ported to interop assemblies for .NET development.

 

Furthermore, the Visual Studio SCC API forward with a new 1.3 version. 1.3 includes all existing 1.1 and 1.2 methods plus some new methods to help support asynchronous Open from Source Control and propagation of Renames and Deletes from Visual Studio.

 

7.       No Longer Supports SQL Server Objects Versioning

 

 Unfortunately the earlier support in VS.NET 2003 for versioning SQL server objects will no longer be supported in VS 2005. However, we can find some workaround like saving the script (.sql) files in VSS, since all SQL Server creations and modifications can be translated to SQL scripts.

 

Here I just listed some most important changes. If you have other stuff that is not included here, welcome for your comments.

 

Posted by MSDNTST | 1 Comments

How to troubleshoot the COM Add-ins loading issues

1.         What is the unmanaged COM Add-ins loading process?

Here is a COM Add-in registry example.

[HKEY_CURRENT_USER\Software\Microsoft\Office\Excel\AddIns\UnmanagedAddin.Connect]

"FriendlyName"="UnmanagedAddin"

"Description"="Composed in ATL 8.0"

"LoadBehavior"=dword:00000003

         HKEY_CURRENT_USER: this is user level COM-Addin

         Excel: This is an Excel COM Addin

         UnmanagedAddin.Connect: This is progid of the COM Add-in

         LoadBehavior: control how the Add-in will be loaded.

         You may refer the link below about LoadBehavior

http://support.microsoft.com/?id=824251

 

a)        Check the registry for the available COM Add-ins

HKEY_CURRENT_USER\Software\Microsoft\Office\Excel\AddIns\

Or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\Excel\Addins\

 

HKEY_CURRENT_USER one: stored the COM Add-ins for the current user only. (i.e. when we installed the Add-in, we checked “just for me”, user level)

HKEY_LOCAL_MACHINE one: stored the COM Add-ins for all users. (i.e. when we installed the Add-in, we checked “Everyone”, machine level) 

b)        Found an entry of Add-in (UnmanagedAddin.Connect) of LoadBehavior 3.

c)         Attempt to locate the COM DLL of progid “UnmanagedAddin.Connect”(Common COM Load procedure)

                        i.              Found HKEY_CLASSES_ROOT\UnmanagedAddin.Connect\CurVer

Default Value is “UnmanagedAddin.Connect.1"

                      ii.              Found “HKEY_CLASSES_ROOT\UnmanagedAddin.Connect.1\CLSID”

Default Value is “{F51126A7-472D-4D3D-A011-8D1467F6BAFD}”

                    iii.              Located the registry key below.

HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}

[HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}]

@="Connect Class"

[HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}\InprocServer32]

@="c:\\users\\username\\documents\\visual studio 2005\\projects\\comaddins\\unmanagedaddin\\debug\\UnmanagedAddin.dll"

"ThreadingModel"="Apartment"

[HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}\ProgID]

@="UnmanagedAddin.Connect.1"

[HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}\Programmable]

[HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}\TypeLib]

@="{A5A5FD6A-2A19-4DB6-AB8F-51735C47CDAD}"

[HKEY_CLASSES_ROOT\CLSID\{F51126A7-472D-4D3D-A011-8D1467F6BAFD}\VersionIndependentProgID]

@="UnmanagedAddin.Connect"

                     iv.              Loaded the DLL with Win32 LoadLibrary API.

 

2.         What is the managed COM Add-ins loading process?

a)        The steps are similar except for step 1 c) iii

[HKEY_CLASSES_ROOT\CLSID\{5E5E6110-C49E-41FD-891B-7693500F0EC4}]

@="ManagedAddin.Connect"

[HKEY_CLASSES_ROOT\CLSID\{5E5E6110-C49E-41FD-891B-7693500F0EC4}\Implemented Categories]

[HKEY_CLASSES_ROOT\CLSID\{5E5E6110-C49E-41FD-891B-7693500F0EC4}\Implemented Categories\{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}]

[HKEY_CLASSES_ROOT\CLSID\{5E5E6110-C49E-41FD-891B-7693500F0EC4}\InprocServer32]

@="mscoree.dll"

"ThreadingModel"="Both"

"Class"="ManagedAddin.Connect"

"Assembly"="ManagedAddin, Version=1.0.2552.27634, Culture=neutral, PublicKeyToken=null"

"RuntimeVersion"="v2.0.50727"

"CodeBase"="file:///C:/Users/username/Documents/Visual Studio 2005/Projects/COMAddins/ManagedAddin/bin/Debug/ManagedAddin.dll"

 

b)        In a managed scenario, the mscoree.dll will be loaded instead of the Add-in DLL directly. Then, it is the mscoree.dll which loads the managed Add-in DLL.

 

3.         General troubleshooting steps are based on the COM Add-ins Load Process.

a)        Disable all the other COM Add-ins and restart Office Product

b)        Go through the COM Add-in Load Procedure.

                        i.              If the registry key existed (refer to 1 a)), did the LoadBehavior set to 3?

                      ii.              Follow the steps that how COM DLL is Loaded (refer to 1 c))

 

4.         Some general approaches.

 

a)        By default the .NET CAS (Code Access Security) setting is OK for COM Add-ins, but this is a new security check added by .NET. When you develop managed COM Add-ins, you may try to add “Full Trust” permission set for the Add-in DLL when you have no idea.

http://msdn2.microsoft.com/en-us/library/930b76w0.aspx

 

b)        Embrace your code in a “try…catch” block and write Log when error occurred.

 

c)         Isolate the problem.

Comment out all of your code, and put the simple code as below in your OnConnect method. Once this is called, we should consider the Add-in loading to be OK.

e.g.

STDMETHODIMP CConnect::OnConnection(IDispatch *pApplication, AddInDesignerObjects::ext_ConnectMode /*ConnectMode*/, IDispatch *pAddInInst, SAFEARRAY ** /*custom*/ )

{

        ::MessageBoxW(NULL,L"Hello",L"Test Dialog",MB_ICONINFORMATION);

        return S_OK;

}

d)        Leverage the tools Filemon/Regmon to track the registry/file security setting.

http://www.microsoft.com/technet/sysinternals/utilities/filemon.mspx

http://www.microsoft.com/technet/sysinternals/utilities/regmon.mspx

 

 

Manage database of ASP.NET 2.0 Membership & Role services in non-ASP.NET context

One question I’ve seen asked a few times by people in the NG is “how do I manage ASP.NET Membership, Role Management database in non-ASP.NET application/context”. This blog entry walks you though a few simple steps on how to-do this.

 

Quick Review: What are the new ASP.NET 2.0 membership & role management Services?

 

The ASP.NET version 2.0 membership feature provides secure credential storage for application users. It also provides a membership API that simplifies the task of validating user credentials when used with forms authentication. Membership providers abstract the underlying store used to maintain user credentials. ASP.NET 2.0 includes the following providers:

  • ActiveDirectoryMembershipProvider. This uses either an Active Directory or Active Directory Application Mode (ADAM) user store.
  • SqlMembershipProvider. This uses a SQL Server user store.

 

Here I’ll concentrate on the SQL Server provider since it is used mostly for FormsAuthentication based ASP.NET web applications. By default ASP.NET SqlServer membership/role provider use SQL Express database file(aspnetdb.mdf) as the storage, however, you can easily change it to your own SQL Server database in a certain server instance. What you need to do is simply override/customize the membership setting in the application web.config file. E.g.

 

<connectionStrings>

  <add name="MySqlConnection" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />

</connectionStrings>

<system.web>

...

  <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">

    <providers>

      <clear />

      <add

        name="SqlProvider"

        type="System.Web.Security.SqlMembershipProvider"

        connectionStringName="MySqlConnection"

        applicationName="MyApplication"

        enablePasswordRetrieval="false"

        enablePasswordReset="true"

        requiresQuestionAndAnswer="true"

        requiresUniqueEmail="true"

        passwordFormat="Hashed" />

    </providers>

  </membership>

 

 

 

 

How do I manage ASP.NET Membership, Role Management database in non-ASP.NET application/context?

 

Sometimes you may want to manage the SQL Server membership/role database in non-ASP.NET application/context(such as winform or console application) for some certain reasons:

 

l         Need to add some initial data(users/roles) in the setup program of the application

l         Want to create a non-ASP.NET application to manage the membershp/role database offline

l         Create a non-ASP.NET application that can help create a membership/role database as template(used in other ASP.NET application).

 

Well, this is certainly supported by the ASP.NET 2.0 membership/role(also some other) providers and you can do this follow these steps:

 

 

1.        add the connectionstring to your SQL Server membershp & role provider database into the winform/console application’s App.confg file. e.g.

 

<connectionStrings>

       

        <add name="ProfileAppDB" connectionString="Data Source=localhost;Initial Catalog=ProfileAppDB;Integrated Security=True"

   providerName="System.Data.SqlClient" />

    </connectionStrings>

 

2.        copy the membershp & role setting fragment from your ASP.NET application into the winform/console application’s App.config file. e.g.

 

    …………..

<system.web>

    <anonymousIdentification enabled="true"/>

……………

 

 

    <membership defaultProvider="NewAspNetSqlMembershipProvider">

        <providers>

            <add name="NewAspNetSqlMembershipProvider"

   type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

 connectionStringName="ProfileAppDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />

        </providers>

    </membership>

 

    <roleManager defaultProvider="NewAspNetSqlRoleProvider" enabled="true">

        <providers>

            <add name="NewAspNetSqlRoleProvider" connectionStringName="ProfileAppDB" applicationName="/"

   type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

 

        </providers>

    </roleManager>

    </system.web>

……………

 

3.        Use the built-in façade classes to manage the membership users and roles. E.g.

 

/// <summary>

/// Dump the users and associated roles from membership database

/// </summary>

private void Dump_Users()

 {

            MembershipUserCollection users = Membership.GetAllUsers();

            txtOutput.Text += "\r\n=========Total User Count: " + users.Count + "==========";

            txtOutput.Text += "\r\n\r\n";

 

            foreach (MembershipUser user in users)

            {

                txtOutput.Text += "\r\n\tUsername: " +user.UserName + "\t, Creation Time: " + user.CreationDate;

               

 

                string[] roles = Roles.GetRolesForUser(user.UserName);

 

                txtOutput.Text += "\r\n Roles: " + string.Join(", ",roles);

            }

}

 

/// <summary>

/// create a new membership user

/// </summary>

     

private void btnCreate_Click(object sender, EventArgs e)

 {

            MembershipCreateStatus ret;

 

            MembershipUser user = Membership.CreateUser(

                txtUsername.Text,

                txtPassword.Text,

                txtUsername.Text + "@test.org",

                "who am i?",

                txtUsername.Text, true, null, out ret);

 

            MessageBox.Show(ret.ToString());

}

 

 

 

 

winform app UI

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Winform App UI

 

 

 

 

 

Additional common questions here:

 

Q1: What shall I do if I can not add an App.config file for the program at design-time(used in a setup program)? How can I provide the connectionstring and membershp provider configuration info?

 

A1: You can dynamically create an app.exe.config file for your program in the initialization/startup time. Use built-in API to get the runtime main exe path and create a config file on the fly, then write the configuration info into it(load from resource or any other place).

 

 

 

Q2: How can I programmatically install the membership & role services into an empty SQL Server database(in a certain server instance)?

 

A2: You have two options here:

ü         Call the aspnet_regsql.exe utility the install the services in your database

http://msdn2.microsoft.com/en-us/library/x28wfk74.aspx

 

ü         Directly use the System.Web.Management.SqlServices class to install the services into your SQL Server database

http://msdn2.microsoft.com/en-us/library/system.web.management.sqlservices.aspx

 

 

 

 

Q3: How can I do programmatically create a SQL Express database file which has the membershp & role services installed

 

A3: Well, you can find that ASP.NET Sqlmembership provider will automatically create a mdf file if you’ve configured to use the default SQL Express connectionstring. Thus, you can inspect it through reflector and find out the SqlConnectionHelper.CreateMdfFile method which include the complete code for creating such as database file on the fly

 

reflector1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 reflector2

 

 

Hope this helps.

 

Steven Cheng

Use your ASP .NET WebControl in MOSS 2007 with Sharepoint Delegate Control

 

In the new release of Sharepoint Server (MOSS 2007), a very interesting control is provided,  "DelegateControl", under Microsoft.SharePoint.WebControls.SPControl. With this control we can easily reuse our ASP.NET control on SPS pages. Now, an ASP .NET programmer can name himself a "part time SPS Web part developer" :)

Here is sample on how you can use DelegateControl on a sharepoint page:

1. Create an ASP .NET WebControl (ASPNETControl.ascx) file as following:

 

<%@ Control Language="C#" AutoEventWireup="true" ClassName="ASPNETControl"   %>

<script runat ="server" >

 protected void Button1_Click(object sender, EventArgs e)

    {

        TextBox1.Text = System.DateTime.Now.ToShortDateString();    

    }

</script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

 

2. Create a folder "ASPNETControl" under:

 

\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES

And Copy the file (ASPNETControl.ascx) to this folder.

 

3. Create two xml file feature.xml (fixed name, must be feature.xml) and Control.xml:

 

Feature.xml:

<?xml version="1.0" encoding="utf-8" ?>

<Feature Id="62D5F317-A793-4328-A250-50CBE1F5B70E"

  Title="ASPNETControl"

  Scope="Farm"

  Description="Test ASPNET control"

  Version="1.0.0.0"

  xmlns="http://schemas.microsoft.com/sharepoint/" >

  <ElementManifests>

      <ElementManifest Location="Control.xml" />

  </ElementManifests>

</Feature>

 Control.xml:

 

<?xml version="1.0" encoding="utf-8" ?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >

    <Control Id="ASPNETControl"

          ControlSrc="~/_ControlTemplates/ASPNETControl/ASPNETControl.ascx"

          Sequence="100" >

      </Control>

</Elements>

 

4. Create a folder "ASPNETControl" under following folder:

\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES

And copy the two XML files into it.

 

5. Execute stsadm.exe to run following command:

 

Stsadm -o installfeature -filename ASPNETControl\feature.xml -force

 

6. Open Sharepoint 3.0 central Administration, in

 

Central Administration>Operations>Global Configuration>Manage Farm Features   

You will notice this new feature has been enabled by default

 

 

7. Open your site with SharePoint Designer 2007, and add following line in the default.aspx:

 

<SharePoint:DelegateControl ControlId="ASPNETControl" RunAt="server" />

Save the page, and view your site again. You will see the control has been updated on it.

 

Additionally, for those ASP .NET controls with code behind, you need to copy the .cs or .vb file with the .ascx file

Posted by MSDNTST | 14 Comments

Row Size limitation in SQL 2000 and 2005

 

When you creating a table, you may encounter the following information: ' Table <table name> has been created but its maximum row size(11038) exceeds the maximum number of bytes per row (8060). INSERT or UPDATE Of a row in this table will fail if the resulting row length exceeds 8060 bytes.

 

The reason for the error is that maximum size of a row on your table exceeds 8kb. This restriction is by SQL 2000 design. SQL Server engine stores it's data on 8kb pages & a single record must fit in a single page and cannot be spanned to multiple pages. You may want to reduce number of

fields on your table or shorten the field length of some columns.

 

Data pages are the structures that contain all data that is not text or image. As with all other types of pages in SQL Server, data pages have a fixed size of 8 KB, or 8192 bytes. They consist of three major components: the page header, data rows, and the row offset array. The following is the structure of a data page in SQL Server.

 

 

 

Structure of a data page

 

In SQL Server 7.0 and SQL Server 2000 we are allowed to create a table that contains variable columns with a total length GT. 8060 (the total sum of fixed length columns must be LT 8060 as well as the length of an individual column).

 

However when executing an inset or an update statement SQL Server may fail if the actual length is greater than 8K. You may want to try the following statements in SQL 2000 to see this behavior:

 

 

CREATE TABLE mytab ( col1 varchar(8000), col2 varchar(8000) )

 

-- Warning: The table 'mytab' has been created but its maximum row size (16025) exceeds the maximum number of bytes per row (8060). INSERT or UPDATE of a row in this table will fail if the resulting row length exceeds 8060 bytes.

 

INSERT INTO mytab ( col1, col2 )

SELECT REPLICATE ( 'A', 8000), REPLICATE ( 'A', 8000)

 

--Server: Msg 511, Level 16, State 1, Line 1

--Cannot create a row of size 16013 which is greater than the allowable maximum of 8060.

--The statement has been terminated.

 

 

INSERT INTO mytab ( col1, col2 )

SELECT REPLICATE ( 'A', 8000), REPLICATE ( 'A', 60)

 

--Server: Msg 511, Level 16, State 1, Line 1

--Cannot create a row of size 8073 which is greater than the allowable maximum of 8060.

--The statement has been terminated.

 

INSERT INTO mytab ( col1, col2 )

SELECT REPLICATE ( 'A', 8000), REPLICATE ( 'A', 47)

 

 

In SQL 2005 this execution will succeed

 

For example:

 

CREATE TABLE mytab ( col1 varchar(8000), col2 varchar(8000) )

 

--Command(s) completed successfully.

 

INSERT INTO mytab ( col1, col2 )

SELECT REPLICATE ( 'A', 8000), REPLICATE ( 'A', 8000)

 

--(1 row(s) affected)

 

INSERT INTO mytab ( col1, col2 )

SELECT REPLICATE ( 'A', 8000), REPLICATE ( 'A', 9000)

 

--(1 row(s) affected)

 

SELECT len(col1) as len1, len(col2) AS len2 FROM mytab

 

len1        len2

----------- -----------

8000        8000

8000        8000

 

(2 row(s) affected)

 

If both varchars columns contain 8000 bytes the insert will succeed in 2005 and it will fail in the previous releases.

 

The 8060 limit for individual varchar/varbinary columns is still in place. However, it will truncate the charters larger than 8000.

 

In SQL 2005, surpassing the 8,060 row size limit may impact performance. This is because SQL Server still maintains a limit of 8 KB per page. When a combination of varchar, nvarchar, varbinary, or sql_variant columns exceeds this limit, SQL Server moves the record column with the largest width to another page, while maintaining a 24-byte pointer on the original page.

Moving large records to another page happens dynamically as records are lengthened based on update operations. Update operations that shorten records may result in records moved back to the original page. In addition, querying and performing other select operations such as sorts or joins on large records that contain row-overflow data slows processing time.

 

To fetch a column values that has been pushed off the main row requires an extra I/O. Besides, having wide rows also reduces the scan density - because fewer rows fit on a page.

 

If you find the table has many rows with overflow data then you should seriously consider normalizing the table.

 

In SQL 2005, VarChar(MAX), NVarChar(MAX) and VarBinary(MAX) allow storage of data up to 2 gigabytes. Image/Text data type in SQL 2000/2005 is also stored separately and will not be covered in 8KB size.

 

Row-Overflow Data Exceeding 8 KB

http://msdn2.microsoft.com/en-us/ms186981.aspx

 

Maximum Capacity Specifications for SQL Server 2005 

http://msdn2.microsoft.com/en-us/library/ms143432.aspx

 

 

How to debug application crash/hang in production environment?

A common tough scenario is the application crash/hang in production environment. Production environment is different from development environment that it normally does not have any powerful tools to obtain information regarding application failure. In this blog entry, I will talk about 2 wonderful tools to help collect information in production environment: Windbg and Process Explorer.

 

Application Crash:

Crash is the most common scenario of application failure. It is actually caused by an unhanded exception generated in the application. There are 2 types of information that are common critical to resolve application crash:

1.       Unhandled exception type (it is called exception code in unmanaged world) and error message

2.       The full stack trace for the unhandled exception

 

These 2 types of information are trivial to obtain in development environment, because the application runs under the VS debugger, the debugger will tell us this information while unhandled exception is caught.

 

In production environment, it may not be practical to install Visual Studio IDE for debugging, because: 1. Visual Studio is not free. 2. VS has a large memory footprint. 3. The problem can even disappear after installing the Visual Studio.

 

Windbg and Process Explorer are 2 free download tools with much less impact on end user.

 

Using Windbg to obtain Application Crash information:

Windbg is included in the Microsoft “Debugging tools for Windows”. You may download the “Debugging tools for Windows” from the link below:

http://www.microsoft.com/whdc/devtools/debugging/default.mspx

 

After installing windbg, the first thing is setting up the symbol path for it. The symbol path is critical during debugging, because windbg will retrieve the Windows system dlls internal symbols from the symbol path to display the meaningful name for functions/variables. Without the correct symbol loaded, the debugger can only display the numeric memory address for the functions/variables. For example, in a windbg without symbol path, if we use “k” command to obtain the current call stack, we will see following output(note the red numeric):

 

0:000> k

*** ERROR: Module load completed but symbols could not be loaded for notepad.exe

ChildEBP RetAddr 

WARNING: Stack unwind information not available. Following frames may be wrong.

0007f6ec 01001fe4 USER32!MessageBoxW

0007f70c 010027e7 notepad+0x1fe4

0007f944 010035b9 notepad+0x27e7

0007f960 7739c3b7 notepad+0x35b9

0007f98c 7739c484 USER32!EnableMenuItem+0x4cd4

0007fa04 7739ca68 USER32!EnableMenuItem+0x4da1

0007fa60 7739ce7a USER32!TranslateMessageEx+0xd5

0007fa88 7c82ec9e USER32!MsgWaitForMultipleObjectsEx+0x126

0007fb08 773966f0 ntdll!KiUserCallbackDispatcher+0x2e

0007fb24 7739668a USER32!DefWindowProcW+0xc7

0007fb6c 010038e2 USER32!DefWindowProcW+0x61

0007fb94 7739c3b7 notepad+0x38e2

0007fbc0 7739c484 USER32!EnableMenuItem+0x4cd4

0007fc38 7739ca68 USER32!EnableMenuItem+0x4da1

0007fc94 7739ce7a USER32!TranslateMessageEx+0xd5

0007fcbc 7c82ec9e USER32!MsgWaitForMultipleObjectsEx+0x126

0007fd3c 773966f0 ntdll!KiUserCallbackDispatcher+0x2e

0007fd58 7739668a USER32!DefWindowProcW+0xc7

0007fda0 010037fc USER32!DefWindowProcW+0x61

0007fdc8 7739c3b7 notepad+0x37fc

 

Yes, the windbg can only recognize the export function names of the dll. Since we do not have the symbol for notepad.exe, the windbg will only display a *magic* number for the function memory address which is not meaningful to us.

 

To set the symbol path, you may set the following path in the windbg menu item File->”Symbol File Path…”:

“srv*DownstreamStore*http://msdl.microsoft.com/download/symbols”

 

 

Change “DownstreamStore” to any local folder to cache the downloaded symbol files on your machine. For example, I normally use “srv*c:\LocalSymbols* http://msdl.microsoft.com/download/symbols”.

 

Now, you may open the windbg and click File->”Open Executable…” and select your application for launching. Windbg will launch your application and break in the initial loader breakpoint. You can check the red rectangle in the figure to ensure the symbol path is correct:


 

You may press “F5” or input “g” command to tell windbg to ignore the initial loader breakpoint. Now, you may manipulate your application to reproduce the crash. When the application crashes with exception, windbg will automatically break-in your application. Then you may input “k” command to get the full stack trace of this exception/failure.

 

Note: the “k” command may require some time to load the symbols from Microsoft symbol server for the system dlls the first time. So the windbg will report “busy…” for sometime. You may wait to have a coffee for the symbol loading and output.

 

Use Process Explorer to obtain application hangs information:

Process Explorer can be free downloaded in the

http://www.microsoft.com/technet/sysinternals/utilities/ProcessExplorer.mspx

 

Process Explorer is especially suitable for troubleshooting hang problem in application, because it has a very good UI for monitor threads activity.

 

After downloading the Process Explorer, the first thing to do is still setting the symbol server path as we do in windbg:

 

 

Note: in the “Dbghelp.dll path” textbox above, I used to Dbghelp.dll in “Debugging Tools for Windows” package, because this Dbghelp.dll has a higher version than the one in “%windir%/System32/”. If you do not have “Debugging Tools for Windows” installed on end user machine, you can live with using the one in “%windir%/System32/” directory.

 

Let’s demonstrate the Process Explorer usage with a sample. In a .Net Winform application, we write the following code in an existing VC application to simulate the hang in application:

 

Sleep(30000);

 

While the application is hang, we can find the application in the Process Explorer and double click it to launch its property dialog. Then, we should switch to the “Threads” tabpage to examine the thread status. This is what I got in the sample:

 

 

As you can see there is only one thread in the test application. Then, we can select the thread and click “Stack” button in the dialog, we got:

 

 

Aha, by examining this stack trace, we can see that “VMQueryHelper” function calls Sleep() function, which causes the hang.

 

Use Windbg to obtain application hangs information:

Windbg can also be used to troubleshoot the application hang. I assume you have downloaded the windbg and set up the symbol path the same way as said in first section.

 

Now, another .Net application is hanging in customer’s machine. We can use windbg to attach the hang application with the menu item below:

 

 

In the dialog, we can choose the hang application and click Ok button:

 

 

In the windbg, the first thing we should do is checking how many threads are there in the hang application with “~*” command, please see the figure below.

 

As you can see in the figure, thread #0 is executing _CorExeMain method, which is .Net Winform application main GUI thread. The thread #5 has a “.” in the front which means the current examine thread. Because the application hang occurs in the main GUI thread, we should switch the current thread to the #0 thread by inputting “~0s”, see figure.

 

Now, the context is switched to the main GUI hang thread. We can input the “K” command to get the full stack trace of the hang thread to see what it is waiting for.

 

All these 3 commands and output are listed in the figure below.

 

 

As you can see it is the Button.Click() method in .Net Winform calls the System.Threading.Thread.Sleep(30000) that caused the hang.

Posted by MSDNTST | 5 Comments

Amazing SSIS: Parameters in Execute SQL Task

 

SQL Server 2005 Books Online and MSDN have provided many references on the new features of SSIS; however few references demonstrate how to use parameters in Execute SQL Task. I would like to share my experiences here to enlighten those interested and save them time.

 

This chapter introduces three examples explaining the usage of OLE DB parameters in Execute SQL Task.

 

1.   Preparation

SQL Server 2000: My2KServer

Database: TestDB

Table: PCTEST

CREATE TABLE [dbo].[PCTEST] (

      [id] [int] IDENTITY (1, 1) NOT NULL ,

      [pid] [int] NOT NULL ,

      [sname] [char] (10)

) ON [PRIMARY]

GO

 

2.   Examples

2.1 Insert an item into the table with parameters.

1) Create an OLE DB Connection "OLE DB Connection: My2KServer.TestDB"

2) Drag a "Execute SQL Task" to the "Control Flow" panel from Toolbox;

3) Double click the task, set the properties as following:

    [General]  

    Connection: My2KServer.Northwind

    SQLSourceType: Direct Input

    SQLStatement:  INSERT INTO PCTEST (pid, sname) VALUES (?,?)

    BypassPrepare: False

    ResultSet: None   

Configuration at General Tab 

 

 

 

[pic] 1. Configuration at General Tab

    

[Parameter Mapping]

    Create two variables User:pid and User::sname.

    User::pid

    ---------------------------------

    Container: Execute SQL Task

    Name: pid

    Namespace: User

    Value Type: Int32

    Value: 10

Set variable for pid 

 

[pic] 2. Set variable for pid

 

    User::sname

    -------------------------------

    Container: Execute SQL Task

    Name: sname

    Namespace: User

    Value Type: String

    Value: Charles

Set variable for sname 

 

[pic] 3. Set variable for sname

 

    [Variable Name][Direction][DataType][Parameter Name]

    User::pid             Input         LONG           0

    User::sname      Input         VARCHAR  1

 

 

 

[pic] 4. parameter mapping

 

4) Save the package and execute the task.

 

 [pic] 5. A successful execution

           The result:

 

 

[pic] 6. Result in SQL Server

2.2 Get an output parameter value from stored procedure

1) Create a procedure in the database 

create procedure proc_insertPCTEST

(

@pid int,

@sname varchar(20),

@id int output

)

AS

INSERT INTO PCTEST (pid, sname) VALUES (@pid,@sname)

SELECT @id=SCOPE_IDENTITY()

 

2) In SSIS development environment, double click the "Execute SQL Task", change the SQLStatement "EXEC proc_insertPCTEST ?,?,? output", switch to the Parameter Mapping, add a variable:

User::id

==============

Container: Package

Name: id

Namespace: User

Value type: Int32

Value: -1

 

Direction: Output

Data Type: LONG

Parameter Name: 2

===============

        3) Create a second "Execute SQL Task" named "Execute SQL Task 1" and

            set the first "Execute SQL Task" as its input. Double click the "Execute

            SQL Task 1", set the OLE DB Connection and enter the SQL statement:

 "UPDATE PCTEST SET sname='TEST' WHERE id=?"

 

 

 

[pic] 7. Combine two “Execute SQL Task” into one package

 

Click Parameter Mapping, and add the User::id as its input parameter:

Variable Name: User::id

Direction: Input

Data Type: LONG

Parameter Name: 0

 

4) Save the package and execute it.

You will find that the new inserted value has been changed.

 

2.3 Get the return value from a stored procedure

         1) On the basis of 2.2, create a stored procedure:

create procedure proc_getid

as

declare @intval int

set @intval = (select max(id) as maxid from PCTEST )

RETURN @intval

 

2) Set the task properties in SSIS development environment:

Execute SQL Task Properties:

========================

[General]

SQL Statement: exec ? = proc_PCTEST

ResultSet: None

[Parameter Mapping]

User::id       ReturnValue       LONG    0

 

Execute SQL Task1 Properties:

=======================

[General]

SQL Statement: Update PCTEST Set sname='TEST1' WHERE id=?

ResultSet: None

[Parameter Mapping]

User::id Input    LONG    0

 

         3) Save the package and execute it.

The column ‘sname’ value will be changed to TEST1.

 

3.   Conclusion

The three examples demonstrate common usages of passing parameters in SSIS packages. In SSIS Development Studio, it is required to use the character ‘?’ to represent parameters of ADO/ODBC/OLE DB; though Package scope or Task scope variables can be defined and mapping to parameters, the parameters names must be numbers like 0,1,etc which represents the parameters sequentially. However for ADO.NET connections, it is required to use @<parameter> as the parameter name.

 

4.   Reference

Execute SQL Task 

http://msdn2.microsoft.com/en-us/library/ms141003.aspx

Integration Services Variables 

http://msdn2.microsoft.com/en-us/library/ms141085.aspx

How to: Add a Variable to a Package Using the Variables Window 

http://msdn2.microsoft.com/en-us/library/ms141670.aspx

OLE DB Source 

http://msdn2.microsoft.com/en-us/library/ms141696.aspx

 

Posted by MSDNTST | 8 Comments

Best practice for asking questions in MSDN newsgroup

 

1. How to get my question answered quick?

  • Create a new message, don't post a question of your own in response to another question.
  • Make the "Subject line" a short, relevant synopsis of your problem.
  • Before going into detail, clearly summarize the problem.
  • Make a concise, clear description of the problem.
  • Unless multiple problems seem related, do not mix them together, make separate posts.
  • When posting error messages, include the exact text in the error message. If there is a "Details" button, click it and copy/paste the error message itself into the post.
  • Tell if an error occurs when doing some action or using some particular software.
  • What changed in your system shortly before the problem occurred?   Knowing about a setting change or added software or hardware may be helpful in solving the problem.
  • Briefly describe your machine, OS, video card, CPU, amount of RAM, hard drive size and amount of free space.
  • Identify clearly the steps and procedures you have already used to try to fix the problem.
  • Proof-read and spell-check the post before sending.

 

2. Should I post confirmation after my issue is resolved?

It is useful to post back to the group afterwards, saying thanks and that a suggestion worked (or not).  That tells the group if it is a useful solution.

 

3. Where to submit a request for adding special NG into supported list?

https://support.microsoft.com/common/survey.aspx?scid=sw;en;1296&showpage=1&ws=msdn&sd=msdn&pa=msdnw

 

4. How to submit product feedback?

http://connect.microsoft.com/VisualStudio/Feedback

http://connect.microsoft.com/SQLServer/Feedback

 

5. Where to ask if I have some license related issue?

http://www.microsoft.com/licensing/index/worldwide.asp 

Posted by MSDNTST | 5 Comments

MSDN Managed Newsgroup Support Service Introduction

MSDN managed newsgroups are available in English to MSDN Universal, Enterprise, Professional, and Operating Systems subscribers to receive free technical support on select Microsoft technologies as well as to share ideas with other subscribers.

  • MSDN Newsgroup Support Boundary

In MSDN Managed Newsgroup, you may ask any question related to the development process. The supported newsgroups are for development products and .NET- related technologies. Common newsgroup postings include questions related to code and application development, interoperability with other Microsoft products, setup, installation, and debugging setup and questions.

 our service doesn’t provide support on following issues:

  • Debugging of source code itself, reading memory dumps or lab setup of complex scenarios.
  • Beta product and products that no longer have Extended support from MS.
  • Third party software or non-HCL hardware.
  • Resource Kit Utilities.
  • Licensing issues.
  • Non-English software or hardware.
  • Performance issues in a production environment.
  • MSDN Newsgroup Response Time 

MSDN Managed Newsgroup support offering is for non-urgent issues where an initial response from the community or a Microsoft Support Engineer within 2 business day is acceptable. Please note that each follow up response may take approximately 2 business days as the support professional working with you may need further investigation to reach the most efficient resolution. The offering is not appropriate for situations that require urgent, real-time or phone-based interactions. Issues of this nature are best handled working with a dedicated Microsoft Support Engineer by contacting Microsoft Customer Support Services (CSS) at http://msdn.microsoft.com/en-us/subscriptions/aa948874.aspx.

To get in-time notification for response, you may make use of our web client to set up email notification so that you can get email when there is somebody replied you. Please refer to the following link:
http://msdn.microsoft.com/subscriptions/managednewsgroups/#notifications.

You are supposed to receive an initial reply in 2 business days for a new posting. The most possible reasons for failing this are:

1. You didn’t post in a managed newsgroup.
To resolve this, you may check the full list of MSDN Managed Newsgroup List:
http://msdn.microsoft.com/subscriptions/managednewsgroups/list.aspx

2. Your account didn’t get registered correctly
Please submit a comment on MSDN Managed Newsgroup Contact Us web page:
https://support.microsoft.com/common/survey.aspx?scid=sw%3Ben%3B1296&showpage=1&ws=msdn&sd=msdn&pa=msdnw and our engineer will help you on it.

3. Your newsgroup reader didn't get latest update from our newsgroup.

Please browse with our web client: http://msdn.microsoft.com/subscriptions/managednewsgroups/


 

 

Posted by MSDNTST | 1 Comments
 
Page view tracker