Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

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

    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, 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.

    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.

    What is Reference counting in COM?

    Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time is it created; the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted. Care must be exercised to prevent a context switch from changing the reference count at the time of deletion.

    How can we use .NET components in COM?Twist: What is CCW (COM callable wrapper)? Twist: How do we ensure that .NET component is compatible with COM?

    .NET components can not be used in straight forward way with COM. You will need to create CCW in order that COM components communicate with .NET assemblies. Other way to create CCW is by using InteropServices attributes. Here interfaces are created automatically. Following are different types of attributes: -None: No class interface is generated for the class. This is default setting when you do not specify anything. -AutoDispatch: Interface that supports IDispatch is created for the class. However, no type information is produced. -AutoDual: A dual interface is created for the class. Type information is produced and made available in the type library. Below in the source code we have used the third attribute. Imports System.Runtime.InteropServices _ Public Class ClsCompliant End Class Other than class attributes defined up there are other attributes with which you can govern other part of assembly. Example “GuidAttribute” allows you to specify the GUID, “ComVisibleAttribute” can be used to hide .NET types from COM etc. -Once .NET assembly is created using either interface or using Interopservices method we need to create a COM type library using Type library export tool [Tlbexp (AssemblyName)] -The final thing is registering the CCW in registry using regasm tool. Regasm AssemblyName[Options] and that's it.

    How can we use COM Components in .NET? Twist: What is RCW?

    Dot NET components communicate with COM using RCW (Runtime Callable Wrapper). Following are the ways with which you can generate RCW: -Adding reference in Visual Studio.net -Using Type library import tool. Tlbimp.exe yourname.dll -Using interopservices.System.runtime. Interopservices namespace contains class TypeLib Converter which provides methods to convert COM classes and interface in to assembly metadata. -Make your custom wrappers. If your COM component does not have type library then the only way to communicate is writing custom wrappers. That means communicating directly with COM components.

    What is CODE Access security?

    To help protect computer systems from malicious mobile code, to allow code from unknown origins to run with protection, and to help prevent trusted code from intentionally or accidentally compromising security, the .NET Framework provides a security mechanism called code access security. Code access security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code access security also enforces the varying levels of trust on code, which minimizes the amount of code that must be fully trusted in order to run. Using code access security can reduce the likelihood that your code can be misused by malicious or error-filled code. It can reduce your liability because you can specify the set of operations your code should be allowed to perform as well as the operations your code should never be allowed to perform. Code access security can also help minimize the damage that can result from security vulnerabilities in your code.

    All managed code that targets the common language runtime receives the benefits of code access security, even if that code does not make a single code access security call.

    What'is difference between System exceptions and Application exceptions?

    From the System.SystemException documentation:

    This class is provided as a means to differentiate between exceptions defined by the system versus exceptions defined by applications.

    So, consider it the opposite of ApplicationException. All Exceptions that are defined by the .NET Framework inherit from SystemException. All Exceptions that are defined by code that you write should derive from ApplicationException. Exception is the root class of ALL exceptions.

    Friday, June 27, 2008

    What is the difference between VB.NET and C# ?

    Well this is the most debatable issue in .NET community and people treat these languages like religion. It’s a subjective matter which language is best. Some like VB.NET’s natural style and some like professional and terse C# syntaxes. Both use the same framework and speed is also very much equivalents.
    But still let’s list down some major differences between them
    :-Advantages VB.NET :-Has support for optional parameters which makes COM interoperability much easy. With Option Strict off late binding is supported. Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace. Has the WITH construct which is not in C#. The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger. Advantages of C# XML documentation is generated from source code but this is now been incorporated in Whidbey. Operator overloading which is not in current VB.NET but is been introduced in Whidbey. Use of this statement makes unmanaged resource disposal simple. Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).
    This is the major difference that you can access unmanaged code in C# and not in VB.NET.

    What is concept of Boxing and Unboxing ?

    Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type. Boxing is a process in which object instances are created and copy values in to that instance. Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location. Below is sample code of boxing and unboxing where integer data type is converted in to object and then vice versa.

    Dim x As IntegerDim y As Object x = 10‘ boxing process y = x‘ unboxing process x = y

    What are Value types and Reference types ?

    Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure. Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable. All types are derived from the System.Object base type.