천객만래 [千客萬來] (It has an interminable succession of visitors)

Creating GridView Columns Dynamically (Part 1)





http://www.dotnetbips.com/articles/56fadcb9-ee8b-4170-a6ad-cd4f38222bcb.aspx

Creating GridView Columns Dynamically (Part 1)

Introduction

Many months back I wrote three articles - Creating DataGrid ProgrammaticallyCreating DataGrid Templated Columns Dynamically - Part I and Creating DataGrid Templated Columns Dynamically - Part II. Even today these are amongst top viewed articles. This indicates how commonly developers need to create grid controls dynamically. Beginning with this article I am starting a series that will show you how to create data bound controls such as GridView and DetailsView programmatically. To begin with Part 1 shows how to add bound fields and command fields to a GridView. The GridView thus created is fully functional with paging, sorting and editing features.

Creating a sample web site

To begin with create new web site in Visual Studio. Drag and drop a GridView control and an SqlDataSource control on the default web form. Do not set any property of either controls at design time. We will be doing that via code.

Now key in the following code in the Page_Load event handler.

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.ConnectionString = 
@"data source=.;initial catalog=northwind;integrated security=true";
SqlDataSource1.SelectCommand = 
"select employeeID,FirstName,LastName from employees";
SqlDataSource1.UpdateCommand = 
"update employees set firstname=@FirstName,lastname=@LastName 
where employeeid=@EmployeeID";
SqlDataSource1.UpdateParameters.Add("@FirstName", "");
SqlDataSource1.UpdateParameters.Add("@LastName", "");
SqlDataSource1.UpdateParameters.Add("@EmployeeID", "");

if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.AutoGenerateColumns = false;
GridView1.DataKeyNames = new string[] { "EmployeeID" };
GridView1.AllowPaging = true;
GridView1.AllowSorting = true;
GridView1.PageSize = 5;

BoundField bf1 = new BoundField();
BoundField bf2 = new BoundField();
BoundField bf3 = new BoundField();

bf1.HeaderText = "Employee ID";
bf1.DataField = "EmployeeID";
bf1.ReadOnly = true;
bf1.SortExpression = "EmployeeID";

bf2.HeaderText = "First Name";
bf2.DataField = "FirstName";
bf2.SortExpression = "FirstName";

bf3.HeaderText = "Last Name";
bf3.DataField = "LastName";
bf3.SortExpression = "LastName";

CommandField cf = new CommandField();
cf.ButtonType = ButtonType.Button;
cf.ShowCancelButton = true;
cf.ShowEditButton = true;

GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(cf);
}
}

The code is dissected in the following sections

Configuring the SQL data source control

The code sets the ConnectionString property SQL data source control to required database connection string. In our example we will be using Employees table of Northwind database. Then SelectCommand and UpdateCommand properties are set to corresponding SELECT and UPDATE queries. The UPDATE query is important. Note that the names of the parameters specified in UPDATE statement are matching the table column names. The UPDATE statement contains three parameters - @FirstName, @LastName and @EmployeeID. These parameters are then added to the UpdateParameters collection.

Configuring the GridView control

The GridView control uses SqlDataSource1 as its data source. This is indicated by setting the DataSourceID property of GridView. Further some properties of GridView are set. Note that you need to set these properties only once and hence they come inside the "if" condition. The AutoGenerateColumns property indicates whether to generate GridView columns automatically. We set this property to false as we wish to add them via code. The DataKeyNames property is a string array specifying the primary key columns. The AllowPagng and AllowSorting properties enable paging and sorting feature respectively. The PageSize property sets the page size to 5.

Creating Bound Fields

The GridView control can contain many types of columns such as BoundField, HyperLinkField and TemplateField. In this example we will be using BoundField columns. We need three bound fields for EmployeeID, FirstName and LastName respectively. A bound field is represented by a class called BoundField. The HeaderText property of BoundField class indicates the column heading. The DataField property indicates the name of the table column that you wish to display in the bound field. The SortExpression property governs if that bound field will be sortable or not. If you set the SortExpression property to a column name then the bound field will be sortable based on that column. Since EmployeeID bound field represents primary key we set its ReadOnly property to true. This way it won't be editable.

In order to provide editing feature you need to add a CommandField column to the GridView. The ButtonType property of CommandField class indicates the type of button to render. Possible values are Button, LinkButton and ImageButton. The ShowCancelButton and ShowEditButton properties decide if the Edit and Cancel buttons will be displayed.

Once we create the columns they need to be added to the Columns collection of GridView.

That's it! If you run the web form then it should look as shown below:



You can now test GridView features such as paging sorting and editing.






Posted by SB패밀리

에러메시지 : Unable to start debugging on the web server







Unable to start debugging on the web server. The server does not support debugging of ASP.NET or ATL Server applications

 

이런 에러 메시지가 나타는 경우 다음과 같이 해결해 보자.

 

비주얼스튜디오에서 실행시 나는 에러로

 

이 에러는 보통 ASP.NET 파일 익스텐션 (.aspx)에 관한 정보가 인터넷 인포메이션 서비스에 제대로 등록이 되어 있지 않은 경우에 발생합니다.

 

한번 확인해 볼까요?

 

Control Panel -> Internet Information Services 에서 디버깅할 디렉토리 찾아 주세요. 오른쪽 클릭해서 프라퍼티 윈도우 열어 주세요.

 

그림 1

 

Virtual Directory 탭으로 가서, Applicatioin Settings 에 있는 Configuration 버튼을 꾸욱 눌러주세요

 

그림 2

 

.aspx의 Executable path 에 그 정보가 저장 되어 있습니다.
 
C:\WINDOWS\Microsoft.NET\Framework\Version\aspnet_isapi.dll 혹은
C:\WINNT\Microsoft.NET\Framework\Version\aspnet_isapi.dll
 
여기서 버전은 본인이 어떤 버전을 깔았는지에 따라 다릅니다.
 
이런 엔트리가 없거나 패스가 다르다면 프로그램 인스톨 시에 뭔가 문제가 있었던 거에요.
 
어떻게 해결할 까요?
 
Start -> Run 에서 cmd 타입합니다. 커맨드 프람프트에서 cd 이용하여
C:\WINDOWS\Microsoft.NET\Framework\Version\ 나
C:\WINNT\Microsoft.NET\Framework\Version\
로 이동해 주세요.  버전은 컴터마다 달라요~. 내 컴터에 있는 버전으로 해 주세요.
 
이동이 다 되었으면...
 
aspnet_regiis -i
 
타입하고 엔터키 눌러서 실행해 주세요.


Posted by SB패밀리

현재 페이지에 표시된 DataGrid의 내용을 버튼클릭시 다운로드 하는 소스입니다.
필요해서 한번 해봤는데 되네요..

 

DataListRepeater 등 모든 서버컨트롤이나 HTML컨트롤에도 사용 가능합니다! *^^*

 

private void Button1_Click(object sender, System.EventArgs e)
{   
    System.Web.HttpContext.Current.Response.Buffer = true;
    System.Web.HttpContext.Current.Response.AddHeader
        ("Content-Disposition", "attachment;filename=20050614.xls");
   System.Web.HttpContext.Current.Response.ContentType="application/unknown";

 

    // 이부분은 web.config의 <globalization requestEncoding="utf-8"   
    // responseEncoding="utf-8" /> 인코딩 부분과 같도록 맞춰주시면 됩니다.
   

    // 2005.09.26 추가 : 인코딩 문자열을 자동으로 맞추려면

    // Request.ContentEncoding.HeaderName 로 인코딩 문자열을 받아서 사용한다.

    System.Web.HttpContext.Current.Response.Write       
        ("<meta http-equiv=Content-Type content='text/html; charset=utf-8'>");

 

    System.IO.StringWriter sWriter = new System.IO.StringWriter();   
    System.Web.UI.HtmlTextWriter htmlWriter
           = new System.Web.UI.HtmlTextWriter(sWriter);


    DataGrid1.RenderControl(htmlWriter);   


    System.Web.HttpContext.Current.Response.Write(sWriter.ToString());   
    System.Web.HttpContext.Current.Response.End();
}

참조 : http://blog.naver.com/tear230/100013986512

DataGrid를 이용할줄 안다면 GridView도 응용해서 이용할수 있습니다.
Posted by SB패밀리

자바스크립트 개발에서 자식창에서 부모창이 갖고 있는 이벤트를 실행하는 방법입니다.

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

자식창에 있는 값을 부모창에 바로 반영하고 싶을 경우
보통 스트립트로 자식창의 값을 부모창에 넘긴다음
부모창의 변경된 내용을 submit시킴으로써 일괄적으로 처리합니다.

하지만 가끔 자식창에서 부모창으로 값을 넘기면서 바로 DB처리를 해야 할 경우가 있을지도 모릅니다. 그럴때 이용하는 방법입니다.

다음은 자식창에서 입력한 텍스트값을 부모창의 링크버튼 이벤트를 이용하여
부모창의 리스트박스에 추가하는 소스로 두가지 방법을 사용해서 만들어 보았습니다.

자세한 내용은 첨부한 소스코드를 참고하세요.

 

--- 아래는 팝업페이지의 소스코드 일부입니다..

 

  <script language="javascript">
  <!--
   // __doPostBack에 인지값을 직접 넘기는 방법
   function ListBoxAdd1()
   {
    var strValue = document.all["txtValue"].value;
    opener.__doPostBack('lnkEvent1', strValue);
   }
   
   // 부모창의 hidden input 으로 넘겨서 받는 방법
   function ListBoxAdd2()
   {
    opener.document.all["hidValue"].value = document.all["txtValue"].value;
    opener.__doPostBack('lnkEvent2', '');
   }
  //-->
  </script>

 

   <INPUT type="text" id="txtValue">
   <INPUT type="button" value="추가(방법1)" onclick="ListBoxAdd1();">
   <INPUT type="button" value="추가(방법2)" onclick="ListBoxAdd2();">

 

-- 아래는 부모창의 소스코드 일부입니다.

-- 자식창에서 __doPostBack을 사용하시려면 링크버튼을 이용하시는게 편리합니다.

-- 링크버튼을 사용하시면  컴파일후 부모창에  __doPostBack 스크립트 함수를 자동으로 생성해주기 때문이죠.

 

<aspx>

    <asp:ListBox id="ListBox1" runat="server">
     <asp:ListItem Value="선택하세요">값을 추가해주세요.</asp:ListItem>
    </asp:ListBox>

 

    <asp:LinkButton id="lnkEvent1" runat="server"></asp:LinkButton>
    <asp:LinkButton id="lnkEvent2" runat="server"></asp:LinkButton>
   <input type="hidden" id="hidValue">

 

<cs>

        // RaisePostBackEvent를 이용해서 인자값 받기

        string newValue = null;
        protected override void RaisePostBackEvent

                (IPostBackEventHandler sourceControl, string eventArgument)
        {
                newValue = eventArgument;
                base.RaisePostBackEvent (sourceControl, eventArgument);
        }
        private void lnkEvent1_Click(object sender, System.EventArgs e)
        {
                if(newValue != null)
                         ListBox1.Items.Add(newValue );
        }

 

        // hidden값에 인자값을 넣어서 받기

        private void lnkEvent2_Click(object sender, System.EventArgs e)
        {
                if(Request["hidValue"] != null)
                        ListBox1.Items.Add(Request["hidValue"]);               
        }


출처 : http://blog.naver.com/tear230/100012963979

Posted by SB패밀리



도입

어플리케이션 개발은 종종 매우 역동적인 과정을 거치며, ‘즉각적인 사용가능이란 기술의 특성은 반복적인 개발 과정과 빈번한 발행을 가져온다.

사용자 품질확인 테스팅(UAT: User Acceptance Testing) 위한 빌드를 배포할 , 이는 고객들에게 현재 빌드가 다음과 같은 이유로 디버그 빌드임을 기억나도록 하는데 도움이 된다.

  1. 배너 안에 버전 번호가 보인다면, 피드백이 보내질 쉽게 참조하면 된다.
  2. 빌드 버전은 종종 동일한 어셈블리들의 릴리즈 버전에 비해 형평 없는 결과를 내놓는데, 배너가 이를 설명해주기도 한다.
  3. 사용자는 우연찮게 테스트 사이트를 사용하면서 사이트가 살아 있거나, 혹은 죽어있다고 생각하게 되는데(이런 일이 종종 일어난다!), 배너는 이를 분명하게 해준다.

문서는 점검중인 웹사이트의 ASPX 페이지에서 배너 개발 렌터링하는 HTTP 파이프라인에 대한 플러그인을 위한 매우 실용적인 코드를 설명하고 제공한다.

Web.config 파일에 적절한 설정을 추가하고, 배너 어셈블리가 사이트의 bin 디렉토리에 위치해 있어야 한다는 유일한 요구사항이다.

예제 배너는 페이지에 플로팅 이미지로 구석에 추가되기 때문에 페이지의 레이아웃에 방해가 되지 않는다. 이미지, ALT 텍스트, 그리고 자바스크립트는 모두 최종 어셈블리에 포함 리소스로 저장되며, 이는 완전한 독립실행형, 그리고 모듈러 (modular tool) 만든다.

배경과 전제조건

ASP.NET 기본 지식이 요구되고, HTTP 파이프라인에 대한 기본적인 이해가 도움이 되지만 필요하지는 않다. 사실, 예제를 실행시켜보고 싶을 따름이라면, 완성된 어셈블리를 다운로드 받고 아래 "설정" 부분으로 넘어가면 되겠다!

이미지 띄우기

페이지에 위치한 배너 이미지는 부분 투명 PNG, 페이지의 상단 오른쪽에 할당된 고정된 위치로 설정된 DIV 감싸여 있다. 자바스크립트는 하이퍼텍스트 스트림에 HTML 직접 삽입하기 보다는 페이지에 요구된 HTML 위치시키는데 사용된다.

<div style="Position: absolute;Top: 0;Right: 0;

    Background: transparent;Filter: Alpha(Opacity=60);-moz-opacity:.60;opacity:.60;">

    <img src="{0}" alt=\"development build: version {1}\" />

</div>


String
형식은 HTML string 배너 이미지의 경로와 대체 텍스트(alternate text,) 삽입하기 위해 사용된다.

// 실행중인 어셈블리의 버전 가져오기,

// 배너 대체 텍스트에서 사용되어야 하는 어셈블리의 버전

Version version = page.GetType().BaseType.Assembly.GetName().Version;

 

// 로컬 리소스에서 배너 HTML 검색하고,

// 이미지와 대체 텍스트를 위한 동적 URL 삽입

string szHtml = string.Format(BuildConfigurationBannerResources.BannerHtml,

    page.ClientScript.GetWebResourceUrl(GetType(),

    "Common.Web.Resources.BannerImage.png"), version);

 

// 페이지가 로드된 후에 HTML에서 DOM으로 삽입되는 자바스크립트 등록

page.ClientScript.RegisterStartupScript(GetType(), "DevelopmentBanner",

    string.Format("Event.observe(window, 'load', function()

        {{new Insertion.Bottom($(document.body), '{0}');}});", szHtml), true);


HTTP
파이프라인: 동작중인 ASP 조작

HTTP 파이프라인은 ASP.Net 실행 시퀸스로, HTTP 요청을 다룰 실행의 시퀸스를 다룬다.
기본적으로, HTTP 모듈은
IHttpModule 인터페이스의 구현물로, Web.config 통해 실행 시퀸스를 병합시키도록 설정하며, 개발자들은 파이프라인에 쉽사리 기능을 추가하도록 해준다.

런타임 제공되는 모든 ASP.NET 페이지에 사용자지정 자바스크립트를 등록하기 위해서 HTTP 모듈을 사용하려 한다.

관심을 갖고 있는 파이프라인 이벤트는 PreRequestHandlerExecute, 우리의 사용자 지정 자바스크립트를 첨부할 것이다. HTML 콘텐츠를 직접 조작해야 해야 하지만, HTML 결과를 차례로 다루는 C# Page 오브젝트 모델을 사용하면 HTML 파싱의 복잡한 작업을 자초할 필요는 없다.

어플리케이션의 Context Handler 통해서 Page 오브젝트에 접근 가능하며, 이번 경우엔 ASPX 페이지(AXD, 혹은 런타임 매핑 URL 타입과는 대조적으로) 위한 요청인 Page 인스턴스이다.

IHttpHandler handler = application.Context.Handler;

if (handler is Page)

{

    Page page = handler as Page;

    if (IsAssemblyDebugBuild(page))

    {

        ...

    }

}


배너
표시 여부 결정

어플리케이션 어셈블리가 디버그 빌드인지 결정하기 위해서는, 디버그 빌드 동안 닷넷 컴파일러에 의해 삽입된 어셈블리 내의 다음 코드에서 DebuggableAttribute 찾아야 한다.

private bool IsAssemblyDebugBuild(Page page)

{

    foreach (Attribute att in

        page.GetType().BaseType.Assembly.GetCustomAttributes(false))

        if (att is System.Diagnostics.DebuggableAttribute)

            return (att as System.Diagnostics.DebuggableAttribute).IsJITTrackingEnabled;

    return false;

}


설정

어플리케이션에 배너를 사용하도록 설정하기 위해서, 어플리케이션의 bin 디렉토리에 배너 어셈블리가 포함되어 있어야 하고, Web.config 파일에 다음 XML 추가해야 한다.

 <httpModules>

   <add name="Banner" type="Common.Web.Modules.BuildConfigurationBannerModule,

        Common.Web"/>

 </httpModules>


이런
모두 갖춰지면, 어플리케이션의 모든 페이지는 디버그 어셈블리로 빌드 배너를 가지게 된다.

 

 

출처 : http://www.codeproject.com/KB/aspnet/BuildBanner.aspx

Posted by SB패밀리




A Complete Scriptable ActiveX Web Control Tutorial using ATL

By Arif Zaman | 18 Dec 2007 | Unedited contribution
An article on Scriptable ActiveX Web Control using ATL
Is your email address OK? You are signed up for our newsletters but your email address is either unconfirmed, or has not been reconfirmed in a long time. Please click here to have a confirmation email sent so we can confirm your email address and start sending you newsletters again. Alternatively, you can update your subscriptions
Scriptable ActiveX Web Control

Introduction

ActiveX control is a term used to denote reusable software components that are based on Microsoft Component Object Model (COM) that allows the developer to create objects or controls that can be used to "activate" content on the World Wide Web.

I have read lots of stuffs over the internet but I have not find any complete guideline or example through the process I can build an ActiveX Control for web using ATL with VC++6.0. I wrote this article because I couldn't find a unified description of this process anywhere on the Web and also from my hurdles. I am going to present you a complete example with necessary stuffs. Hope this will help you to understand how we can build a Scriptable ActiveX control for web using ATL and also you will get the clear vision about the ActiveX security details. It's written with as much detail as possible, but with the assumption that the reader basically knows his stuff.

In this article, I have tried to present you an example of Scriptable ActiveX Web Control using ATL which will display a Label Control with the current Date and Time on your Internet Explorer. Also you will be guided step by step on creating the control using Microsoft VC++6.0 as safe for WEB.

Safety and security

The security concerns associated with ActiveX control is mainly due to the fact that ActiveX controls can do almost anything that a normal application can. Therefore, both malware and useful form ActiveX controls exists; thus the threat level of an ActiveX control can be associated with how trusted its author is.

However, there is one famous case of ActiveX controls safety concern: Internet Explorer. Internet Explorer has the ability to run ActiveX controls within a web page. This is both a blessing and a pain.

ActiveX controls like Adobe Reader, Adobe Flash Player, Apple QuickTime Player, Microsoft Windows Media Player, Real Networks RealPlayer, and Sun Java Virtual Machine are routinely used by Internet surfers every hour of a day all across the globe.

However, opening a web page that contains a harmful ActiveX control, and then allowing Internet Explorer to run that harmful control, would be same as running a malware on the computer. Fortunately, Internet Explorer 6 and Windows Vista have taken actions to reduce such risks.

Requirements for Scriptable ActiveX Controls

Microsoft has published a document that describes all aspects of component object safety with regard to scripting ActiveX controls.

Before registering your control as safe for scripting, you must ensure that your control does not take any actions that may be unsafe when used by a scripting client. Unsafe actions include exposing information normally kept private, such as passwords and other sensitive information, executing files, and making dangerous system calls.

Another type of object safety concerns the use of parameters and properties with the control. When used with a scripting client, a safe control must ensure that the control can continue to function with any possible combination of properties defined by the user.

Design a Scriptable ActiveX Controls

A scriptable ActiveX control is a control that is constructed so that it is appropriate for use by scripting clients. Scriptable controls are designed to be safe when used in a Web browser, such as Internet Explorer, or by scripts written for the Windows Scripting Host (WSH). Scriptable controls also support mechanisms to simplify passing parameters to the control via a scripting language.

By default, ActiveX controls are not considered safe for scriptable clients. If you have an ActiveX control that could be useful by scripting clients, taking a few simple steps can expand the usefulness of your control. If you're using ATL, these changes typically take just a few minutes.

To be scriptable, an ActiveX control must meet the following requirements:

  • Be safe when executed by an arbitrary scripting client.
  • Be registered as "Safe for Scripting".
  • Support the IPersistPropertyBag interface. This is technically not a requirement, but it simplifies the task of passing parameters to the control.
  • Creating a Scriptable ActiveX Control

    To create a Scriptable ActiveX control, use Microsoft Visual C++ 6.0 to perform the following steps:

    1. File->New->Projects.

    2. In the New Project dialog, as shown in Figure 1, select "ATL COM AppWizard".

    New Project dialog

    Figure 1. New Project Dialog

    3. Name the project ScriptableActiveX; for Location, enter the working folder for the project's source code, and then click the OK button.

    4. You will see a screen, as shown in Figure 2, that gives you several choices. The first choice is "Server Type". We are going to build a Server DLL, so make sure that the Server Type is set to "Dynamic Link Library".

    ATL COM AppWizard

    Figure 2. ATL COM AppWizard

    5. The other three checkboxes below do not concern us for this particular project, so we can ignore them. Press the finish button to have the Wizard generate to appropriate files for you.

    6. A "New Project Information" window, as shown in Figure 3, will appear to tell you what files are going to be created. Press the Ok button to accept this.

    New Project Information

    Figure 3. New Project Information

    Creating a new ATL object

    1. From the Insert menu, select "New ATL Object" menu item. The "ATL Object Wizard" window, as shown in Figure 4, will appear.

    ATL Object Wizard

    Figure 4. ATL Object Wizard

    2. Select Controls from the wizard's Category list box, and then select Full Control as the control type. Click Next to begin adding ScriptableLabel control to the project.

    3. The "ATL Object Wizard Properties" dialog, as shown in Figure 5, will appear so that you can define your control's properties. For full controls, such as ScriptableLabel, the dialog box offers four tabs.

    ATL Object Wizard Properties

    Figure 5. ATL Object Wizard Properties

    4. All component types present a Names property page that contains naming attributes for ATL components. You only need to fill in the Short Name property for ScriptableLabel and the other fields are filled in automatically.

    5. The second tab, as shown in Figure 6, for most component types is the Attributes property page, which is used to collect information about the component. All these values are the default options, except "Support Connection Points" properties for the component. Connection points are used to supply events to a control's container.

    ATL Object Wizard Properties (Attributes)

    Figure 6. ATL Object Wizard Properties (Attributes)

    6. The third tab, as shown in Figure 7, is the Miscellaneous tab. It contains attributes specific to ActiveX controls.

    ATL Object Wizard Properties (Miscellaneous)

    Figure 7. ATL Object Wizard Properties (Miscellaneous)

    7. The final tab, as shown in Figure 8, in the dialog box is Stock Properties. It contains a list of all stock properties that can be implemented by an ActiveX control.

    ATL Object Wizard Properties (Stock Properties)

    Figure 8. ATL Object Wizard Properties (Stock Properties)

    8. The ScriptableLabel control uses the following stock properties:

  • Background Color
  • Caption
  • Font
  • Foreground Color
  • After you select the stock properties listed here, click OK to close the dialog box. The ATL New Object Wizard then generates the necessary code and adds it to your project.

    Modify Control Attributes

    The default handler for OnCreate will superclass a default instance of the Windows CStatic class. Apply the following window styles changes to the OnCreate() member function to the ScriptableLabel control:

    Collapse | Copy Code
    
    m_ctlStatic.Create( m_hWnd,
                        rc, 
                        _T("Static"),
                        WS_CHILD|WM_PAINT);
    
    

    Retrieving Ambient Properties

    When the control is initially loaded, it collects the current foreground color, background color, and font from its container. A good time to collect ambient properties is when the control and its container negotiate the client site. Add the following source code to the ScriptableLabel.cpp source file. This function overrides the base class implementation of SetClientSite() and stores the ambient values of these three properties.
    Collapse | Copy Code
    
    STDMETHODIMP CScriptableLabel::SetClientSite(LPOLECLIENTSITE pSite)
    {
        HRESULT hr = CComControlBase::IOleObject_SetClientSite(pSite);
        if(!m_pFont && pSite)
        {
            hr = GetAmbientFontDisp(&m_pFont);
        }
        GetAmbientBackColor(m_clrBackColor);
        GetAmbientForeColor(m_clrForeColor);
        return hr;
    }
    
    

    Add the following member function declaration to the CScriptableLabel class:

    Collapse | Copy Code
    
    STDMETHOD(SetClientSite)(LPOLECLIENTSITE pSite);
    
    

    Drawing the Control

    The OnDraw() function is called by the ATL framework, passing in a structure that contains various bits of information needed to actually paint information on the screen. Our implementation isn�t much more complicated than it would be if we were simply displaying the current Date and Time. Add the following drawing code for the control to the ScriptableLabel.h header file.
    Collapse | Copy Code
    
    void DrawString( HDC hdc, RECT* rc, BSTR caption )
    {
    	USES_CONVERSION;		
    	TCHAR* pCaption = OLE2T(caption);
    
    	DrawText( hdc,
    			 pCaption,
    			 lstrlen( pCaption ),
    			 rc,
    			 DT_WORDBREAK );
    }
    
    HRESULT OnDraw(ATL_DRAWINFO& di)
    {
    	RECT& rc  = *(RECT*)di.prcBounds;
    	HDC   hdc = di.hdcDraw;
    
    	COLORREF clrFore, clrBack;
    	OleTranslateColor(m_clrForeColor, NULL, &clrFore);
    	OleTranslateColor(m_clrBackColor, NULL, &clrBack);
    	SetTextColor(hdc, m_clrForeColor);
    	HBRUSH hbrBtn = CreateSolidBrush(m_clrBackColor);
    
    	FillRect(hdc, &rc, hbrBtn);		
    	DrawString(hdc, &rc, m_bstrCaption);	
    
    	DeleteObject(hbrBtn);
    	return 0;
    }
    
    

    Implementing IPersistPropertyBag

    To simplify the use of ScriptableLabel in a scripting client, such as Internet Explorer, the control must support the IPersistPropertyBag interface. The ATL class library includes a class, IPersistPropertyBagImpl, that provides a default implementation of IPersistPropertyBag that is sufficient in most cases.

    1. Add the following line to your class derivation list:

    Collapse | Copy Code
    
    public IPersistPropertyBagImpl<CScriptableLabel>
    
    

    2. Add the following lines to your COM_MAP:

    Collapse | Copy Code
    
    COM_INTERFACE_ENTRY(IPersistPropertyBag)
    
    

    Marking the Control as Safe for Scriptable Clients

    You can easily add support for marking the Control as Safe for Scriptable Clients by implementing the IObjectSafety interfaces. This is done by deriving your control from the default ATL implementation, IObjectSafetyImpl.

    You can use two methods to mark a control as safe for scripting clients:

  • Make appropriate entries directly in the System Registry.
  • Implement the IObjectSafety interface.
  • Microsoft recommends that you use new controls to implement the IObjectSafety interface instead of making Registry entries. IObjectSafety enables the control to apply much finer-grained safety policies than possible using the Registry.

    ATL provides a default implementation of IObjectSafety that you easily can take advantage of by deriving your class from the IObjectSafetyImpl class.

    1. Add the following line to your class derivation list:

    Collapse | Copy Code
    
    public IObjectSafetyImpl<CScriptableLabel, 
                            INTERFACESAFE_FOR_UNTRUSTED_CALLER | 
                            INTERFACESAFE_FOR_UNTRUSTED_DATA>
    
    

    Two template arguments are passed to IObjectSafetyImpl:

  • The name of the class deriving from IObjectSafetyImpl.
  • The type of safety to be applied to the control.
  • Two values may be passed for the safety options:

    INTERFACESAFE_FOR_UNTRUSTED_CALLER specifies that your control can be used safely by a scripting client and does not violate any of Microsoft's security or safety guidelines. INTERFACESAFE_FOR_UNTRUSTED_DATA specifies that your control will work (or at least degrade gracefully) in the presence of any possible set of par

    2. Add the following lines to your COM_MAP:

    Collapse | Copy Code
    
    COM_INTERFACE_ENTRY(IObjectSafety)
    
    

    Compiling the Scriptable ActiveX Control

    Compile the ScriptableActiveX project. The compiler will register your new DLL in the registry so that other programs can make use of it. You can test the control in a variety of control containers, including Visual Basic and Visual C++. You will find lots of examples using Visual Basic and Visual C++. Better! we consider as web control.

    Because the ScriptableLabel control is scriptable, you can also use the control on an HTML page with Internet Explorer. Lets try it out.

    Building a Signed ActiveX Control

    To use your control on web pages, it is very convenient to distribute it as a .cab (cabinet file). This is a compressed archive - the classic use is to put the .cab file on a web server, and refer to it from web pages that host the control. Internet Explorer is smart enough to download and install the control if it is not already installed on the client machine, and to selectively update any files that are newer in the .cab file. Microsoft provides CABARC.EXE for creating and editing .cab files.

    The Contents of a CAB File

    A CAB file contains at least two files in the archive: an ActiveX component file (.EXE, .DLL or .OCX file), and an .INF file.

  • Component File (.EXE, .DLL or .OCX): The type of ActiveX component you create determines the file extension of the file included here. All ActiveX controls have a .OCX extension. Other ActiveX components either .EXEs or .DLLs. This file is your ActiveX component being installed.
  • .INF: This is the Information file that contains information about what other files your ActiveX component depends on (dependency files), where to get copies of those files, and how to install those files.
  • Creating a CAB File

    This section describes creating CAB files for distributing ATL and MFC controls over the Internet.

    To create a CAB file:

    1. Create an INF file.

    2. Run the CABARC utility.

    1. Creating an INF File

    The INF file is a text file that specifies the files (such as DLLs or other OCXs) that need to be present or downloaded for your control to run. An INF file allows you to bundle all the needed files in one compressed CAB file. By default, files with the same version numbers as existing files on the user's hard disk will not be downloaded.

    As an example, the following INF file will be used to create a CAB file for the ScriptableActiveX control.

    Collapse | Copy Code
    ; Sample INF file for SCRIPTABLEACTIVEX.DLL
    [version] 
    ; version signature (same for both NT and Win95) do not remove
    signature="$CHICAGO$"
    AdvancedINF=2.0  
    
    [Add.Code]
    ScriptableActiveX.dll=ScriptableActiveX.dll
    ScriptableActiveX.inf=ScriptableActiveX.inf
    
    [ScriptableActiveX.dll]
    file-win32-x86=thiscab
    clsid={B8748B60-E34D-42AA-9309-8012CA4964AC} 
    FileVersion=1,0,0,1 
    RegisterServer=yes
    
    [ScriptableActiveX.inf]
    file=thiscab
    ; end of INF file
    
    The clsid is the CLSID of the control to be installed.

    2. Running the CABARC Utility

    Once you have created an INF file, run the CABARC utility to create the CAB file. You should run CABARC in the directory that contains your source files. On the command line, put the source files in the order they appear in the INF and the INF file last. For example, to make a CAB file for the Polygon control from the INF above, use the following command:

    Collapse | Copy Code
    CABARC -s 6144 n ScriptableActiveX.cab ScriptableActiveX.dll ScriptableActiveX.inf
    
    The -s option reserves space in the cabinet for code signing. The n command specifies that you want to create a CAB file.

    Code Signing Tools

    Microsoft provides code signing tools as part of the "Microsoft .NET Framework software development kit (SDK) 1.1". To download the SDK, visit the following Microsoft Web site: .NET Framework SDK Version 1.1. After you install the SDK you will be able to find the code signing files in the following location on your PC: "\Program Files\Microsoft.NET\SDK\v1.1\Bin". From the many files found in the above BIN directory the following are of interest to us:

  • signcode.exe
  • makecert.exe
  • cert2spc.exe
  • chktrust.exe
  • Recently, with the introduction of "Studio 2005" Microsoft has released a new set of tools. The new set of tools is provided as part of the "Visual Studio 2005" and in the "Platform SDK". To download the "Platform SDK", visit the following Microsoft Web site: Platform SDK Full Download. After you install the SDK you will be able to find the code signing files in the following location on your PC: "\Program Files\Microsoft Platform SDK\Bin". From the many files found in the above BIN directory the following are of interest to us:

  • signtool.exe
  • makecert.exe
  • cert2spc.exe
  • All the above mentioned tools are actually small console programs that should be run from a command prompt. When run, each program expects command-line parameters in a special syntax. Now, we will demonstrate how to do it in this article.

    Signing a CAB File

    Security is becoming increasingly important for software and media developers. "Code Signing" enables end users of your software to verify that the code you provide comes from the rightful source and that it has not been maliciously altered or accidentally corrupted.

    Code signing technology is available for many years, but many software vendors refrained from using it because of the complexity involved in the process. However - since the release of "Windows XP Service Pack 2" - code signing can not be ignored any more.

    With XP SP2, when downloading an UN-SIGNED program with Internet Explorer and choosing to open it (or even if saved to a file and later opened via Windows Explorer), the browser will display the "Security Warning" dialog. BUT when downloading a SIGNED program the browser does not result in annoying error messages complaining that it is an unsigned or unsafe control.

    You have 2 options to sign your code:

    Option-1. Using Test Certificate

    Option-2. Using Public Certificate

    Option-1: Using Test Certificate

    Before you start with the process it is highly recommended that you create a "TEST certificate", and use it to sign your program as a test run. A program signed by this certificate must not be distributed on the net.

    Use the following steps to sign and validate the .cab file:

    1. Type the following at a command prompt to create a private key file, Mycert.pvk.

    Collapse | Copy Code
    makecert -sv "mycert.pvk" -n "CN=My Company" mycert.cer
    
    The file created in this step, Mycert.cer, is used to create an .spc file. Type the password in the dialog box.

    2. Create an .spc file from the certificate file with the correct password. To do so, type the following line at a command prompt:

    Collapse | Copy Code
    cert2spc mycert.cer mycert.spc
    
    Note that this step involves creation of a test private key. Alternatively, valid certificates can be created through Microsoft Certificate Server for Intranet use or purchased from external vendors for Internet use.

    3. Create a Personal Information Exchange file. This step is optional. You will need it only if you select to sign your code using SIGNTOOL.EXE as described above. The following command line may be used to create a "Personal Information Exchange" (PFX) file:

    Collapse | Copy Code
    pvk2pfx -pvk mycert.pvk -pi Pass1 -spc mycert.spc -pfx mycert.pfx -po Pass2 -f
    
    PVK2PFX.EXE expects 2 passwords:

    Pass1: - Provide the same password you used when creating the Private & Public keys.

    Pass2: - Provide a new password to protect the PFX file.

    Once signed you can distribute the ActiveX component to any user, BUT the user must install certificate chain. If you want users to install an ActiveX component without the Root and Intermediate certificates then buy a Public code-signing certificate.

    Option-2: Using Public Certificate

    To be able to sign your code you will need a certificate. Certificates are issued by special Internet organizations called CA (Certificate Authority). There are many such organizations, the most prominent ones are: verisign.com and tawthe.com.

    You can get a full list of CAs by going to: Microsoft Root Certificate Program Members

    However - acquiring a certificate is quite a tedious and time consuming process, (The CA has to identify you or your organization before it can issue a certificate) and you should expect to pay few hundred of dollars for the certificate.

    Finishing Touches

    Now, Use the key information to sign the .cab file:

    Collapse | Copy Code
    signcode -v mycert.pvk -spc mycert.spc ScriptableActiveX.cab -t [Timestamp server URL] 
    

    Or, the following commands may be used to sign your code using SIGNTOOL.EXE:

    Collapse | Copy Code
    signtool sign /f mycert.pfx /p Pass2 /v ScriptableActiveX.cab /t [Timestamp server URL]
    
    Pass2: Enter here the second password you used when creating the PFX file.

    Note Specify the timestamp server URL at this step. The timestamp server URL provides a place to enter or edit the location of a timestamp server. A timestamp server validates the date and time that the cabinet file was signed. Certificate files can expire after a certain period of time. Contact your certificate file provider (certificate authority) for the location of their timestamp server. The URL of a time stamping service provided for free by verisign.com http://timestamp.verisign.com/scripts/timstamp.dll

    Validate a CAB File

    Follow this procedure to validate a .cab file:

    Option-A: Using CHKTRUST

    a. Type the following at a command prompt to run SETREG.EXE on the client system with the TRUE value so that the test certificates are recognized:

    Collapse | Copy Code
    setreg -q 1 TRUE
    

    b. Run CHECKTRUST.EXE to ensure that the CAB file is signing correctly:

    Collapse | Copy Code
    chktrust ScriptableActiveX.cab
    
    Expected results:
    Collapse | Copy Code
    ScriptableActiveX.cab: Succeeded
    

    Option-B: Using SIGNTOOL

    Run SIGNTOOL.EXE to verify the signing:

    Collapse | Copy Code
    signtool verify /v /a ScriptableActiveX.cab
    
    Expected results:
    Collapse | Copy Code
    ScriptableActiveX.cab: Succeeded
    

    Option-C: Using Properties

    You can also use the following method to verify your digital signature:

  • Open Explorer.
  • Browse to the file you just signed.
  • Right Click the file name and select "Properties".
  • Explorer will present you with the properties dialog of the file. This properties dialog will include a new tab "Digital Signatures". You can now read the details of the signature in this tab.

    Embedding a Signed CAB File on a Web Page

    ATL and MFC controls are embedded in Web pages using the <OBJECT> tag. Within the <OBJECT> tag, you need to specify three attributes for the control:

    Collapse | Copy Code
    
    <OBJECT classid=B8748B60-E34D-42AA-9309-8012CA4964AC
    	id=ScriptableLabelControl
    	CODEBASE ="ScriptableActiveX.cab#version=1,0,0,1">
    </OBJECT>
    
    

    The ID parameter refers the name of the control. The CLASSID parameter refers the CLSID of the control. And the CODEBASE parameter refers the location from which to download the control. Note that CODEBASE can point at a number of different file types successfully.

    If you include the optional version number with a CAB file, the version number should refer to the control being downloaded. For example, since ScriptableActiveX.dll has a version number of 1, 0, 0, 1, the version for the CAB is also 1, 0, 0, 1.

    If you do not include the version number, older versions of the same control will not be replaced if they are found on the client machine.

    Testing the Scriptable ActiveX Web Control

    Adding controls by hand is not a simple process. The CLSID numbers are unwieldy to type, and it can be difficult to visualize the effects of the parameter settings on the control. To help with these difficulties, Microsoft created the ActiveX Control Pad, which can be obtained from their web site at Microsoft ActiveX Control Pad.

    To test the Scriptable ActiveX Web Control with JavaScript, you may use ActiveX Control Pad to create or you may find it easier to lay out your page in your preferred HTML editor as the following HTML code:

    Collapse | Copy Code
    
    <HTML>
    <HEAD>
    <TITLE>Scriptable ActiveX Web Control</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    	function NotifyActiveX(e)
    	{
    		if ( e.readyState != 4 ) return;
    		window.setInterval("document.all.ScriptableLabelControl.caption=(new Date()).toString()",1000);
    	}
    </SCRIPT>
    <STYLE TYPE="text/css">
    #ScriptableLabelControl {
    	width: 250px;
    	height: 27px;
    	padding: 10px;
    	border: thin solid #408080;
    	margin-left: 10em;
    }
    </STYLE>
    </HEAD>
    
    <BODY>
    <OBJECT 
      ID="ScriptableLabelControl"
      onReadyStateChange="NotifyActiveX(this)"
      CLASSID="CLSID:B8748B60-E34D-42AA-9309-8012CA4964AC"
      CODEBASE="ScriptableActiveX.cab">
    </OBJECT>
    </BODY>
    </HTML>
    
    

    Save this HTML code in your web server, and browse it!

    Internet Explorer will prompt the user before downloading and installing the ActiveX control. If Internet Explorer is attempting to install the Signed ActiveX control automatically it shows the prompt, as shown in Figure 9.

    Install ActiveX

    Figure 9. Install ActiveX

    When prompted with a certificate, please accept it. When downloading and installation process will be finished, the current date and time should appear, as shown in Figure 10.

    Scriptable ActiveX Control

    Figure 10. Scriptable ActiveX Control

    If you see the current date and time displayed properly in your browser, CONGRATULATIONS! ActiveX and scripting are working properly.

    Note:

  • If you see a date and time but it isn't the right time, your PC's clock is set wrong! Double-click the time in the system tray to correct it.
  • If you see a blank space, ActiveX is probably working properly, but not scripting.
  • If you see the message ActiveX is not supported, then your browser doesn't recognize ActiveX at all. Netscape, Opera, or other browsers usually do not support ActiveX.
  • When you think you've corrected any problem you are having with this, simply refresh the page [press F5] to try again.
  • Conclusion

    For a control to be scriptable, it must follow Microsoft's object safety guidelines and be marked as safe for scripting. In this article, you examined the IObjectSafety interface and learned how a control built using ATL can take advantage of IObjectSafety. An example of a safely scriptable ActiveX control helped you explore this topic.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    출처: http://www.codeproject.com/KB/atl/ScriptableActiveX.aspx

    Posted by SB패밀리

    Cabarc 사용법

    실행화일을 배포하기 위해 일반적으로 사용하는 것이 CAB화일 형태로 만든 다음 하나의 CAB화일을 OBJECT Tag로 넣어 HTML에 삽입 하는 것입니다. dll이나 ocx 또는 다른 cab화일을 통해 새로운 CAB화일을 만들 수 있습니다. CAB화일은 다운로드를 위해 압축을 하는 일종의 압축포맷입니다.

    1. CAB 파일 생성방법

    Usage: CABARC [options] command cabfile [@list] [files] [dest_dir]
     기본 예> cabarc -s 6144 N my.cab my1.ocx my2.ocx

    1. 하나의 파일을 Cab 파일로 생성
        CabArc n my.cab my.ocx

    2. 적은수의 파일을 Cab 파일로 생성
       - 3개의 파일(my.ocx, my2.ocx, my.inf)로 Cab 파일 생성
        Cabarc n my.cab my1.ocx my2.ocx my.inf

    3. 많은수의 파일을 Cab 파일로 생성
       - 파일들을 하나의 하위 디렉토리(예:app)에 넣고 바로 위 디렉토리에서 다음의 명령을 이용한다.
        Cabarc r ?p my.cab app\*.*

    2. Cabarc 옵션리스트

    1. Command
      L Cabinet(CAB) 파일의 목록 보기 (예: CabArc l my.cab)
      N 새로운 cabinet 파일 생성 (예: CabArc n my.cab *.dll *.ocx)
      X Cabinet 파일로부터 파일 꺼내기 (예: CabArc x my.cab my.ocx)

    2. Options
      -c 작업할 파일 확인하기
      -o 파일을 꺼낼 때, 사용자에게 묻지 않고 덮어쓰기
      -m 압축 형태 지정 [LZX:<15..21>|MSZIP|NONE], (기본 형태는 MSZIP)
      -p 파일명에 파일 경로 포함하기 (단, 상대 경로만 허용)
      -P 파일 포함 시 지정된 접두어 생략하기 (주로, 파일 경로의 일부가 지정됨)
      -r 하위 디렉토리의 파일까지 포함하기 (주로, -p 옵션과 함께 사용)
      -s Cabinet 파일 내에 사인 정보를 둘 여유 공간 확보 (예: -s 6144 => 6K bytes)
      -I Cabinet 생성시 'Cabinet Set ID' 지정 (기본 아이디는


    출처 : http://www.certkorea.co.kr/doc.asp?g_dev_cabarc

    Posted by SB패밀리