Showing posts with label ASP. Show all posts
Showing posts with label ASP. Show all posts

Friday, May 28, 2010

Extensible Request Validation

ASP.NET request validation searches incoming HTTP request data for strings that are commonly used in cross-site scripting (XSS) attacks. If potential XSS strings are found, request validation flags the suspect string and returns an error. The built-in request validation returns an error only when it finds the most common strings used in XSS attacks. Previous attempts to make the XSS validation more aggressive resulted in too many false positives. However, customers might want request validation that is more aggressive, or conversely might want to intentionally relax XSS checks for specific pages or for specific types of requests.

In ASP.NET 4, the request validation feature has been made extensible so that you can use custom request-validation logic. To extend request validation, you create a class that derives from the new System.Web.Util.RequestValidator type, and you configure the application (in the httpRuntime section of the Web.config file) to use the custom type. The following example shows how to configure a custom request-validation class:

<httpRuntime requestValidationType="Samples.MyValidator, Samples" />



The new requestValidationType attribute requires a standard .NET Framework type identifier string that specifies the class that provides custom request validation. For each request, ASP.NET invokes the custom type to process each piece of incoming HTTP request data. The incoming URL, all the HTTP headers (both cookies and custom headers), and the entity body are all available for inspection by a custom request validation class like that shown in the following example:



public class CustomRequestValidation : RequestValidator
{
protected override bool IsValidRequestString(
HttpContext context, string value,
RequestValidationSource requestValidationSource,
string collectionKey,
out int validationFailureIndex)
{...}
}

For cases where you do not want to inspect a piece of incoming HTTP data, the request-validation class can fall back to let the ASP.NET default request validation run by simply calling base.IsValidRequestString.

Expanding the Range of Allowable URLs

ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters, based on the NTFS file-path limit. In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications, using two new httpRuntime configuration attributes. The following example shows these new attributes.

<httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" />




To allow longer or shorter paths (the portion of the URL that does not include protocol, server name, and query string), modify the maxRequestPathLength attribute. To allow longer or shorter query strings, modify the value of the maxQueryStringLength attribute.



ASP.NET 4 also enables you to configure the characters that are used by the URL character check. When ASP.NET finds an invalid character in the path portion of a URL, it rejects the request and issues an HTTP 400 error. In previous versions of ASP.NET, the URL character checks were limited to a fixed set of characters. In ASP.NET 4, you can customize the set of valid characters using the new requestPathInvalidChars attribute of the httpRuntime configuration element, as shown in the following example:



 



<httpRuntime requestPathInvalidChars="&lt;,&gt;,*,%,&amp;,:,\,?"  />




By default, the requestPathInvalidChars attribute defines eight characters as invalid. (In the string that is assigned to requestPathInvalidChars by default, the less than (<), greater than (>), and ampersand (&) characters are encoded, because the Web.config file is an XML file.) You can customize the set of invalid characters as needed.

Permanently Redirecting a Page

It is common practice in Web applications to move pages and other content around over time, which can lead to an accumulation of stale links in search engines. In ASP.NET, developers have traditionally handled requests to old URLs by using by using the Response.Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example:

RedirectPermanent("/newpath/foroldcontent.aspx");

ViewStateMode in ASP.Net 4.0

 

When asp.net introduced the concept of viewstate, it changed the way how developers maintain the state for the controls in a web page. Until then to keep the track of the control(in classic asp), it was the developer responsibility to manually assign the posted content before rendering the control again. Viewstate made allowed the developer to do it with ease. The developers are not bothered about how controls keep there state on post back.

Viewstate is rendered to the browser as a hidden variable __viewstate. Since viewstate stores the values of all controls, as the number of controls in the page increases, the content of viewstate grows large. It causes some websites to load slowly.

As developers we need viewstate, but actually we do not want this for all the controls in the page. Till asp.net 3.5, if viewstate is disabled from web.config (using <pages viewstate=”false”/> ..</pages>), then you can not enable it from the control level/page level. Both <%@ Page EnableViewState=”true”…. and <asp:textbox EnableViewState=”true” will not work in this case.

Lot of developers demands for more control over viewstate. It will be useful if the developers are able to disable it for the entire page and enable it for only those controls that needed viewstate. With ASP.NET 4.0, this is possible, a happy news for the developers. This is achieved by introducing a new property called ViewStateMode.

Let us see, What is ViewStateMode – Is a new property in asp.net 4.0, that allows developers to enable viewstate for individual control even if the parent has disabled it. This ViewStateMode property can contain either of three values

  1. Enabled- Enable view state for the control even if the parent control has view state disabled.
  2. Disabled - Disable view state for this control even if the parent control has view state enabled
  3. Inherit - Inherit the value of ViewStateMode from the parent, this is the default value.

To disable view state for a page and to enable it for a specific control on the page, you can set the EnableViewState property of the page to true, then set the ViewStateMode property of the page to Disabled, and then set the ViewStateMode property of the control to Enabled.

Find the example below.

Page directive - <%@ Page Language="C#"  EnableViewState="True" ViewStateMode="Disabled" .......... %>

Code for the control  - <asp:TextBox runat="server" ViewStateMode="Enabled" ............../>

Now the viewstate will be disabled for the whole page, but enabled for the TextBox.

ViewStateMode gives developers more control over the viewstate.

Thursday, November 19, 2009

How to check if Silverlight Running out of browser or in the browser ?

As Silverlight increases its Out of Browser features it will become more important to detect if the application is running in or out of the browser.  This is the check:

if (Application.Current.IsRunningOutOfBrowser)
{
// Out of Browser

}
else

{
// in the browser

}

Monday, October 12, 2009

How To Export Data in a DataGrid on an ASP . NET WebForm to Microsoft Excel

  • Start Visual Studio .NET. On the File menu, point to New, and then click Project.
  • In the Project Types pane, click Visual Basic Projects. Under Templates, click ASP.NET Web Application. Name the application ExcelExport and then click OK.
    WebForm1 appears in Design view for you.
  • In Solution Explorer, right-click WebForm1.aspx and then click Rename. Change the name of the file to Bottom.aspx.
  • On the View menu, click HTML Source to add the following DataGrid between the < form > and < / form > tags:

    <asp:datagrid id="DataGrid1" runat="server" GridLines="Vertical" CellPadding="3" BackColor="White" BorderColor="#999999" BorderWidth="1px" BorderStyle="None" Width="100%" Height="100%" Font-Size="X-Small" Font-Names="Verdana"> <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C"></SelectedItemStyle> <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle> <ItemStyle BorderWidth="2px" ForeColor="Black" BorderStyle="Solid" BorderColor="Black" BackColor="#EEEEEE"></ItemStyle> <HeaderStyle Font-Bold="True" HorizontalAlign="Center" BorderWidth="2px" ForeColor="White" BorderStyle="Solid" BorderColor="Black" BackColor="#000084"></HeaderStyle> <FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle> <PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999" Mode="NumericPages"></PagerStyle> </asp:datagrid>

  • On the View menu, click Design to return to design view.
    The DataGrid appears on the WebForm.
  • On the View menu, click Code to display the code behind the Web Form. Add the following code to the Page_Load event handler:

    Note You must change User ID <username> and password=<strong password> to the correct values before you run this code. Make sure that the user account has the correct permissions to perform this operation on the database.


    ' Create a connection and open it. Dim objConn As New System.Data.SqlClient.SqlConnection("User ID=<username>;Password=<strong password>;Initial Catalog=Northwind;Data Source=SQLServer;") objConn.Open() Dim strSQL As String Dim objDataset As New DataSet() Dim objAdapter As New System.Data.SqlClient.SqlDataAdapter() ' Get all the customers from the USA. strSQL = "Select * from customers where country='USA'" objAdapter.SelectCommand = New System.Data.SqlClient.SqlCommand(strSQL, objConn) ' Fill the dataset. objAdapter.Fill(objDataset) ' Create a new view. Dim oView As New DataView(objDataset.Tables(0)) ' Set up the data grid and bind the data. DataGrid1.DataSource = oView DataGrid1.DataBind() ' Verify if the page is to be displayed in Excel. If Request.QueryString("bExcel") = "1" Then ' Set the content type to Excel. Response.ContentType = "application/vnd.ms-excel" ' Remove the charset from the Content-Type header. Response.Charset = "" ' Turn off the view state. Me.EnableViewState = False
    Dim tw As New System.IO.StringWriter() Dim hw As New System.Web.UI.HtmlTextWriter(tw) ' Get the HTML for the control. DataGrid1.RenderControl(hw) ' Write the HTML back to the browser. Response.Write(tw.ToString()) ' End the response. Response.End()
    End If




  • NOTE: Replace SQLServer in the code with the name of your SQL Server. If you do not have access to a SQL Server that contains the Northwind sample database, modify the connection string to use the Microsoft Access 2002 sample Northwind database:

    provider=microsoft.jet.oledb.4.0; data source=C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb

    If you select this method, modify the aforementioned code to use the OleDbClient namespace rather than the SqlClient namespace.

  • On the Project menu, click Add HTML Page. Name the page Top.htm and then click Open.
    Top.htm appears in Design view.
  • On the View menu, click HTML Source. Replace the contents of the HTML source window with the following code:

    <html> <script language="vbscript"> Sub Button1_onclick Select Case Select1.selectedIndex Case 0 ' Use Automation. Dim sHTML sHTML = window.parent.frames("bottom").document.forms(0).children("DataGrid1").outerhtml Dim oXL, oBook Set oXL = CreateObject("Excel.Application") Set oBook = oXL.Workbooks.Add oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = sHTML oBook.HTMLProject.RefreshDocument oXL.Visible = true oXL.UserControl = true Case 1 ' Use MIME Type (In a New Window). window.open("bottom.aspx?bExcel=1") Case 2 ' Use MIME Type (In the Frame). window.parent.frames("bottom").navigate "bottom.aspx?bExcel=1" End Select End Sub </script> <body> Export to Excel Using: <SELECT id="Select1" size="1" name="Select1"> <OPTION value="0" selected>Automation</OPTION> <OPTION value="1">MIME Type (In a New Window)</OPTION> <OPTION value="2">MIME Type (In the Frame)</OPTION> </SELECT> <INPUT id="Button1" type="button" value="Go!" name="Button1"> </body> </html>

  • On the Project menu, click Add HTML Page. Name the page Frameset.htm and then click Open.
    Frameset.htm opens in Design view.
  • On the View menu, click HTML Source. Replace the contents of the HTML source window with the following code:

    <html> <frameset rows="10%,90%"> <frame noresize="0" scrolling="no" name="top" src="top.htm"> <frame noresize="0" scrolling="yes" name="bottom" src="bottom.aspx"> </frameset> </html>

  • In Solution Explorer, right-click Frameset.htm and then click Set As Start Page.
  • On the Build menu, click Build Solution.
  • On the Debug menu, click Start Without Debugging to run the application.
    After the frameset opens in the Web browser, the DataGrid in the bottom frame displays the data from the Northwind database.
  • In the drop-down list, click Automation, and then click Go.
    The DataGrid contents are displayed outside the browser in the Microsoft Excel application window.
  • In the drop-down list, click MIME Type (In a New Window), and then click Go.
    The DataGrid contents are displayed in Excel hosted in a new Web browser window.
    NOTE: If you receive a prompt to open or save the Excel file, click Open.
  • In the drop-down list, click MIME Type (In the Frame) and then click Go.
    The DataGrid contents are displayed in the bottom frame of the frameset in Excel hosted in the Web browser.
    NOTE: If you receive a prompt to open or save the Excel file, click Open.

    enjoy……………………..

  • Friday, October 9, 2009

    Why do ASP.NET control events fire more than once?

    I’ve always wondered about this and here is the answer:

    ASP.NET controls recreates their hierarchy (at a minimum) twice during a single request to the server:

    1. First when the control is being restored to a it's previous state.
    2. Second when all the required modifications are applied.

    Wednesday, September 16, 2009

    Page not found using ASP.NET Development server

    When You create a web site and try to debug it visual studio opens the browser at a different port than the development server runs at. When You try to run any project you receive "Page not found" in browser opened by ASP.NET Development server.

    here is its fix,

    as u have Eset nod32 antivirus v3.0.621 (same as me) , the problem is from this AV that dont allow connections to be made to Visual Studio ASP.NET Server .

    now follow these steps to solve this issue:

    1.DoubleClick on Nod32 icon on tray and Open it up.
    2.if it is not in "Advanced Mode" , switch to Advanced Mode. ( you can do it by clicking on the bottom-left link "Display:Standard Mode" and then click on "Toggle Advanced Mode" )
    3.then goto SETUP section. then on the Right Pane click on "Antivirus and Antispyware protection". the panel should be opened.
    4.now in the "Web Access protection" click on "Configure..."
    5.from the left Tree go to path : "Web access protection > HTTP > Web Browsers"
    6.now you should see visual studio 8 "devenv.exe" in the list .
    7.click on it twice till you see a cross sign in the box. ( Note on CROSS sign , not mark sign ! )
    8.with this cross sign you tell the Nod32 that this program should not be scanned and filtered for web access.
    due to this steps , my problem solved and now i can access my page from localhost: .

    Friday, May 29, 2009

    How to Create A Sliding Panel with Jquery

    We are going to show you a series of how to articles to create some jQuery effects with JavaScript in your web designs. In case you don’t know what jQeury is, it’s a JavaScript Library. It has heaps of Ajax and JavaScript components that will let you enhance your web design and the users experience on your site.

    First you need to grab a copy of jQuery Grab the latest released mini(compressed) version.

    How to get the elements you need.

    Creating jQuery Functions is relatively easy thank to the great documentation. The main thing you have to know is how to get the exact element that you want to apply the effects to.

    Example :


    * $(”#header”) = get the element with id=”header”
    * $(”h3″) = get all <h3> element
    * $(”div#content .photo”) = get all element with class=”photo” nested in the <div id=”content”>
    * $(”ul li”) = get all <li> element nested in all <ul>
    * $(”ul li:first”) = get only the first <li> element of the <ul>

    So with that in mind we are going to create our first jQuery effect. The commonly seen sliding panel, where you click a button and a panel slides up or down. Create a html document and call in the JavaScript file between the <head> tags along with you css file for styling. Then create two divs, one big one called <div id=”panel”></div> for the pannel and <div class=”btn-slide”></div> for the button. Style as you wish.

    Then call is javascript into your page either inline, or by an external .js file.






    When any element with in your html file is clicked, it will toggle the slide up and down of the <div id=”panel”> element and then toggle a CSS class=”active” to the <a class=”btn-slide”> element. The .active class will toggle the background position of the arrow image (by CSS).

    Missing Dynamic Data Templates - VS 2008 SP1 and .NET 3.5 SP1

    In case you have installed the .NET 3.5 SP1 and Visual Studio 2008 SP1 and are unable to find the Dynamic Data Website Template, you can install the latest version of the runtime from here

    If you are unable to find the "Dynamic Data Website" Template than instead of fixing the issue by installing/uninstalling SP1 Bits again, it is better to install the latest bits of the Dynamic Data Runtime from CodePlex. this will install the template and the other advantage is that, you will also get the "Dynamic Data Website Wizard (Preview)" that allows you to configure a data driven website very quickly, by following the wizard steps.

    Happy Coding :-)

    ASP.Net Dynamic Data Web Site

    If your web site is heavily data driven then here is a quick and easy way for you to create one without writing much code. All you need is Visual Studio 2008 SP1 or Visual Web Developer 2008 Express SP1 installed on your box.

    Dynamic Data Web Sites makes use of a mechanism called Scaffolding. When Scaffolding is enabled it lets ASP.Net go through your data model and generate web pages for your tables. These generated pages have Insert, Delete and Update capabilities for each table.

    ASP.NET Dynamic Data Web Sites provides a framework that enables you to quickly build a functional data-driven application, based on a LINQ to SQL or Entity Framework data model. It also adds great flexibility and functionality to the DetailsView, FormView, GridView, and ListView controls in the form of smart validation and the ability to easily change the display of these controls using templates.

    ASP.NET Dynamic Data brings major usability and RAD development changes to the existing ASP.NET data controls. RAD development is significantly increased by the use of a rich scaffolding framework. After you add a LINQ to SQL or Entity Framework data model to a project, you can simply register it with Dynamic Data. The result is a fully functional Web site. Full CRUD (create, read, update, and delete) operations are supported. The site includes filtering by foreign keys and Boolean fields; foreign keys are automatically converted to their friendly names. Smart validation is automatically available, which provides validation based on database constraints for nullable fields, data type, and field length.

    The DetailsView and GridView controls have been extended to display fields by using templates instead of by using hard-coded rules that are programmed in the controls. These templates are part of the project, and you can customize them to change their appearance or to specify which controls they use for rendering. This makes it very easy to make a change in one place in your site that specifies how to present dates for editing, as one example. FormView and ListView controls can implement similar behavior by using a DynamicControl object in their templates and by specifying which field in the row to display. Dynamic Data will then automatically build the UI for these controls based on the templates that you specify.

    Validation is significantly improved in the controls as well. The controls read metadata for a LINQ to SQL or Entity Framework data model and provide automatic validation based on the model. For example, if a column in the database is limited to 50 characters, and if a column is marked as not nullable, a RequiredFieldValidator control is automatically enabled for the column. (The controls also automatically support data-model-level validation.) You can apply other metadata to take further control over display and validation.

    Here are some Links to start with :

    Getting Started with Dynamic Data

    Begin Modifying Dynamic Data Applications with URL Routing

    Begin Editing the Templates in ASP.NET Dynamic Data Applications

    Enable In-Line Editing in ASP.NET Dynamic Data Applications

    Or a blog post by Reshmi Mangalore at msdn blogs


    Try this today and have fun!

    Friday, March 27, 2009

    How to open Excel XLS file in C#.net

    Suppose you have an excel file that contains the data and you wish to use the same The following code snippet will read the file and return it in a dataset now you are free to use this dataset for your purpose.



    static DataSet readExcel()
    {
    string filename = "";
    string sheetname = "";
    filename = "";
    sheetname = "";
    OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0");
    con.Open();
    DataSet myDataSet = new DataSet();
    OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM ["+sheetname+"$]", con);
    myCommand.Fill(myDataSet);
    con.Close();
    return myDataSet;
    }

    Friday, November 14, 2008

    Error: ASPX page has not been pre-compiled, and cannot be requested

    Sometime we find that our web site was working perfectly on our development machine but start displaying error “ Error: ASPX page has not been pre-compiled, and cannot be requested” in many of forums I foud many of our peers are still struggling with same issue.

    The simple workaround for that I have found is :

    1. If you are using any 3rd party component , remove them from web.config, then using Add Reference add all reference to them again.
    2. Instead of setting the WDP's Output Assemblies property to “Merge all outputs to a single assembly” and deploy, use Publish Web Site under the Build menu.
    3. Check the "Allow this precompiled site to be updatable" check box in the Publish Web Site options of Visual Studio 05, and deploy.
    4. make sure you uploaded all the required assemblies. If anyone is missing upload that manually.

    Hope this information will be helpful to my peer community.

    Monday, September 15, 2008

    General network error. Check your network documentation.

    There is a lot of people out there complaining about SQL Server returning a General network error while executing a command form ADO.NET version 1.1 or 1.0. Since it is a General network error, it seems to me that there are as many reasons for this error as there are people having it. one fine day I too experienced the same so I googled it but saveral posts in several blogs leads to various solutions like append max pool size = 7500, to your connection string will solve the issue or setting the command timeout to anything but zero totally fixes it.

    I tried all of them but still i experienced the same error intermittently. Finally i found that The calling asp.net page creates an ojbect which opens the connection over and over and relies on the destruct method of the database object to do the closing so I am assuming our problem is related to this but I have not been able to reproduce it reliably so I can't be sure this is the cause of the problem.

    then i found this microsoft KB article

    it says that In the current design, after an application role is enabled on a client connection to SQL Server, you cannot reset the security context of that connection. Therefore, when the user ends the SQL Server session and disconnects from the server, the session is not reusable. However, OLE DB resource pooling returns the closed connection to the pool, and the error occurs when that connection is reused and the client application tries to reset the connection's security context by calling sp_setapprole again.

    WORKAROUND

    The only available workaround is to disable OLE DB Resource Pooling, which ADO uses by default. You can do this by adding "OLE DB Services = -2" to the ADO Connection string, as shown here: 'For SQLOLEDB provider
    'strConnect = "Provider=SQLOLEDB;server=SQL7Web;OLE DB Services = -2;uid=AppUser;pwd=AppUser;initial catalog=northwind"

    ' For MSDASQL provider
    'strConnect = "DSN=SQLNWind;UID=Test;PWD=Test; OLE DB Services= -2"


    Pooling can be disabled for the SQL Server .Net Data Provider by adding "Pooling=False" to the connection string.

    although that solves my issue but what if the connection pooling is needed ????

    Wednesday, July 2, 2008

    What is equivalent for regsvr32 exe in .NET?

    Regasm

    What are types of compatibility inVB6?

    There are three possible project compatibility settings: - No compatibility - Project compatibility - Binary compatibility No Compatibility With this setting, new class ID’s, new interface ID’s and a new type library ID will be generated by VB each time the ActiveX component project is compiled. This will cause any compiled client components to fail(with error 429!) and report a missing reference to the `VB ActiveX Test component’ when a client project is loaded in the VB IDE. Note: Use this setting to compile the initial release of a component to other developers. Project Compatibility With this setting, VB will generate new interface ID’s for classes whose interfaces have changed, but will not change the class ID’s or the type library ID. This will still cause any compiled client components to fail(with error 429!)but will not report a missing reference to the `VB ActiveX Test component’ when a client project is loaded in the VB IDE. Recompilation of client components will restore them to working order again. Note: Use this setting during the initial development and testing of a component within the IDE and before the component is released to other developers. Binary Compatibility VB makes it possible to extend an existing class or interface by adding new methods and properties etc. And yet still retain binary compatibility. It can do this, because it silently creates a new interface ID for the extended interface and adds registration code to register the original interface ID but with a new forward key containing the value of the new interface ID.COM will then substitute calls having the old ID with the new ID and hence applications built against the old interface will continue to work(assuming the inner workings of the component remain backward compatible!). With this settings, VB will not change any of the existing class, interface or type library ID’s, however in order that it can do so, VB requires the project to specify an existing compiled version that it can compare against to ensure that existing interfaces have not been broken.

    How do you do object pooling in .NET?

    COM+ reduces overhead by creating object from scratch. So in COM+ when object is activated from its pool and when it’s deactivated it’s pushed back to the pool. Objects pooling is configured by using the “ObjectPoolingAttribute” to the class.

    How to implement DTC in .NET?

    DTC is implemented using COM+. Following are the steps to implement COM+ in .NET: - “EnterpriseService” namespace has all the classes by which we can implement DTC in .NET. You have to add reference “EnterpriseService” namespace. - Your class must derive from “Service Component” object. - Then you have to define your class with the transaction attribute - After the class level transaction type is defined, its time to define at the method level the AutoComplete attribute. AutoComplete attribute says that if no exception is thrown then mark its part of the transaction as being okay. This helps cut down on the amount of code required. If the implementation sets AutoComplete to false, or omits it all together, then we would need to manage the transaction manually. To manually control the transaction you will need to use the ContextUtil class and its static members.

    How do we create DCOM objects in VB6?

    Using the Create Object method you can create a DCOM object. You have to put the server name in the registry.

    Can you describe IUKNOWN interface in short?

    Every COM object supports at least one interface, the IUnknown interface. All interfaces are classes derived from the base class IUnknown. Each interface supports methods access data and performs operations transparently to the programmer. For example, IUnknown supports three methods, AddRef, Release (), and QueryInterface(). Suppose that printerf is a pointer to an IUnknown. Printerf->;AddRef() increments the reference count. Printerf->;Release() decrements the reference count, deleting the object when the reference count reaches zero. Printerf->;QueryInterface(IDesired, pDesired) checks to see if the current interface (IUnknown) supports snother interface, IDesired, creates an instance (via a call to CoCreateInstance()) of the object if the reference count is zero (the object does not yet exist), and then calls pDesired->;AddRef() to increment the reference count (where pDesired is a pointer to IDesired) and returns the pointer to the caller.