Волгоградский государственный университет
Опубликован: 02.03.2009 | Доступ: свободный | Студентов: 1513 / 186 | Оценка: 4.20 / 4.03 | Длительность: 16:55:00
Лекция 15:

Разработка модулей для DotNetNuke в Visual Studio 2005

< Лекция 14 || Лекция 15: 123456

Этапы реализации уровня представления

Для создания уровня представления следует:

  • модифицировать файлы локализации ( *.resx );
  • модифицировать элементы управления и связанные с ними файлы кода ( EditGuestBook.ascx, Settings.ascx, ViewGuestBook.ascx ).

Все перечисленные файлы находятся в каталоге /DesktopModules/GuestBook.

Модификация файлов локализации

Технология локализации, используемая в DNN, позволяет создавать текстовые метки с возможностью изменения текста при переключении языка. Это достигается путем изменения файла ресурсов, который имеет расширение .resx.

Откройте файл /DesktopModules/GuestBook/App_LocalResources/EditGuestBook.ascx.resx (рис. 15.27).

Исходное содержимое файла EditGuestBook.ascx.resx.

Рис. 15.27. Исходное содержимое файла EditGuestBook.ascx.resx.

Измените содержимое файла таким образом, чтобы оно соответствовало рис. 15.28.

Измененное содержимое файла EditGuestBook.ascx.resx.

Рис. 15.28. Измененное содержимое файла EditGuestBook.ascx.resx.

Откройте файл Settings.ascx.resx (рис. 15.29).

Исходное содержимое файла Settings.ascx.resx

Рис. 15.29. Исходное содержимое файла Settings.ascx.resx

Следует изменить его содержимое таким образом, чтобы оно соответствовало приведенному на рис. 15.30.

Измененное содержимое файла Settings.ascx.resx

Рис. 15.30. Измененное содержимое файла Settings.ascx.resx

Аналогично, следует заменить содержимое файла ресурсов ViewGuestBook.ascx.resx на следующее (рис. 15.31).

Измененное содержимое файла ViewGuestBook.ascx.resx

Рис. 15.31. Измененное содержимое файла ViewGuestBook.ascx.resx

Модификация элементов управления

Модуль состоит из трех элементов управления:

  1. EditGuestBook.ascx и EditGuestBook.ascx.vb
  2. Settings.ascx и Settings.ascx.vb
  3. ViewGuestBook.ascx и ViewGuestBook.ascx.vb

В контекстном меню файла EditGuestBook.ascx выберите пункт View Markup (рис. 15.32).

Контекстное меню файла EditGuestBook.ascx

Рис. 15.32. Контекстное меню файла EditGuestBook.ascx

Замените код элемента управления на следующий:

<%@ Control language="VB" Inherits="YourCompany.Modules.GuestBook.EditGuestBook" 
CodeFile="EditGuestBook.ascx.vb" AutoEventWireup="true"%>
<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %>
<dnn:label id="lblContent" runat="server" controlname="lblContent" 
suffix=":"></dnn:label>
&nbsp;
<asp:ObjectDataSource ID="ObjectDataSource_Tasks" runat="server" 
  DataObjectTypeName="YourCompany.Modules.GuestBook.GuestBookInfo"
  DeleteMethod="GuestBook_Delete" InsertMethod="GuestBook_Insert" 
  OldValuesParameterFormatString="original_{0}"
  OnInit="Page_Load" SelectMethod="GuestBook_GetAll" 
  TypeName="YourCompany.Modules.GuestBook.GuestBookController"
  UpdateMethod="GuestBook_Update">
    <SelectParameters>
      <asp:Parameter DefaultValue="00" Name="ModuleId" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>
&nbsp;
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
  AutoGenerateColumns="False" DataSourceID="ObjectDataSource_Tasks" 
  DataKeyNames="ID">
  <Columns>
    <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
    <asp:BoundField DataField="ID" HeaderText="ID" Visible="False" />
    <asp:BoundField DataField="ModuleID" HeaderText="ModuleID" Visible="False" />
    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
    <asp:BoundField DataField="Message" HeaderText="Message" SortExpression="Message" />
    <asp:BoundField DataField="Email" HeaderText="Email" />
    <asp:BoundField ApplyFormatInEditMode="True" DataField="DateEntered" 
     DataFormatString="{0:d}"
    HeaderText="Date" HtmlEncode="False" SortExpression="DateEntered" />
  </Columns>
</asp:GridView> <asp:BoundField ApplyFormatInEditMode="True" DataField="DateEntered" 
 DataFormatString="{0:d}"
 HeaderText="Date" HtmlEncode="False" SortExpression="DateEntered" />
</Columns>
</asp:GridView>

Проделайте аналогичную процедуру с файлом Settings.ascx, заменив его разметку на следующую:

<%@ Control Language="VB" AutoEventWireup="false" 
   CodeFile="Settings.ascx.vb" Inherits="YourCompany.Modules.GuestBook.Settings" %>
<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %>

<dnn:label id="lblshowform" runat="server" controlname="lblshowform" 
  suffix=":"></dnn:label>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
  OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
  <asp:ListItem Selected="True">Yes</asp:ListItem>
  <asp:ListItem>No</asp:ListItem>
</asp:DropDownList>

То же самое следует проделать с разметкой файла ViewGuestBook.ascx, заменив ее на следующую:

<%@ Control Language="VB" Inherits="YourCompany.Modules.GuestBook.ViewGuestBook" 
 CodeFile="ViewGuestBook.ascx.vb"
AutoEventWireup="true" %>
<%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %>
<asp:ObjectDataSource ID="ObjectDataSource_Tasks" runat="server" 
  DataObjectTypeName="YourCompany.Modules.GuestBook.GuestBookInfo"
  DeleteMethod="GuestBook_Delete" InsertMethod="GuestBook_Insert" 
  OldValuesParameterFormatString="original_{0}"
  SelectMethod="GuestBook_GetAll" TypeName="YourCompany.Modules.GuestBook.GuestBookController"
  UpdateMethod="GuestBook_Update" OnInit="Page_Load">
  <SelectParameters>
    <asp:Parameter DefaultValue="00" Name="ModuleId" Type="Int32" />
  </SelectParameters>
</asp:ObjectDataSource>
&nbsp;
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource_Tasks"
  AutoGenerateColumns="False" AllowPaging="True" HorizontalAlign="Center">
  <Columns>
    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
    <asp:BoundField DataField="Message" HeaderText="Message" 
      SortExpression="Message" />
    <asp:BoundField ApplyFormatInEditMode="True" DataField="DateEntered" 
      DataFormatString="{0:d}"
  HeaderText="Date" SortExpression="DateEntered" HtmlEncode="False" />
  </Columns>
  <EmptyDataTemplate>
    There are no entries.
  </EmptyDataTemplate>
</asp:GridView>
<br />
<center>
  <dnn:Label ID="lblAddMessage" runat="server" ControlName="lblAddMessage" 
    Suffix=":">
  </dnn:Label>
</center>
<br />
<asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource_Tasks" 
  DefaultMode="Insert" HorizontalAlign="Center">
  <InsertItemTemplate>
    <table cellpadding="2" cellspacing="5" style="width: 50%" align="center">
      <tr>
        <td align="right" style="width: 4px">
        <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td>
        <td style="width: 100px">
        <asp:TextBox ID="NameTextBox" runat="server" 
         Text='<%# Bind("Name") %>' Width="264px"></asp:TextBox></td>
      </tr>
      <tr>
        <td align="right" style="width: 4px; height: 23px">
        <asp:Label ID="Label3" runat="server" Text="Email"></asp:Label></td>
        <td style="width: 100px; height: 23px">
        <asp:TextBox ID="EmailTextBox" runat="server" 
          Text='<%# Bind("Email") %>' Width="264px"></asp:TextBox></td>
      </tr>
      <tr>
        <td align="right" style="width: 4px; height: 21px">
        <asp:Label ID="Label2" runat="server" 
          Text="Message"></asp:Label></td>
        <td style="width: 100px; height: 21px">
        <asp:TextBox ID="MessageTextBox" runat="server" EnableViewState="False" 
        MaxLength="250"         Rows="2" Text='<%# Bind("Message") %>' 
        TextMode="MultiLine" Width="264px"></asp:TextBox></td>
      </tr>
      <tr>
        <td align="right" colspan="2" style="height: 21px">
        <asp:Button ID="InsertButton" runat="server" Text="Submit" 
         CommandName="Insert" /></td>
      </tr>
    </table>
    <br />
    &nbsp;
  </InsertItemTemplate>
</asp:FormView>
15.3.

Далее следует в контекстном меню файла EditGuestBook.ascx выбрать пункт View Code (рис. 15.33).

Контекстное меню файла EditGuestBook.ascx

Рис. 15.33. Контекстное меню файла EditGuestBook.ascx

Открывшийся код следует заменить на следующий:

Imports DotNetNuke
Imports System.Web.UI
Imports System.Collections.Generic
Imports System.Reflection
Imports DotNetNuke.Entities.Modules

Namespace YourCompany.Modules.GuestBook
  Partial Class EditGuestBook
    Inherits PortalModuleBase
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
      Try
      Catch exc As Exception
        Exceptions.ProcessModuleLoadException(Me, exc)
      End Try
    End Sub

    Protected Sub SetModuleId(ByVal sender As Object, 
    ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) _
            Handles ObjectDataSource_Tasks.Selecting
      e.InputParameters("ModuleId") = ModuleId.ToString
    End Sub
  End Class
End Namespace

Код файла Settings.ascx необходимо заменить на следующий:

Imports System
Imports System.Web.UI
Imports DotNetNuke
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Services.Exceptions
Namespace YourCompany.Modules.GuestBook
  Partial Class Settings
    Inherits ModuleSettingsBase
    Public Overrides Sub LoadSettings()
      Try
        If (Page.IsPostBack = False) Then
          If (Not (CType(TabModuleSettings("showform"), String)) Is Nothing) Then
            Me.DropDownList1.SelectedValue = CType(TabModuleSettings("showform"), String)
          End If
        End If
      Catch exc As Exception
        Exceptions.ProcessModuleLoadException(Me, exc)
      End Try
    End Sub

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
      Dim objModules As ModuleController = New ModuleController
      If (Me.DropDownList1.SelectedValue = "Yes") Then
        objModules.UpdateTabModuleSetting(TabModuleId, "showform", "Yes")
      Else
        objModules.UpdateTabModuleSetting(TabModuleId, "showform", "No")
      End If
    End Sub
  End Class
End Namespace

Аналогично ниже приведен код для файла ViewGuestBook.ascx:

Imports DotNetNuke
Imports System.Web.UI
Imports System.Collections.Generic
Imports System.Reflection
Imports DotNetNuke.Entities.Modules
Namespace YourCompany.Modules.GuestBook
  Partial Class ViewGuestBook
    Inherits Entities.Modules.PortalModuleBase
    Implements Entities.Modules.IActionable
    Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection _
                                          Implements Entities.Modules.IActionable.ModuleActions
      Get
        Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
        Actions.Add(GetNextActionID, _
            Localization.GetString(Entities.Modules.Actions.ModuleActionType.EditContent, 
            LocalResourceFile), 
            Entities.Modules.Actions.ModuleActionType.EditContent, 
            "", "", EditUrl(), False, Security.SecurityAccessLevel.Edit, True, False)
        Return Actions
      End Get
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
      Try
        Dim objModules As ModuleController = New ModuleController
        If Not Page.IsPostBack Then
          If (Not (CType(Settings("showform"), String)) Is Nothing) Then
            If (CType(Settings("showform"), String) = "No") Then
              ' Do not allow messages to be added
              FormView1.Visible = False
              lblAddMessage.Visible = False
            End If
          End If
        Else
          Me.GridView1.DataBind()
        End If
      Catch ex As Exception
        Exceptions.ProcessModuleLoadException(Me, ex)
      End Try
    End Sub

    Protected Sub NewItem(ByVal sender As Object, _
              ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) _
              Handles FormView1.ItemInserting
      e.Values.Item("ID") = 0
      e.Values.Item("ModuleId") = ModuleId.ToString()
      e.Values.Item("DateEntered") = DateTime.Now.ToShortDateString
    End Sub

    Protected Sub SetModuleID(ByVal sender As Object, _
              ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) _
              Handles ObjectDataSource_Tasks.Selecting
      e.InputParameters("ModuleId") = ModuleId.ToString
    End Sub
  End Class
End Namespace
< Лекция 14 || Лекция 15: 123456