Load document in iframe dynamically

Published 03/11/2005 by Henry in ASP.NET | C#
Tags: ,

Supose you need to show an xml, html or aspx document inside an ASP.NET page. So you actually want to embed another page or document inside the original page. You want to load a document in an iframe dynamically from the server-side.
What you really need is an iFrame server control. However an iFrame is an html control and it's properties are not directly available at the server side (in the codebehind). So we need a way to access the 'src' property of the iFrame directly. Inside the iFrame's tag in the html of the aspx page we set the 'runat' attribute with the 'server' value.

   1:  <iframe id ="MyIframe" runat ="server"> 
   2:  </iframe> 

In the aspx.cs (codebehind) file we declare a System.Web.UI.HtmlGenericControl and name it (the name does not have to be the same as in the html page, but I think it is good practice to do so).

   1:  protected System.Web.UI.HtmlControls.HtmlGenericControl MyIframe;

We create a method we can call in order to load a document in our iFrame by using the FindControl method of the System.Web.UI.Page and typecast it This way we can acces all properties of the HtmlControl through the Attributes property. The "MyIframe" referred in Find Control is the ID as declared in the ASPX Page.

   1:  private void LoadDocumentInIFrame(string url)
   2:  { 
   3:      HtmlControl MyIframe = (HtmlControl)this.FindControl("MyIframe"); 
   4:      MyIframe.Attributes["width"] = "100%"; 
   5:      MyIframe.Attributes["height"] = "400px"; 
   6:      MyIframe.Attributes["src"] = url; 
   7:  }
   8:   
   9:   
  10:  // Example that calls the method
  11:  LoadDocumentInIFrame("http://www.google.com")


This way we can load a document in an iframe dynamically from server-side.
With the FindControl() we can get a reference to the HtmlGenericControl object and access the properties of it. As you will understand this is not limited only to the iFrame, but can be used for more 'HTML' controls.

Henry Cordes
My thoughts exactly...

 


.NET Framework version...

Published 19/10/2005 by Henry in ASP.NET
Tags:

I started working on a new project, the project runs on version 1.0 of the .NET Framework, on my development machine version 1.1 of the .NET Framework also is installed. Now the project gives exeptions becasue IIS runs it on the 1.1 Framework.

This is why I had to solve the following problem:
How do you tell one Web application to use the new version and the others to use the previous version?

The simple answer is to use the ASP.NET IIS Registration Tool, which is included with each version of the .NET Framework and usually is located at <WinDir>Microsoft.NETFramework<version>aspnet_regiis.exe.

In the case of an .aspx page, IIS loads the ASP.NET ISAPI extension (aspnet_isapi.dll) and passes it the request. The ASP.NET ISAPI extension then passes the request to the ASP.NET worker process, aspnet_wp.exe. Each version of the .NET Framework installs its own version of aspnet_isapi.dll and aspnet_wp.exe, how does IIS know which one to invoke for any particular .aspx page? You can find the answer in the IIS management console, located under the Administrative Tools section of the Control Panel.

To determine which version of ASP.NET is being used, open the IIS management console, right-click on the virtual directory or Web site, and select Properties. On the Directory or Home Directory tab, click on the Configuration button.
As shown in Figure 1, you should be on the Mappings tab, which displays a list of file extensions and the path to the corresponding CGI executable or ISAPI extension. The key here is to see which version of the ASP.NET ISAPI extension is being invoked for .aspx pages. For version 1.0 it should be <WinDir>Microsoft.NETFrameworkv1.0.3705aspnet_isapi.dll; for version 1.1 it should be <WinDir>Microsoft.NETFrameworkv1.1.4322 aspnet_isapi.dll.

ASP.NET Version 1.1
Version 1.1.4322

It now is possible to change this by selecting al extensions that use the .NET framework and click "Edit" to re- map the executable path for all the ASP.NET extensions to <WinDir>Microsoft.NETFrameworkv1.1.4322aspnet_isapi.dll., but what if you need to do this more often or have many websites to cover?
Using the IIS Registration Tool is straightforward. It has several options that let you install and uninstall not only the extension mappings but also the JavaScript files that perform client-side validation. You can do this for a virtual directory, an entire Web site, or all ASP.NET applications on the machine. Using the previous example, you can force the NewVersion Web application to use ASP.NET 1.1, by using this syntax:

aspnet_regiis -s W3SVC/1/ROOT/NewVersion

Watch out for a couple of possible pitfalls here. One thing to remember is your command prompt must be in the <WinDir>Microsoft.NETFrameworkv1.1.4322 directory; otherwise, there's no telling which version will be executed. The other thing to remember is the path to the virtual directory might not always begin with W3SVC/1/.
determine the path for the Web site you're working with. It is possible to do this by going to the Web site's Properties dialog and on the Web Site tab clicking the Properties button in the logging section. You should see the Log File Name at the bottom of the General Properties tab. This is the path you should use, minus the actual filename itself.

Logdirectory IIS

Another handy option for this tool is to view all the applications that are mapped to ASP.NET and which version they are mapped to. This is also another way to find the path name for the Web site. For this option, use this syntax:

aspnet_regiis -lk

This syntax will display something like this:

W3SVC/ 1.1.4322.0
W3SVC/1/ROOT/ 1.1.4322.0
W3SVC/1/ROOT/OldVersion/ 1.0.3705.288
W3SVC/1/ROOT/NewVersion/ 1.1.4322.0

Henry Cordes
My thoughts exactly...


ASP.NET 2.0 update

Published 27/09/2005 by Henry in ASP.NET
Tags:

Through this link you can find a lot of information about ASP.NET 2.0:

http://msdn.microsoft.com/asp.net/beta2/faq/default.aspx

Henry Cordes
My thoughts exactly...


Data Access Application Block (EntLib)

Published 22/09/2005 by Henry in EntLib
Tags:

When I first started working with the Enterprise Library, I found it hard to find information about how to use it. I even heard a story about a developing-team that decided not to use it because they could not figure out fast enough how to use it.
So I will try to make some sort of Data Access Application Block walkthrough and hope this will make it easier for people to start using the Enterprise Library.

Consuming app
Suppose we got a webapplication with one page. We are going to use the Northwind database. In the Northwind database there is a stored procedure called:
CustOrdersOrders
which needs the parameter:
@CustomerID nvarchar(5).

On the page in our webapp we got a Datagrid. In this grid we want to show the data that the stored procedure returns.
We are going to use the Data Access Application Block for access to the database.

Web Application
First we create a web Application. The language I use is C#. I renamed the WebForm1.aspx to Default.aspx and put a datagrid on the page and named it dGrid, I left 'Auto Generate Columns' checked. Enterprise Library Configuration (Tool) Next we open the Enterprise Library Configuration Tool, we click on ‘File’ > ‘Open Application” or click the ‘Open’ icon.

Open application 
Open Existing Application

Browse to the directory where the web.config of the Web Application is located selected it and click on ‘Open’. Now we see the following:

New application 
New Application

You can rename the ‘Application’ node, I named it ‘WebAppEntLib’. You right-click the ‘Application’ node and choose ‘New’ > ‘Data Access Application Block’.

New dataaccesappblock 

As you see the DAAB (Data Access Application Block) is installed (with the Configuration Application Block).

New DAAB
New DAAB

Configuration Application Block
The ‘Configuration Application Block’ is installed with the Data Access Application Block and is used to store the information about which method is used to store the config information (XML File) and where this XML based dataacces config file can be found. By chancing the ‘FileName’ under ‘XML File Storage Provider’ under the ‘dataConfiguration’ node in the name with a directory name before the name (\dataConfiguration.config) you can control where the config file will be stored. If you don’t do this the file will be in the same directory as the web.config or app.config file.

Data Access Application Block
With the Configuration Tool we make the configuration settings needed to make the Data Acces Block work for us. Database Types With this node it is possible to define other database types (Oracle, MySql etc.). With the Enterprise Library the Oracle database type is included and can easily be chosen.

Oracle db
Oracle database

Sql Connection String
With the Sql Connection String node the connectionstring used to connect to the database can be defined.
Default the following nodes are provided, we use the following values:

  • Database - ‘Northwind’
  • Integrated Security - ‘False’
  • Server - ‘(local)’

We also need the nodes (with the following values):

  • Uid (userid) - ‘developer’
  • Pwd (Password) - ‘developer’

Through a right click and choosing the menu’s new > ‘parameter’ and supplying as name ‘uid’ with the Value the username we need to connect to our database (in our case ‘developer’).
And once more with New > Password parameter we supply ‘pwd’ as Name and in our case ‘developer’ as password (by clicking the ellipse).
We also change the default node name ‘SQL Connection String’ into ‘Northwind Connection String’ by right clicking the node name and choosing ‘Rename’.

Database Instances
With the Database Instances node we define database instances. A great benefit from the Data Access Application Block is that it is relatively easy to make an application communicate with multiple databases. We define which Connectionstring, Database Type and Name of the Database we are going to use through this node.

  • Connectionstring node - ‘Northwind Connection String’ (dropdown)
  • DatabaseTypeNode - ‘Sql Server’ (dropdown) Name - ‘Northwind’

choose databasetypenode 

We save this settings with File > Save Application or through the disk icon. All settings now are written in the dataconfiguration.config file <P align=left>We save this settings with File &gt; Save Application or through the disk icon.<BR>All settings now are written in the dataconfiguration.config file.<BR></P>

Example (NOT COMPLETE):

<dataConfiguration>
 <xmlSerializerSectiontype="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<enterpriseLibrary.databaseSettingsxmlns:xsd=http://www.w3.org/2001/XMLSchemaxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancedefaultInstance="Northwind" xmlns="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/data">
  <databaseTypes>
    <databaseTypename="Sql Server"type="Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase, Microsoft.Practices.EnterpriseLibrary.Data, Version=1.0.0.0,   Culture=neutral, PublicKeyToken=null"/>
  </databaseTypes>
  <instances>
    <instancename="Northwind"type="Sql Server"connectionString="Northwind Connection String"/>
  </instances>
  <connectionStrings>
    <connectionStringname="Northwind Connection String">
    <parameters>
      <parametername="database"value="Northwind"isSensitive="false"/>
      <parametername="Integrated Security"value="False"isSensitive="false"/>
      <parametername="uid"value="developer"isSensitive="false"/>
      <parametername="pwd"value="developer"isSensitive="true"/> <parametername="server"value="(local)"isSensitive="false"/>
    </parameters>
    </connectionString>
  </connectionStrings>
  </enterpriseLibrary.databaseSettings>
 </xmlSerializerSection>
</dataConfiguration>



In Visual Studio we highlight our project and select Project > Add Reference. On the .NET tab, we use "Browse..." to locate and set references to the following dll's:

 

  • Microsoft.Practices.EnterpriseLibrary.Configuration
  • Microsoft.Practices.EnterpriseLibrary.Data

Now we open the code-behind file for our startingpage: default.aspx.cs and add the following directives:

using Microsoft.Practices.EnterpriseLibrary.Data;using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

In default.aspx code-behind we create the method BindDataFromDAAB(), which we call in the Page_Load() 

   1:  private void BindDataFromDAAB()
   2:  { 
   3:      DataRow dataRow; 
   4:      
   5:      DataTable dataTable = new DataTable(); 
   6:      dataTable.Columns.Add(new DataColumn("OrderID", typeof(Int32))); 
   7:      dataTable.Columns.Add(new DataColumn("OrderDate", typeof(DateTime))); 
   8:      dataTable.Columns.Add(new DataColumn("RequiredDate", typeof(DateTime))); 
   9:      dataTable.Columns.Add(new DataColumn("ShippedDate", typeof(DateTime))); 
  10:      
  11:      //Create a database object 
  12:      Database dataBase = DatabaseFactory.CreateDatabase(); 
  13:      //In case of multiple databases 
  14:      //Database dataBase=DatabaseFactory.CreateDatabase("Northwind"); 
  15:      
  16:      //Create command wrappers to specify parameters 
  17:      DBCommandWrapper dbCommandWrapper = dataBase.GetStoredProcCommandWrapper("CustOrdersOrders"); 
  18:      //Fill parameter 
  19:      dbCommandWrapper.AddInParameter("@CustomerID", DbType.String,"BOTTM"); 
  20:      
  21:      using (IDataReader dataReader = dataBase.ExecuteReader(dbCommandWrapper))
  22:      { 
  23:          while (dataReader.Read())
  24:          { 
  25:              dataRow = dataTable.NewRow(); 
  26:              // 0 
  27:              OrderID, string dataRow[0] = dataReader.Int32(0); 
  28:              // 1 
  29:              OrderDate, datetime dataRow[1] = dataReader.GetDateTime(1); 
  30:              // 2 
  31:              RequiredDate, datetime dataRow[2] = dataReader.GetDateTime(2); 
  32:              // 3 
  33:              ShippedDate, datetime dataRow[3] = dataReader.GetDateTime(3); 
  34:              dataTable.Rows.Add(dataRow); 
  35:          } 
  36:          dataReader.Close(); 
  37:      } 
  38:      dGrid.DataSource = dataTable; 
  39:      dGrid.DataBind();
  40:  }


This code is pretty unreusable, but I think it gets the point across.
In the real world you could make a dataacces class to do all the database related stuff, a class Orders in which all the Orders related stuff would be. So you would not have all the data and business logic in the webpage code-behind. 


Henry Cordes 
My thoughts exactly... 

SQL Server and Dynamic SQL

Published 20/08/2005 by Henry in SQL
Tags:
HTML Source EditorWord wrap

'EXEC()', 'sp_executesql' and 'EXEC('EXEC sp_executesql ...')'

There are two ways to invoke dynamic SQL in MS SQL Server, 'EXEC()' and 'sp_executesql'. And you can use a combination of the two 'EXEC('EXEC sp_executesql ...')'.
EXEC() is the most simple, as illustrated by this example:

   1:  SELECT @table = 'sales' EXEC('SELECT * FROM ' + @table) 

The permissions of the current user always apply, even if the statement appears in a stored procedure. 'EXEC(''')' is similar to the EXEC of a stored procedure. But rather than calling a stored procedure, you invoke a batch of single SQL statements.

sp_executesql has the advantage that it allows you to pass parameters to the dynamic query, both for input and output.
Here is an example with an output parameter:

   1:  DECLARE @sql nvarchar(4000) -- nvarchar(MAX) on SQL 2005. DECLARE @col sysname 
   2:  DECLARE @min varchar(20) 
   3:  SELECT @col = N'au_fname' 
   4:  SELECT @sql = N'SELECT @min = convert(varchar(20), MIN(' + @col + N')) FROM authors' 
   5:  EXEC sp_executesql @sql, N'@min varchar(20) OUTPUT', @min OUTPUT SELECT @min 

Thus, you can much easier get a value from your dynamic SQL statement into a local variable than with EXEC().

These points apply to EXEC() and sp_executesql as well:

  • The SQL code is it in own scope, and you have no access to the variables in the calling stored procedure;
  • The permissions of the actual user apply;
  • Any USE statement will not affect the calling stored procedure;
  • Temp tables created in the SQL batch will not be available to the calling procedure;
  • SET statements only affects the SQL batch, not the caller;
  • Termination of the batch executed by sp_executesql terminates the calling procedure too;
  • @@error reports the status of the last statement in the dynamic SQL code;
  • According to Books Online the return value from sp_executesql is either 0 for success or 1 for failure. However it appears that the return value is the final value of @@error, at least in SQL 2000.

EXEC('EXEC sp_executesql ....
By using 'EXEC('EXEC sp_executesql ....' it is possible to use statement parameters with the dynamic query string. The sql query must be in unicode string , in nvarchar the MAX characters is 4000. By using EXEC('EXEC sp_executesql ...., multiple parameters can be concatenated, which results in the possibility to use more than 4000 characters in the dynamic query (the point with dynamic ofcourse is that you can not be sure what length the query will be).

Example:

   1:  DECLARE @query nvarchar(4000)
   2:  DECLARE @@queryDynamic nvarchar(4000)
   3:  DECLARE @l_Startdate datetimeDECLARE @l_Enddate datetimeDECLARE @dbName varchar(50)
   4:  DECLARE @dbName2 varchar(50)
   5:   
   6:  SET @dbName = '[SQLServer_instance].[Databasename]'
   7:  SET @dbName2 = '[SQLServer_instance2].[Databasename2]' 
   8:  SET @query = 'SELECT * FROM ' + @dbName + '.dbo.tblTable ' + 'WHERE startDate >= @pl_Startdate AND Enddate < @pl_Enddate '
   9:  SET @@queryDynamic = 'UNION ' + 'SELECT * FROM ' + @dbName2 + '.dbo.tblTable ' + 'WHERE startDate >= @pl_Startdate AND Enddate < @pl_Enddate ' 
  10:   
  11:  EXEC('EXEC sp_executesql N''' + @query + @queryDynamic + ''', N''@pl_Startdate datetime ,
 12:                              @pl_Enddate datetime'', @pl_Startdate = ''' + @l_Startdate + ''', @pl_Enddate = ''' + @l_Enddate + '''')


Henry Cordes
My thoughts exactly...