Search Results

Search found 92 results on 4 pages for 'formview'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • Accessing Controls Within A Gridview

    - by Bunch
    Sometimes you need to access a control within a GridView, but it isn’t quite as straight forward as just using FindControl to grab the control like you can in a FormView. Since the GridView builds multiple rows the key is to specify the row. In this example there is a GridView with a control for a player’s errors. If the errors is greater than 9 the GridView should display the control (lblErrors) in red so it stands out. Here is the GridView: <asp:GridView ID="gvFielding" runat="server" DataSourceID="sqlFielding" DataKeyNames="PlayerID" AutoGenerateColumns="false" >     <Columns>         <asp:BoundField DataField="PlayerName" HeaderText="Player Name" />         <asp:BoundField DataField="PlayerNumber" HeaderText="Player Number" />         <asp:TemplateField HeaderText="Errors">             <ItemTemplate>                 <asp:Label ID="lblErrors" runat="server" Text='<%# EVAL("Errors") %>'  />             </ItemTemplate>         </asp:TemplateField>     </Columns> </asp:GridView> In the code behind you can add the code to change the label’s ForeColor property to red based on the amount of errors. In this case 10 or more errors triggers the color change. Protected Sub gvFielding_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvFielding.DataBound     Dim errorLabel As Label     Dim errors As Integer     Dim i As Integer = 0     For Each row As GridViewRow In gvFielding.Rows         errorLabel = gvFielding.Rows(i).FindControl("lblErrors")         If Not errorLabel.Text = Nothing Then             Integer.TryParse(errorLabel.Text, errors)             If errors > 9 Then                 errorLabel.ForeColor = Drawing.Color.Red             End If         End If         i += 1     Next End Sub The main points in the DataBound sub is use a For Each statement to loop through the rows and to increment the variable i so you loop through every row. That way you check each one and if the value is greater than 9 the label changes to red. The If Not errorLabel.Text = Nothing line is there as a check in case no data comes back at all for Errors. Technorati Tags: GridView,ASP.Net,VB.Net

    Read the article

  • Stir Trek 2: Iron Man Edition

    Next month (7 May 2010) Ill be presenting at the second annual Stir Trek event in Columbus, Ohio. Stir Trek (so named because last year its themes mixed MIX and the opening of the Star Trek movie) is a very cool local event.  Its a lot of fun to present at and to attend, because of its unique venue: a movie theater.  And whats more, the cost of admission includes a private showing of a new movie (this year: Iron Man 2).  The sessions cover a variety of topics (not just Microsoft), similar to CodeMash.  The event recently sold out, so Im not telling you all of this so that you can go and sign up (though I believe you can get on the waitlist still).  Rather, this is pretty much just an excuse for me to talk about my session as a way to organize my thoughts. Im actually speaking on the same topic as I did last year, but the key difference is that last year the subject of my session was nowhere close to being released, and this year, its RTM (as of last week).  Thats right, the topic is Whats New in ASP.NET 4 how did you guess? Whats New in ASP.NET 4 So, just what *is* new in ASP.NET 4?  Hasnt Microsoft been spending all of their time on Silverlight and MVC the last few years?  Well, actually, no.  There are some pretty cool things that are now available out of the box in ASP.NET 4.  Theres a nice summary of the new features on MSDN.  Here is my super-brief summary: Extensible Output Caching use providers like distributed cache or file system cache Preload Web Applications IIS 7.5 only; avoid the startup tax for your site by preloading it. Permanent (301) Redirects are finally supported by the framework in one line of code, not two. Session State Compression Can speed up session access in a web farm environment.  Test it to see. Web Forms Features several of which mirror ASP.NET MVC advantages (viewstate, control ids) Set Meta Keywords and Description easily Granular and inheritable control over ViewState Support for more recent browsers and devices Routing (introduced in 3.5 SP1) some new features and zero web.config changes required Client ID control makes client manipulation of DOM elements much simpler. Row Selection in Data Controls fixed (id based, not row index based) FormView and ListView enhancements (less markup, more CSS compliant) New QueryExtender control makes filtering data from other Data Source Controls easy More CSS and Accessibility support Reduction of Tables and more control over output for other template controls Dynamic Data enhancements More control templates Support for inheritance in the Data Model New Attributes ASP.NET Chart Control (learn more) Lots of IDE enhancements Web Deploy tool My session will cover many but not all of these features.  Theres only an hour (3pm-4pm), and its right before the prize giveaway and movie showing, so Ill be moving quickly and most likely answering questions off-line via email after the talk. Hope to see you there! Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How to implement EntityDataSource Where IN entity sql clause

    - by TonyS
    I want to pass a number of values into a parameter of the EntityDataSource, e.g.: Where="it.ORDER_ID IN {@OrderIdList}" (this is a property on the EntityDataSource) <WhereParameters> <asp:ControlParameter Name="OrderIdList" Type="Int16" ControlID="OrderFilterControl" PropertyName="OrderIdList" /> </WhereParameters> This doesn't work as ORDER_ID is of type int32 and I need to pass in multiple values, e.g. {1,2,3} etc The next thing I tried was setting the Where clause in code-behind and this all works except I can't get data binding on DropDownLists to work. By this I mean no value is returned from the bound dropdownlists in the EntityDataSource Updating Event. My ideal solution would be to use a WhereParameter on the EntityDataSource but any help is appreciated. Thanks, Tony. A complete code example follows using the AdventureWorks db: Public Class EntityDataSourceWhereInClause Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load CustomersEntityDataSource.Where = WhereClause ''# reset after each postback as its lost otherwise End Sub Private Sub cmdFilterCustomers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFilterCustomers.Click Dim CustomerIdList As New Generic.List(Of Int32) For Each item As ListItem In CustomerIdCheckBoxList.Items If item.Selected Then CustomerIdList.Add(item.Value) End If Next Dim CustomerCsvList As String = String.Join(", ", CustomerIdList.Select(Function(o) o.ToString()).ToArray()) WhereClause = "it.CustomerID IN {" & CustomerCsvList & "}" CustomersEntityDataSource.Where = WhereClause FormView1.PageIndex = 0 End Sub ''# save between postbacks the custom Where IN clause Public Property WhereClause() As String Get Return ViewState("WhereClause") End Get Set(ByVal value As String) ViewState.Add("WhereClause", value) End Set End Property Private Sub CustomersEntityDataSource_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.EntityDataSourceChangingEventArgs) Handles CustomersEntityDataSource.Updating Dim c = CType(e.Entity, EntityFrameworkTest.Customer) If c.Title.Length = 0 Then Response.Write("Title is empty string, so will save like this!") End If End Sub End Class <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EntityDataSourceWhereInClause.aspx.vb" Inherits="EntityFrameworkTest.EntityDataSourceWhereInClause" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <%''# filter control %> <div> <asp:EntityDataSource ID="CustomerIdListEntityDataSource" runat="server" ConnectionString="name=AdventureWorksLT2008Entities" DefaultContainerName="AdventureWorksLT2008Entities" EnableFlattening="False" EntitySetName="Customers" Select="it.[CustomerID]" OrderBy="it.[CustomerID]"> </asp:EntityDataSource> <asp:CheckBoxList ID="CustomerIdCheckBoxList" runat="server" DataSourceID="CustomerIdListEntityDataSource" DataTextField="CustomerID" DataValueField="CustomerID" RepeatDirection="Horizontal"> </asp:CheckBoxList> <asp:Button ID="cmdFilterCustomers" runat="server" Text="Apply Filter" /> </div> <% ''# you get this error passing in CSV in the where clause ''# The element type 'Edm.Int32' and the CollectionType 'Transient.collection[Edm.String(Nullable=True,DefaultValue=,MaxLength=,Unicode=,FixedLength=)]' are not compatible. The IN expression only supports entity, primitive, and reference types. Near WHERE predicate, line 6, column 15. ''# so have coded it manually in code-behind Where="it.CustomerID IN {@OrderIdList}" %> <asp:EntityDataSource ID="CustomersEntityDataSource" runat="server" ConnectionString="name=AdventureWorksLT2008Entities" DefaultContainerName="AdventureWorksLT2008Entities" EnableFlattening="False" EnableUpdate="True" EntitySetName="Customers" AutoGenerateOrderByClause="false"> </asp:EntityDataSource> <%''# updating works with DropDownLists until the Where clause is set in code %> <asp:FormView ID="FormView1" runat="server" AllowPaging="True" CellPadding="4" DataKeyNames="CustomerID" DataSourceID="CustomersEntityDataSource" ForeColor="#333333"> <EditItemTemplate> CustomerID: <asp:Label ID="CustomerIDLabel1" runat="server" Text='<%# Eval("CustomerID") %>' /> <br /> NameStyle: <asp:CheckBox ID="NameStyleCheckBox" runat="server" Checked='<%# Bind("NameStyle") %>' /> <br /> Title: <%''# the SelectedValue is not Bound to the EF object if the Where clause is updated in code-behind %> <asp:DropDownList ID="ddlTitleBound" runat="server" DataSourceID="TitleEntityDataSource" DataTextField="Title" DataValueField="Title" AutoPostBack="false" AppendDataBoundItems="true" SelectedValue='<%# Bind("Title") %>'> </asp:DropDownList> <asp:EntityDataSource ID="TitleEntityDataSource" runat="server" ConnectionString="name=AdventureWorksLT2008Entities" DefaultContainerName="AdventureWorksLT2008Entities" EnableFlattening="False" EntitySetName="Customers" Select="it.[Title]" GroupBy="it.[Title]" ViewStateMode="Enabled"> </asp:EntityDataSource> <br /> FirstName: <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>' /> <br /> MiddleName: <asp:TextBox ID="MiddleNameTextBox" runat="server" Text='<%# Bind("MiddleName") %>' /> <br /> LastName: <asp:TextBox ID="LastNameTextBox" runat="server" Text='<%# Bind("LastName") %>' /> <br /> Suffix: <asp:TextBox ID="SuffixTextBox" runat="server" Text='<%# Bind("Suffix") %>' /> <br /> CompanyName: <asp:TextBox ID="CompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' /> <br /> SalesPerson: <asp:TextBox ID="SalesPersonTextBox" runat="server" Text='<%# Bind("SalesPerson") %>' /> <br /> EmailAddress: <asp:TextBox ID="EmailAddressTextBox" runat="server" Text='<%# Bind("EmailAddress") %>' /> <br /> Phone: <asp:TextBox ID="PhoneTextBox" runat="server" Text='<%# Bind("Phone") %>' /> <br /> PasswordHash: <asp:TextBox ID="PasswordHashTextBox" runat="server" Text='<%# Bind("PasswordHash") %>' /> <br /> PasswordSalt: <asp:TextBox ID="PasswordSaltTextBox" runat="server" Text='<%# Bind("PasswordSalt") %>' /> <br /> rowguid: <asp:TextBox ID="rowguidTextBox" runat="server" Text='<%# Bind("rowguid") %>' /> <br /> ModifiedDate: <asp:TextBox ID="ModifiedDateTextBox" runat="server" Text='<%# Bind("ModifiedDate") %>' /> <br /> <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" /> &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" /> </EditItemTemplate> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <ItemTemplate> CustomerID: <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>' /> <br /> NameStyle: <asp:CheckBox ID="NameStyleCheckBox" runat="server" Checked='<%# Bind("NameStyle") %>' Enabled="false" /> <br /> Title: <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' /> <br /> FirstName: <asp:Label ID="FirstNameLabel" runat="server" Text='<%# Bind("FirstName") %>' /> <br /> MiddleName: <asp:Label ID="MiddleNameLabel" runat="server" Text='<%# Bind("MiddleName") %>' /> <br /> LastName: <asp:Label ID="LastNameLabel" runat="server" Text='<%# Bind("LastName") %>' /> <br /> Suffix: <asp:Label ID="SuffixLabel" runat="server" Text='<%# Bind("Suffix") %>' /> <br /> CompanyName: <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Bind("CompanyName") %>' /> <br /> SalesPerson: <asp:Label ID="SalesPersonLabel" runat="server" Text='<%# Bind("SalesPerson") %>' /> <br /> EmailAddress: <asp:Label ID="EmailAddressLabel" runat="server" Text='<%# Bind("EmailAddress") %>' /> <br /> Phone: <asp:Label ID="PhoneLabel" runat="server" Text='<%# Bind("Phone") %>' /> <br /> PasswordHash: <asp:Label ID="PasswordHashLabel" runat="server" Text='<%# Bind("PasswordHash") %>' /> <br /> PasswordSalt: <asp:Label ID="PasswordSaltLabel" runat="server" Text='<%# Bind("PasswordSalt") %>' /> <br /> rowguid: <asp:Label ID="rowguidLabel" runat="server" Text='<%# Bind("rowguid") %>' /> <br /> ModifiedDate: <asp:Label ID="ModifiedDateLabel" runat="server" Text='<%# Bind("ModifiedDate") %>' /> <br /> <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" /> </ItemTemplate> <PagerSettings Position="Top" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> </asp:FormView> </form>

    Read the article

  • C# Multi CheckboxList update inserts checked records but doesn't delete unchecked records

    - by DLL
    I have a multi checkboxlist on a formview. Both use queries in a tableadapter. I'm using VS 2012. When the user updates the form, I use the following code to update the checkbox data. If a user checks a new box, a new record is inserted correctly, however if the user unchecks a box the existing record is not deleted. The delete query works fine if I run it from the query builder in the table adapter, it's reaching the expected line in the code correctly, all values are correct and I receive no errors. I use a similar query to delete records when the form level data is deleted which works fine. The very last line is the one that doesn't work. Query: DELETE FROM [SLA_Categories] WHERE (([SLA_ID] = @SLA_ID) AND ([Choice_ID] = @Choice_ID)) protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) { if (FormView1.DataKey.Value != null) { Categs = (CheckBoxList)FormView1.FindControl("CheckBoxList1"); CurrentSLA_ID = (int)FormView1.DataKey.Value; } if (CurrentSLA_ID > 0) { foreach (ListItem li in Categs.Items) { // See if there's a record for the current sla in this category int CurrentChoice_ID = Convert.ToInt32(li.Value); SLADataSetTableAdapters.SLA_CategoriesTableAdapter myAdapter; myAdapter = new SLADataSetTableAdapters.SLA_CategoriesTableAdapter(); int myCount = (int)myAdapter.FindCategoryBySLA_IDAndChoice_ID(CurrentSLA_ID, CurrentChoice_ID); // If this category is checked and there is not an existing rec, insert one if (li.Selected == true && myCount < 1) { // Insert a rec for this sla myAdapter.InsertCategory(CurrentChoice_ID, CurrentSLA_ID); } // If this category is unchecked and there is and existing rec, delete it if (li.Selected == false && myCount > 0) { // Delete this rec myAdapter.DeleteCategoryBySLA_IDAndChoice_ID(CurrentChoice_ID, CurrentSLA_ID); } } } }

    Read the article

  • Can I have two separate projects, 1 WebForms and 1 ASP.NET MVC, to both point to the same domain?

    - by Hamman359
    Is it possible to setup two separate projects, 1 WebForms and 1 ASP.NET MVC, to both point to the same domain? i.e. both point to different pages within www.somesite.com. Here's some background on the application and why I'm asking. This is a brownfield application that is currently 2.0 WebForms and is full of WebFormy 'goodness' (i.e. ObjectDataSources, FormView controls, UpdatePanels, etc...) There are lost of other 'fun' things in the code base like 600+ Stored Procedures and 200+ line methods in the business layer code that get data from the DB via stored proc, do some processing on the data, build an HTML string using string concatenation and then return that string to the UI layer. What we are planning on doing is developing new features in MVC and slowly converting the existing features over to MVC one at a time. As part of this transition, we will also be re-writing the layers below the UI to clean up the mess there and to do things like replace the stored procedures with NHibernate and introduce an IOC container. I know that you can run WebForms and MVC side-by-side in the same project, however, because we will be making wholesale changes to the way we do many things throughout our entire development stack, I'd like the new stuff to be a completely separate project within the solution. This should help serve as very visual reminder that this is a different way of doing things than before and make it easier to remove the old code as it is no longer needed. What I don't know is, is this even possible? Can two separate project point to the same domain? Here's an quick example of what I'm thinking: www.somesite.com/orders.aspx?id=123 (Orders page from existing WebForms project) www.somesite.com/customer/987 (Customer page from new MVC project)

    Read the article

  • C# - Naming a value combined "getter/setter" method (WebForms & Binding)

    - by tyndall
    Looking for some help on some names for a project I'm currently working on. I don't have a compsci degree so I don't know what to call this. I have a method called TryToGetSetValue(Direction direction, object value, object valueOnFail) Then there would be a Direction enum public enum Direction { ModelToForm, FormToModel } Background This is a legacy ASP.NET application. The models, database, and mainframe are designed poorly. I can't put in MVP or MVC patterns yet (too much work). ASP.NET code is a ridiculous mess (partial pages, single-page design, 5x the normal amount of jQuery, everything is a jQuery UI dialog). I'm just trying to put in a bridge so then I can do more refactoring over the next year. I have ~200 fields that need to be set on a GET and written back on a POST. I trying not to x2 these 200 fields and have 400 lines of code to support. What would you call my method? enum? Is there so other form of binding that would be easy to use instead? I'm not a fan of the DetailsView or FormView built-ins of ASP.NET WebForms.

    Read the article

  • Dynamic Control loading at wrong time?

    - by Telos
    This one is a little... odd. Basically I have a form I'm building using ASP.NET Dynamic Data, which is going to utilize several custom field templates. I've just added another field to the FormView, with it's own custom template, and the form is loading that control twice for no apparent reason. Worse yet, the first time it loads the template, the Row is not ready yet and I get the error message: {"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."} I'm accessing the Row variable in a LinqDataSource OnSelected event in order to get the child object... Now for the wierd part: If I reorder the fields a little, the one causing the problem no longer gets loaded twice. Any thoughts? EDIT: I've noticed that Page_Load gets called on the first load (when Row throws an exception if you try to use it) but does NOT get called the second time around. If that helps any... Right now managing it by just catching and ignoring the exception, but still a little worried that things will break if I don't find the real cause. EDIT 2: I've traced the problem to using FindControl recursively to find other controls on the page. Apparently FindControl can cause the page lifecycle events (at least up to page_load) to fire... and this occurs before that page "should" be loading so it's dynamic data "stuff" isn't ready yet.

    Read the article

  • A potentially dangerous Request.Form value was detected: Dealing with these errors proactively, or a

    - by Albert
    I'm noticing this error more and more in my error logs. I've read through the questions here talking about this error, but they don't address what I would like to do (see below). I'm considering three options, in the order of preference: 1) When submitting a form (I use formviews almost exclusively, if that helps), if potentially dangerous characters are detected, automatically strip them out and submit. 2) When submitting a form, if potentially dangerous characters are detected, alert the user and let them fix it before trying again. 3) After the exception is generated, deal with it and alert the user. I'm hoping one of the first two options might be able to do somewhat globally...I know for the 3rd I'd have to alter a TON of Try-Catch blocks I already have in place. Doable, but labor intensive. I'd rather be proactive about it if at all possible and avoid the exception all together. Perhaps one approach to #1 would be to write a block of code that could loop through all text entry fields in a formview, during the insert/update event, and strip the characters out. I'm ok with that, but I'd rather not have to heavily alter all my Insert/Update events to accomplish this. Or maybe I just create a different class to do the text checking/deleting, and only insert 1 line of code in each Insert/Update event. If anyone can come up with some example code of any of these approaches that would be a help. Thanks for any ideas or information. I'm definitely open to other solutions too; these are only the 3 that came to mind. I can say that I don't want to turn request validation off though.

    Read the article

  • Problems migrating databinding in VB.NET from Winforms to ASP.NET 2.0

    - by David
    And this was supposed to be so easy... I have existing business and data access layers that handle the retrieval and update of the data in question. These work great with the existing Winforms application (.Net V2.0) Now, in trying to write a new web-based UI, I'm running into all sorts of problems (last time I wrote asp.net code was in 1.1). Specifically, I can't data bind a text box to a business object. Oh, sure there's the ObjectDataSource but that wants to know how to do CRUD operations on the data. What I'm looking for is something that acts like the 'classic' binding objects so that, in my code, it's as simple as retrieving the object and doing a a refresh. The data component like FormView and DetailsView are so generic-looking that it's ridiculous. The existing application would have tabbed dialogs, text boxes grouped by panels, etc. On top of that, I have a directive to use master pages and unless one control causes it, I can't seem to get the content section to expand. I can't just put a text box 'below' the bottom of "Content1" and have it resize the content section - which gives me the same results as an earlier question I posted when the footer wasn't being 'pushed down' - relative position solved that but doesn't seem to solve it with placing small text boxes in the area. What I want is fairly simple. Something like: bindingobject.datasource = businessdataobject bindingobject.refresh ...and have the text boxes refresh with the new values. Likewise to have 'businessdataobject' properties updated as the user enters new data. I was able to do this with the GridView (grdRequests.DataSource = lstRequests) by making a list of asp:BoundField tags inside the collection of the GridView. Am I tilting at windmills here?

    Read the article

  • Spring validation has error in XML document from ServletContext resource

    - by user1441404
    I applied spring validation in my registration page .but the follwing error are shown in my server log of my app engine server. javax.servlet.UnavailableException: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 22 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 22; columnNumber: 30; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'property'. My code is given below : <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd > <beans:bean name="/register" class="com.my.registration.NewUserRegistration"> <property name="validator"> <bean class="com.my.validation.UserValidator" /> </property> <beans:property name="formView" value="newuser"></beans:property> <beans:property name="successView" value="home"></beans:property> </beans:bean> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> </beans:beans>

    Read the article

  • <%: %> brackets for HTML Encoding in ASP.NET 4.0

    - by Slauma
    Accidentally I found this post about a new feature in ASP.NET 4.0: Expressions enclosed in these new brackets <%: Content %> should be rendered as HTML encoded. I've tried this within a databound label in a FormView like so: <asp:Label ID="MyLabel" runat="server" Text='<%: Eval("MyTextProperty") %>' /> But it doesn't work: The text property contains script tags (for testing), but the output is blank. Using the traditional way works: <asp:Label ID="MyLabel" runat="server" Text='<%# HttpUtility.HtmlEncode(Eval("MyTextProperty")) %>' /> What am I doing wrong? (On a sidenote: I am too stupid to find any information: Google refuses to search for that thing. The VS2010 Online help on MSDN offers a lot of hits, but nothing related to my search. Stackoverflow search too. And I don't know how these "things" (the brackets I mean) are officially called to have a better search term.) Any info and additional links and resources are welcome! Thanks in advance!

    Read the article

  • ListView not firing OnItemCommand after preventing postback

    - by nevizi
    Hi there, I have a ListView inside a FormView that, for some strange reason, doesn't fire neither the ItemInsert nor the ItemCommand event. I'm populating the ListView with a generic list. I bind the list to the ListView on the OnPreRenderComplete. <asp:ListView runat="server" ID="lvReferences" DataKeyNames="idReference" OnItemInserting="ContractReferences_Inserting" OnItemDeleting="ContractReferences_Deleting" InsertItemPosition="LastItem" OnItemCommand="ContractReferences_Command" OnItemCreated="ContractReferences_ItemDataBound"> <LayoutTemplate> <ul> <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> </ul> </LayoutTemplate> <ItemTemplate> <li class="obsItem"> <a href="#"><asp:TextBox ID="valRef" runat="server" Width="5px" Enabled="false" Text='<%#Bind("idProcessRecordRef") %>' /></a> <asp:TextBox id="txtRef" runat="server" Text='<%#Bind("description") %>' /> <asp:ImageButton ID="btDelete" runat="server" CommandName="Delete" ImageUrl="~/_layouts/web.commons/Images/eliminar.png" /> </li> </ItemTemplate> <InsertItemTemplate> <li class="obsItem"> <a href="#"><asp:TextBox ID="valRef" runat="server" Width="5px" Enabled="false" /></a> <asp:TextBox id="txtRef" runat="server" /> <asp:ImageButton ID="btDetail" CausesValidation="false" OnClientClick="javascript:openPopup();return false;" runat="server" ImageUrl="~/_layouts/web.commons/Images/novo.png" /> <asp:ImageButton ID="btSaveDs" runat="server" CommmandName="Insert" CausesValidation="false" ImageUrl="~/_layouts/web.commons/Images/gravarObs.png" /> </li> </InsertItemTemplate> </asp:ListView> My ItemDataBound method is: protected void ContractReferences_ItemDataBound(object sender, ListViewItemEventArgs e) { if (!IsPostBack) { TextBox valRef = e.Item.FindControl("valRef") as TextBox; TextBox txtRef = e.Item.FindControl("txtRef") as TextBox; ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "function openPopup(){ window.open('ContractPicker.aspx?c1=" + valRef.ClientID + "&c2=" + txtRef.ClientID + "');}", true); } } So, basically, in the InsertItemTemplate I put a button that opens a LOV and populates my valRef and txtRef fields. I had to put a "return false" in order for the parent page to not postback (and I think the problem lies here...). Then, when I click in the ImageButton with the CommandName="Insert", instead of firing the ItemCommand event, it enters once again in the ItemDataBound handler. So, any ideas? Thanks!

    Read the article

  • ListView not firing OnItemCommand (nor ItemInserting) after preventing postback

    - by nevizi
    Hi there, I have a ListView inside a FormView that, for some strange reason, doesn't fire neither the ItemInsert nor the ItemCommand event. I'm populating the ListView with a generic list. I bind the list to the ListView on the OnPreRenderComplete. <asp:ListView runat="server" ID="lvReferences" DataKeyNames="idReference" OnItemInserting="ContractReferences_Inserting" OnItemDeleting="ContractReferences_Deleting" InsertItemPosition="LastItem" OnItemCommand="ContractReferences_Command" OnItemCreated="ContractReferences_ItemDataBound"> <LayoutTemplate> <ul> <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> </ul> </LayoutTemplate> <ItemTemplate> <li class="obsItem"> <a href="#"><asp:TextBox ID="valRef" runat="server" Width="5px" Enabled="false" Text='<%#Bind("idProcessRecordRef") %>' /></a> <asp:TextBox id="txtRef" runat="server" Text='<%#Bind("description") %>' /> <asp:ImageButton ID="btDelete" runat="server" CommandName="Delete" ImageUrl="~/_layouts/web.commons/Images/eliminar.png" /> </li> </ItemTemplate> <InsertItemTemplate> <li class="obsItem"> <a href="#"><asp:TextBox ID="valRef" runat="server" Width="5px" Enabled="false" /></a> <asp:TextBox id="txtRef" runat="server" /> <asp:ImageButton ID="btDetail" CausesValidation="false" OnClientClick="javascript:openPopup();return false;" runat="server" ImageUrl="~/_layouts/web.commons/Images/novo.png" /> <asp:ImageButton ID="btSaveDs" runat="server" CommmandName="Insert" CausesValidation="false" ImageUrl="~/_layouts/web.commons/Images/gravarObs.png" /> </li> </InsertItemTemplate> </asp:ListView> My ItemDataBound method is: protected void ContractReferences_ItemDataBound(object sender, ListViewItemEventArgs e) { if (!IsPostBack) { TextBox valRef = e.Item.FindControl("valRef") as TextBox; TextBox txtRef = e.Item.FindControl("txtRef") as TextBox; ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "function openPopup(){ window.open('ContractPicker.aspx?c1=" + valRef.ClientID + "&c2=" + txtRef.ClientID + "');}", true); } } So, basically, in the InsertItemTemplate I put a button that opens a LOV and populates my valRef and txtRef fields. I had to put a "return false" in order for the parent page to not postback (and I think the problem lies here...). Then, when I click in the ImageButton with the CommandName="Insert", instead of firing the ItemCommand event, it enters once again in the ItemDataBound handler. So, any ideas? Thanks!

    Read the article

  • ASP.Net: Insert null DateTime

    - by Vinzcent
    Hey I'am using a SQLDatasource in combination with a Formview. When I want to insert or update a DateTime that has no value, I always get an error. How do you insert a DateTime null. My SQLDataSource <asp:SqlDataSource ID="sqldsDetailOrder" runat="server" ConnectionString="<%$ ConnectionStrings:csBookStore %>" SelectCommand="SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.*, tblLanguages.*, tblOrders.* FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID INNER JOIN tblLanguages ON tblBooks.LANG_ID = tblLanguages.LANG_ID INNER JOIN tblOrders ON tblBooks.BOOK_ID = tblOrders.BOOK_ID WHERE tblOrders.ID = @ID" DeleteCommand="DELETE FROM [tblOrders] WHERE [ID] = @ID" InsertCommand="INSERT INTO [tblOrders] ([NAME], [ADDRESS], [CITY], [PC], [DATE], [BOOK_ID], [COUNT], [AMOUNT], [DELIVERED], [DDATE], [PAID], [PDATE]) VALUES (@NAME, @ADDRESS, @CITY, @PC, @DATE, @BOOK_ID, @COUNT, @AMOUNT, @DELIVERED, @DDATE, @PAID, @PDATE)" UpdateCommand="UPDATE [tblOrders] SET [NAME] = @NAME, [ADDRESS] = @ADDRESS, [CITY] = @CITY, [PC] = @PC, [DATE] = @DATE, [BOOK_ID] = @BOOK_ID, [COUNT] = @COUNT, [AMOUNT] = @AMOUNT, [DELIVERED] = @DELIVERED, [DDATE] = @DDATE, [PAID] = @PAID, [PDATE] = @PDATE WHERE [ID] = @ID"> <SelectParameters> <asp:ControlParameter ControlID="gvOrdersAdmin" Name="ID" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="NAME" Type="String" /> <asp:Parameter Name="ADDRESS" Type="String" /> <asp:Parameter Name="CITY" Type="String" /> <asp:Parameter Name="PC" Type="String" /> <asp:Parameter DbType="DateTime" Name="DATE" /> <asp:Parameter Name="BOOK_ID" Type="Int32" /> <asp:Parameter Name="COUNT" Type="Int32" /> <asp:Parameter Name="AMOUNT" Type="Decimal" /> <asp:Parameter Name="DELIVERED" Type="Boolean" /> <asp:Parameter DbType="DateTime" Name="DDATE" /> <asp:Parameter Name="PAID" Type="Boolean" /> <asp:Parameter DbType="DateTime" Name="PDATE" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="NAME" Type="String" /> <asp:Parameter Name="ADDRESS" Type="String" /> <asp:Parameter Name="CITY" Type="String" /> <asp:Parameter Name="PC" Type="String" /> <asp:Parameter DbType="DateTime" Name="DATE" /> <asp:Parameter Name="BOOK_ID" Type="Int32" /> <asp:Parameter Name="COUNT" Type="Int32" /> <asp:Parameter Name="AMOUNT" Type="Decimal" /> <asp:Parameter Name="DELIVERED" Type="Boolean" /> <asp:Parameter DbType="DateTime?" Name="DDATE" /> <asp:Parameter Name="PAID" Type="Boolean" /> <asp:Parameter DbType="DateTime" Name="PDATE" /> </InsertParameters> </asp:SqlDataSource> Thanks Vincent

    Read the article

  • December release of Microsoft All-In-One Code Framework is available now.

    - by Jialiang
    The code samples in Microsoft All-In-One Code Framework are updated on 2010-12-13. Download address: http://1code.codeplex.com/releases/view/57459#DownloadId=185534 Updated code sample index categorized by technologies: http://1code.codeplex.com/wikipage?title=All-In-One%20Code%20Framework%20Sample%20Catalog (it also allows you to download individual code samples instead of the entire All-In-One Code Framework sample package.) If it’s the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on YouTube http://www.youtube.com/watch?v=cO5Li3APU58, or read the introduction on our homepage http://1code.codeplex.com/,  and this Port25 article http://port25.technet.com/archive/2010/01/18/the-all-in-one-code-framework.aspx.  -------------- New ASP.NET Code Samples VBASPNETAJAXWebChat and CSASPNETAJAXWebChat Most of you have some experience in chatting with friends on the web. So you may want to know how to make a web chat application, it seems to be quite complicated. But ASP.NET gives you the power to buiild a chat room easily. In this code sample, we will construct our own web chat room with the amazing AJAX feature. The principle is simple relatively. As we all know, a base chat application need 4 base controls: one List control to show the chat room members, one List control to show the message list, one TextBox control to input messages and one button to send message. User inputs his message in the textbox first and then presses Send button, it will send the message to the server. The message list will update every 2 seconds to get the newest message list in the chat room from the server. We need to know, it is hard for us to make an AJAX web chat application like a windows form application because we cannot keep the connection after one web request ended. So a lot of events which communicates between client side and server side cannot be realized. The common workaround is to make web requests in every some seconds to check whether the server side has been updated. But another technique called COMET makes it possible. But it is different with AJAX and will not be talked in details in this KB. For more details about COMET, we can get some clues from the Reference.   CSASPNETCurrentOnlineUserList and VBASPNETCurrentOnlineUserList This sample demos a system that needs to display a list of current online users' information. As a matter of fact, Membership.GetNumberOfUsersOnline Method  can get the number of online users and there is a convenient approach to check whether the user is online by using Membership.GetUser(string userName).IsOnline property,however many asp.net projects are not using membership.So in this case,the sample shows how to display a list of current online users' information without using membership provider. It is not difficult to check whether the user is online by using session.Many projects tend to be used “Session_End” event to mark a user as “Offline”,however ,it may not be a good idea,because it can’t detect the user status accurately. In addition, "Session_End" event is only available in the "InProc" session mode. If you are storing session states in the State Server or SQL Server, "Session_End" event will never fire. To handle this issue, we need to save the user online status to a  global DataTable or  DataBase. In the sample application, define a global DataTable to store the information of online users.Use XmlHttpRequest in the pages to update and check user's last active time at intervals and also retrieve information on how many users are still online. The sample project can auto delete offline users' information from a global DataTable by checking users’ last active time. A step-by-step guide illustrating how to display a list of current online users' information without using membership provider: 1. Login page. Let user sign in and add current user’s information to a global datatable while Initialize the global datatable which used to store information of current online users. 2. Current online user list page. Use XmlHttpRequest in this page to update and check user's last active time at intervals and also retrieve information on how many users are still online. 3. If user closes the page without clicking  the sign out link button ,the sample project can auto mark the user as offline and delete offline users' information from a global DataTable which used to store information of current online users  by checking users’ last active time. Then the current online user list will be like this:   CSASPNETIPtoLocation This sample demonstrates how to find the geographical location from an IP address. As we know, it is not hard for us to get the IP address of visitors via Request.ServerVariable property, but it is really difficult for us to know where they come from. To achieve this feature, the sample uses a free third party web service from http://freegeoip.appspot.com/, which returns the information about an IP address we send to the server in the format of XML, JSON or CSV. It makes all things easier.   CSASPNETBackgroundWorker Sometimes we do an operation which needs long time to complete. It will stop the response and the page is blank until the operation finished. In this case, we want the operation to run in the background, and in the page, we want to display the progress of the running operation. Therefore, the user can know the operation is running and can know the progress. CSASPNETInheritingFromTreeNode In windows forms TreeView, each tree node has a property called "Tag" which can be used to store a custom object. Many customers want to implement the same tag feature in ASP.NET TreeView. This project creates a custom TreeView control named "CustomTreeView" to achieve this goal. CSASPNETRemoteUploadAndDownload and VBASPNETRemoteUploadAndDownload This code sample was created in response to a code sample request in our new code sample request frunction for customers. The code samples demonstrate uploading files to and downloading files from a remote HTTP or FTP server. In .NET Framework 2.0 and higher versions, there are some lightweight class libraries which support HTTP and FTP protocol transmission. By using these classes, we can achieve this programming requirement.   CSASPNETImageEditUpload and VBASPNETImageEditUpload This demo will shows how to insert, edit and update a common image with the type of "jpg", "png", "gif" or "bmp" . We mainly use two different SqlDataSources with the same database to bind to GridView and FormView in order to establish the “cascading” effort. Besides we apply our self-made ImageHanlder to encoding or decoding images of different types, and use context to output the stream of images. We will explicitly assign the binary streams of images through the event of “FormView_ItemInserting” or “Form_ItemUpdating” to synchronize the stream both in what we can see on an aspx page as well as in what’s really stored in the database.   WebBrowser Control, Network and other Windows General New Code Samples   CSWebBrowserSuppressError and VBWebBrowserSuppressError The sample demonstrates how to make WebBrowser suppress errors, such as script error, navigation error and so on.   CSWebBrowserWithProxy and VBWebBrowserWithProxy The sample demonstrates how to make WebBrowser use a proxy server.   CSWebDownloadProgress and VBWebDownloadProgress The sample demonstrates how to show progress during the download. It also supplies the features to Start, Pause, Resume and Cancel a download.   CppSetDesktopWallpaper, CSSetDesktopWallpaper and VBSetDesktopWallpaper This code sample application allows you select an image, view a preview (resized smaller to fit if necessary), select a display style among Tile, Center, Stretch, Fit (Windows 7 and later) and Fill (Windows 7 and later), and set the image as the Desktop wallpaper. CSWindowsServiceRecoveryProperty and VBWindowsServiceRecoveryProperty CSWindowsServiceRecoveryProperty example demonstrates how to use ChangeServiceConfig2 to configure the service "Recovery" properties in C#. This example operates all the options you can see on the service "Recovery" tab, including setting the "Enable actions for stops with errors" option in Windows Vista and later operating systems. This example also include how to grant the shut down privilege to the process, so that we can configure a special option in the "Recovery" tab - "Restart Computer Options...".   New Office Development Code Samples   CSOneNoteRibbonAddIn and VBOneNoteRibbonAddIn The code sample demonstrates a OneNote 2010 COM add-in that implements IDTExtensibility2. The add-in also supports customizing the Ribbon by implementing the IRibbonExtensibility interface. It is a skeleton OneNote add-in that developers can extend it to implement more functions. The code sample was requested by a customer in our code sample request service. We expect that this could help developers in the community.   New Windows Shell Code Samples   CppShellExtPreviewHandler, CSShellExtPreviewHandler and VBShellExtPreviewHandler In the past two months, we released the code samples of Windows Context Menu Handler, Infotip Handler, and Thumbnail Handler. This is the fourth part of the shell extension series: Preview Handler. The code samples demo the C++, C# and VB.NET implementation of a preview handler for a new file type registered with the .recipe extension. Preview handlers are called when an item is selected to show a lightweight, rich, read-only preview of the file's contents in the view's reading pane. This is done without launching the file's associated application. Windows Vista and later operating systems support preview handlers. To be a valid preview handler, several interfaces must be implemented. This includes IPreviewHandler (shobjidl.h); IInitializeWithFile, IInitializeWithStream, or IInitializeWithItem (propsys.h); IObjectWithSite (ocidl.h); and IOleWindow (oleidl.h). There are also optional interfaces, such as IPreviewHandlerVisuals (shobjidl.h), that a preview handler can implement to provide extended support. Windows API Code Pack for Microsoft .NET Framework makes the implementation of these interfaces very easy in .NET. The example preview handler provides previews for .recipe files. The .recipe file type is simply an XML file registered as a unique file name extension. It includes the title of the recipe, its author, difficulty, preparation time, cook time, nutrition information, comments, an embedded preview image, and so on. The preview handler extracts the title, comments, and the embedded image, and display them in a preview window.   In response to many customers' request, we added setup projects in every shell extension samples in this release. Those setup projects allow you to deploy the shell extensions to your end users' machines. ---------- Download address: http://1code.codeplex.com/releases/view/57459#DownloadId=185534 Updated code sample index categorized by technologies: http://1code.codeplex.com/wikipage?title=All-In-One%20Code%20Framework%20Sample%20Catalog (it also allows you to download individual code samples instead of the entire All-In-One Code Framework sample package.) If you have any feedback for us, please email: [email protected]. We look forward to your comments.

    Read the article

  • Entity Framework version 1- Brief Synopsis and Tips &ndash; Part 1

    - by Rohit Gupta
    To Do Eager loading use Projections (for e.g. from c in context.Contacts select c, c.Addresses)  or use Include Query Builder Methods (Include(“Addresses”)) If there is multi-level hierarchical Data then to eager load all the relationships use Include Query Builder methods like customers.Include("Order.OrderDetail") to include Order and OrderDetail collections or use customers.Include("Order.OrderDetail.Location") to include all Order, OrderDetail and location collections with a single include statement =========================================================================== If the query uses Joins then Include() Query Builder method will be ignored, use Nested Queries instead If the query does projections then Include() Query Builder method will be ignored Use Address.ContactReference.Load() OR Contact.Addresses.Load() if you need to Deferred Load Specific Entity – This will result in extra round trips to the database ObjectQuery<> cannot return anonymous types... it will return a ObjectQuery<DBDataRecord> Only Include method can be added to Linq Query Methods Any Linq Query method can be added to Query Builder methods. If you need to append a Query Builder Method (other than Include) after a LINQ method  then cast the IQueryable<Contact> to ObjectQuery<Contact> and then append the Query Builder method to it =========================================================================== Query Builder methods are Select, Where, Include Methods which use Entity SQL as parameters e.g. "it.StartDate, it.EndDate" When Query Builder methods do projection then they return ObjectQuery<DBDataRecord>, thus to iterate over this collection use contact.Item[“Name”].ToString() When Linq To Entities methods do projection, they return collection of anonymous types --- thus the collection is strongly typed and supports Intellisense EF Object Context can track changes only on Entities, not on Anonymous types. If you use a Defining Query for a EntitySet then the EntitySet becomes readonly since a Defining Query is the same as a View (which is treated as a ReadOnly by default). However if you want to use this EntitySet for insert/update/deletes then we need to map stored procs (as created in the DB) to the insert/update/delete functions of the Entity in the Designer You can use either Execute method or ToList() method to bind data to datasources/bindingsources If you use the Execute Method then remember that you can traverse through the ObjectResult<> collection (returned by Execute) only ONCE. In WPF use ObservableCollection to bind to data sources , for keeping track of changes and letting EF send updates to the DB automatically. Use Extension Methods to add logic to Entities. For e.g. create extension methods for the EntityObject class. Create a method in ObjectContext Partial class and pass the entity as a parameter, then call this method as desired from within each entity. ================================================================ DefiningQueries and Stored Procedures: For Custom Entities, one can use DefiningQuery or Stored Procedures. Thus the Custom Entity Collection will be populated using the DefiningQuery (of the EntitySet) or the Sproc. If you use Sproc to populate the EntityCollection then the query execution is immediate and this execution happens on the Server side and any filters applied will be applied in the Client App. If we use a DefiningQuery then these queries are composable, meaning the filters (if applied to the entityset) will all be sent together as a single query to the DB, returning only filtered results. If the sproc returns results that cannot be mapped to existing entity, then we first create the Entity/EntitySet in the CSDL using Designer, then create a dummy Entity/EntitySet using XML in the SSDL. When creating a EntitySet in the SSDL for this dummy entity, use a TSQL that does not return any results, but does return the relevant columns e.g. select ContactID, FirstName, LastName from dbo.Contact where 1=2 Also insure that the Entity created in the SSDL uses the SQL DataTypes and not .NET DataTypes. If you are unable to open the EDMX file in the designer then note the Errors ... they will give precise info on what is wrong. The Thrid option is to simply create a Native Query in the SSDL using <Function Name="PaymentsforContact" IsComposable="false">   <CommandText>SELECT ActivityId, Activity AS ActivityName, ImagePath, Category FROM dbo.Activities </CommandText></FuncTion> Then map this Function to a existing Entity. This is a quick way to get a custom Entity which is regular Entity with renamed columns or additional columns (which are computed columns). The disadvantage to using this is that It will return all the rows from the Defining query and any filter (if defined) will be applied only at the Client side (after getting all the rows from DB). If you you DefiningQuery instead then we can use that as a Composable Query. The Fourth option (for mapping a READ stored proc results to a non-existent Entity) is to create a View in the Database which returns all the fields that the sproc also returns, then update the Model so that the model contains this View as a Entity. Then map the Read Sproc to this View Entity. The other option would be to simply create the View and remove the sproc altogether. ================================================================ To Execute a SProc that does not return a entity, use a EntityCommand to execute that proc. You cannot call a sproc FunctionImport that does not return Entities From Code, the only way is to use SSDL function calls using EntityCommand.  This changes with EntityFramework Version 4 where you can return Scalar Types, Complex Types, Entities or NonQuery ================================================================ UDF when created as a Function in SSDL, we need to set the Name & IsComposable properties for the Function element. IsComposable is always false for Sprocs, for UDF's set this to true. You cannot call UDF "Function" from within code since you cannot import a UDF Function into the CSDL Model (with Version 1 of EF). only stored procedures can be imported and then mapped to a entity ================================================================ Entity Framework requires properties that are involved in association mappings to be mapped in all of the function mappings for the entity (Insert, Update and Delete). Because Payment has an association to Reservation... hence we need to pass both the paymentId and reservationId to the Delete sproc even though just the paymentId is the PK on the Payment Table. ================================================================ When mapping insert, update and delete procs to a Entity, insure that all the three or none are mapped. Further if you have a base class and derived class in the CSDL, then you must map (ins, upd, del) sprocs to all parent and child entities in the inheritance relationship. Note that this limitation that base and derived entity methods must all must be mapped does not apply when you are mapping Read Stored Procedures.... ================================================================ You can write stored procedures SQL directly into the SSDL by creating a Function element in the SSDL and then once created, you can map this Function to a CSDL Entity directly in the designer during Function Import ================================================================ You can do Entity Splitting such that One Entity maps to multiple tables in the DB. For e.g. the Customer Entity currently derives from Contact Entity...in addition it also references the ContactPersonalInfo Entity. One can copy all properties from the ContactPersonalInfo Entity into the Customer Entity and then Delete the CustomerPersonalInfo entity, finall one needs to map the copied properties to the ContactPersonalInfo Table in Table Mapping (by adding another table (ContactPersonalInfo) to the Table Mapping... this is called Entity Splitting. Thus now when you insert a Customer record, it will automatically create SQL to insert records into the Contact, Customers and ContactPersonalInfo tables even though you have a Single Entity called Customer in the CSDL =================================================================== There is Table by Type Inheritance where another EDM Entity can derive from another EDM entity and absorb the inherted entities properties, for example in the Break Away Geek Adventures EDM, the Customer entity derives (inherits) from the Contact Entity and absorbs all the properties of Contact entity. Thus when you create a Customer Entity in Code and then call context.SaveChanges the Object Context will first create the TSQL to insert into the Contact Table followed by a TSQL to insert into the Customer table =================================================================== Then there is the Table per Hierarchy Inheritance..... where different types are created based on a condition (similar applying a condition to filter a Entity to contain filtered records)... the diference being that the filter condition populates a new Entity Type (derived from the base Entity). In the BreakAway sample the example is Lodging Entity which is a Abstract Entity and Then Resort and NonResort Entities which derive from Lodging Entity and records are filtered based on the value of the Resort Boolean field =================================================================== Then there is Table per Concrete Type Hierarchy where we create a concrete Entity for each table in the database. In the BreakAway sample there is a entity for the Reservation table and another Entity for the OldReservation table even though both the table contain the same number of fields. The OldReservation Entity can then inherit from the Reservation Entity and configure the OldReservation Entity to remove all Scalar Properties from the Entity (since it inherits the properties from Reservation and filters based on ReservationDate field) =================================================================== Complex Types (Complex Properties) Entities in EF can also contain Complex Properties (in addition to Scalar Properties) and these Complex Properties reference a ComplexType (not a EntityType) DropdownList, ListBox, RadioButtonList, CheckboxList, Bulletedlist are examples of List server controls (not data bound controls) these controls cannot use Complex properties during databinding, they need Scalar Properties. So if a Entity contains Complex properties and you need to bind those to list server controls then use projections to return Scalar properties and bind them to the control (the disadvantage is that projected collections are not tracked by the Object Context and hence cannot persist changes to the projected collections bound to controls) ObjectDataSource and EntityDataSource do account for Complex properties and one can bind entities with Complex Properties to Data Source controls and they will be tracked for changes... with no additional plumbing needed to persist changes to these collections bound to controls So DataBound controls like GridView, FormView need to use EntityDataSource or ObjectDataSource as a datasource for entities that contain Complex properties so that changes to the datasource done using the GridView can be persisted to the DB (enabling the controls for updates)....if you cannot use the EntityDataSource you need to flatten the ComplexType Properties using projections With EF Version 4 ComplexTypes are supported by the Designer and can add/remove/compose Complex Types directly using the Designer =================================================================== Conditional Mapping ... is like Table per Hierarchy Inheritance where Entities inherit from a base class and then used conditions to populate the EntitySet (called conditional Mapping). Conditional Mapping has limitations since you can only use =, is null and IS NOT NULL Conditions to do conditional mapping. If you need more operators for filtering/mapping conditionally then use QueryView(or possibly Defining Query) to create a readonly entity. QueryView are readonly by default... the EntitySet created by the QueryView is enabled for change tracking by the ObjectContext, however the ObjectContext cannot create insert/update/delete TSQL statements for these Entities when SaveChanges is called since it is QueryView. One way to get around this limitation is to map stored procedures for the insert/update/delete operations in the Designer. =================================================================== Difference between QueryView and Defining Query : QueryView is defined in the (MSL) Mapping File/section of the EDM XML, whereas the DefiningQuery is defined in the store schema (SSDL). QueryView is written using Entity SQL and is this database agnostic and can be used against any database/Data Layer. DefiningQuery is written using Database Lanaguage i.e. TSQL or PSQL thus you have more control =================================================================== Performance: Lazy loading is deferred loading done automatically. lazy loading is supported with EF version4 and is on by default. If you need to turn it off then use context.ContextOptions.lazyLoadingEnabled = false To improve Performance consider PreCompiling the ObjectQuery using the CompiledQuery.Compile method

    Read the article

  • Developing Spring Portlet for use inside Weblogic Portal / Webcenter Portal

    - by Murali Veligeti
    We need to understand the main difference between portlet workflow and servlet workflow.The main difference between portlet workflow and servlet workflow is that, the request to the portlet can have two distinct phases: 1) Action phase 2) Render phase. The Action phase is executed only once and is where any 'backend' changes or actions occur, such as making changes in a database. The Render phase then produces what is displayed to the user each time the display is refreshed. The critical point here is that for a single overall request, the action phase is executed only once, but the render phase may be executed multiple times. This provides a clean separation between the activities that modify the persistent state of your system and the activities that generate what is displayed to the user.The dual phases of portlet requests are one of the real strengths of the JSR-168 specification. For example, dynamic search results can be updated routinely on the display without the user explicitly re-running the search. Most other portlet MVC frameworks attempt to completely hide the two phases from the developer and make it look as much like traditional servlet development as possible - we think this approach removes one of the main benefits of using portlets. So, the separation of the two phases is preserved throughout the Spring Portlet MVC framework. The primary manifestation of this approach is that where the servlet version of the MVC classes will have one method that deals with the request, the portlet version of the MVC classes will have two methods that deal with the request: one for the action phase and one for the render phase. For example, where the servlet version of AbstractController has the handleRequestInternal(..) method, the portlet version of AbstractController has handleActionRequestInternal(..) and handleRenderRequestInternal(..) methods.The Spring Portlet Framework is designed around a DispatcherPortlet that dispatches requests to handlers, with configurable handler mappings and view resolution, just as the DispatcherServlet in the Spring Web Framework does.  Developing portlet.xml Let's start the sample development by creating the portlet.xml file in the /WebContent/WEB-INF/ folder as shown below: <?xml version="1.0" encoding="UTF-8"?> <portlet-app version="2.0" xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <portlet> <portlet-name>SpringPortletName</portlet-name> <portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class> <supports> <mime-type>text/html</mime-type> <portlet-mode>view</portlet-mode> </supports> <portlet-info> <title>SpringPortlet</title> </portlet-info> </portlet> </portlet-app> DispatcherPortlet is responsible for handling every client request. When it receives a request, it finds out which Controller class should be used for handling this request, and then it calls its handleActionRequest() or handleRenderRequest() method based on the request processing phase. The Controller class executes business logic and returns a View name that should be used for rendering markup to the user. The DispatcherPortlet then forwards control to that View for actual markup generation. As you can see, DispatcherPortlet is the central dispatcher for use within Spring Portlet MVC Framework. Note that your portlet application can define more than one DispatcherPortlet. If it does so, then each of these portlets operates its own namespace, loading its application context and handler mapping. The DispatcherPortlet is also responsible for loading application context (Spring configuration file) for this portlet. First, it tries to check the value of the configLocation portlet initialization parameter. If that parameter is not specified, it takes the portlet name (that is, the value of the <portlet-name> element), appends "-portlet.xml" to it, and tries to load that file from the /WEB-INF folder. In the portlet.xml file, we did not specify the configLocation initialization parameter, so let's create SpringPortletName-portlet.xml file in the next section. Developing SpringPortletName-portlet.xml Create the SpringPortletName-portlet.xml file in the /WebContent/WEB-INF folder of your application as shown below: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="pointManager" class="com.wlp.spring.bo.internal.PointManagerImpl"> <property name="users"> <list> <ref bean="point1"/> <ref bean="point2"/> <ref bean="point3"/> <ref bean="point4"/> </list> </property> </bean> <bean id="point1" class="com.wlp.spring.bean.User"> <property name="name" value="Murali"/> <property name="points" value="6"/> </bean> <bean id="point2" class="com.wlp.spring.bean.User"> <property name="name" value="Sai"/> <property name="points" value="13"/> </bean> <bean id="point3" class="com.wlp.spring.bean.User"> <property name="name" value="Rama"/> <property name="points" value="43"/> </bean> <bean id="point4" class="com.wlp.spring.bean.User"> <property name="name" value="Krishna"/> <property name="points" value="23"/> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages"/> </bean> <bean name="/users.htm" id="userController" class="com.wlp.spring.controller.UserController"> <property name="pointManager" ref="pointManager"/> </bean> <bean name="/pointincrease.htm" id="pointIncreaseController" class="com.wlp.spring.controller.IncreasePointsFormController"> <property name="sessionForm" value="true"/> <property name="pointManager" ref="pointManager"/> <property name="commandName" value="pointIncrease"/> <property name="commandClass" value="com.wlp.spring.bean.PointIncrease"/> <property name="formView" value="pointincrease"/> <property name="successView" value="users"/> </bean> <bean id="parameterMappingInterceptor" class="org.springframework.web.portlet.handler.ParameterMappingInterceptor" /> <bean id="portletModeParameterHandlerMapping" class="org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping"> <property name="order" value="1" /> <property name="interceptors"> <list> <ref bean="parameterMappingInterceptor" /> </list> </property> <property name="portletModeParameterMap"> <map> <entry key="view"> <map> <entry key="pointincrease"> <ref bean="pointIncreaseController" /> </entry> <entry key="users"> <ref bean="userController" /> </entry> </map> </entry> </map> </property> </bean> <bean id="portletModeHandlerMapping" class="org.springframework.web.portlet.handler.PortletModeHandlerMapping"> <property name="order" value="2" /> <property name="portletModeMap"> <map> <entry key="view"> <ref bean="userController" /> </entry> </map> </property> </bean> </beans> The SpringPortletName-portlet.xml file is an application context file for your MVC portlet. It has a couple of bean definitions: viewController. At this point, remember that the viewController bean definition points to the com.ibm.developerworks.springmvc.ViewController.java class. portletModeHandlerMapping. As we discussed in the last section, whenever DispatcherPortlet gets a client request, it tries to find a suitable Controller class for handling that request. That is where PortletModeHandlerMapping comes into the picture. The PortletModeHandlerMapping class is a simple implementation of the HandlerMapping interface and is used by DispatcherPortlet to find a suitable Controller for every request. The PortletModeHandlerMapping class uses Portlet mode for the current request to find a suitable Controller class to use for handling the request. The portletModeMap property of portletModeHandlerMapping bean is the place where we map the Portlet mode name against the Controller class. In the sample code, we show that viewController is responsible for handling View mode requests. Developing UserController.java In the preceding section, you learned that the viewController bean is responsible for handling all the View mode requests. Your next step is to create the UserController.java class as shown below: public class UserController extends AbstractController { private PointManager pointManager; public void handleActionRequest(ActionRequest request, ActionResponse response) throws Exception { } public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws ServletException, IOException { String now = (new java.util.Date()).toString(); Map<String, Object> myModel = new HashMap<String, Object>(); myModel.put("now", now); myModel.put("users", this.pointManager.getUsers()); return new ModelAndView("users", "model", myModel); } public void setPointManager(PointManager pointManager) { this.pointManager = pointManager; } } Every controller class in Spring Portlet MVC Framework must implement the org.springframework.web. portlet.mvc.Controller interface directly or indirectly. To make things easier, Spring Framework provides AbstractController class, which is the default implementation of the Controller interface. As a developer, you should always extend your controller from either AbstractController or one of its more specific subclasses. Any implementation of the Controller class should be reusable, thread-safe, and capable of handling multiple requests throughout the lifecycle of the portlet. In the sample code, we create the ViewController class by extending it from AbstractController. Because we don't want to do any action processing in the HelloSpringPortletMVC portlet, we override only the handleRenderRequest() method of AbstractController. Now, the only thing that HelloWorldPortletMVC should do is render the markup of View.jsp to the user when it receives a user request to do so. To do that, return the object of ModelAndView with a value of view equal to View. Developing web.xml According to Portlet Specification 1.0, every portlet application is also a Servlet Specification 2.3-compliant Web application, and it needs a Web application deployment descriptor (that is, web.xml). Let’s create the web.xml file in the /WEB-INF/ folder as shown in listing 4. Follow these steps: Open the existing web.xml file located at /WebContent/WEB-INF/web.xml. Replace the contents of this file with the code as shown below: <servlet> <servlet-name>ViewRendererServlet</servlet-name> <servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ViewRendererServlet</servlet-name> <url-pattern>/WEB-INF/servlet/view</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> The web.xml file for the sample portlet declares two things: ViewRendererServlet. The ViewRendererServlet is the bridge servlet for portlet support. During the render phase, DispatcherPortlet wraps PortletRequest into ServletRequest and forwards control to ViewRendererServlet for actual rendering. This process allows Spring Portlet MVC Framework to use the same View infrastructure as that of its servlet version, that is, Spring Web MVC Framework. ContextLoaderListener. The ContextLoaderListener class takes care of loading Web application context at the time of the Web application startup. The Web application context is shared by all the portlets in the portlet application. In case of duplicate bean definition, the bean definition in the portlet application context takes precedence over the Web application context. The ContextLoader class tries to read the value of the contextConfigLocation Web context parameter to find out the location of the context file. If the contextConfigLocation parameter is not set, then it uses the default value, which is /WEB-INF/applicationContext.xml, to load the context file. The Portlet Controller interface requires two methods that handle the two phases of a portlet request: the action request and the render request. The action phase should be capable of handling an action request and the render phase should be capable of handling a render request and returning an appropriate model and view. While the Controller interface is quite abstract, Spring Portlet MVC offers a lot of controllers that already contain a lot of the functionality you might need – most of these are very similar to controllers from Spring Web MVC. The Controller interface just defines the most common functionality required of every controller - handling an action request, handling a render request, and returning a model and a view. How rendering works As you know, when the user tries to access a page with PointSystemPortletMVC portlet on it or when the user performs some action on any other portlet on that page or tries to refresh that page, a render request is sent to the PointSystemPortletMVC portlet. In the sample code, because DispatcherPortlet is the main portlet class, Weblogic Portal / Webcenter Portal calls its render() method and then the following sequence of events occurs: The render() method of DispatcherPortlet calls the doDispatch() method, which in turn calls the doRender() method. After the doRenderService() method gets control, first it tries to find out the locale of the request by calling the PortletRequest.getLocale() method. This locale is used while making all the locale-related decisions for choices such as which resource bundle should be loaded or which JSP should be displayed to the user based on the locale. After that, the doRenderService() method starts iterating through all the HandlerMapping classes configured for this portlet, calling their getHandler() method to identify the appropriate Controller for handling this request. In the sample code, we have configured only PortletModeHandlerMapping as a HandlerMapping class. The PortletModeHandlerMapping class reads the value of the current portlet mode, and based on that, it finds out, the Controller class that should be used to handle this request. In the sample code, ViewController is configured to handle the View mode request so that the PortletModeHandlerMapping class returns the object of ViewController. After the object of ViewController is returned, the doRenderService() method calls its handleRenderRequestInternal() method. Implementation of the handleRenderRequestInternal() method in ViewController.java is very simple. It logs a message saying that it got control, and then it creates an instance of ModelAndView with a value equal to View and returns it to DispatcherPortlet. After control returns to doRenderService(), the next task is to figure out how to render View. For that, DispatcherPortlet starts iterating through all the ViewResolvers configured in your portlet application, calling their resolveViewName() method. In the sample code we have configured only one ViewResolver, InternalResourceViewResolver. When its resolveViewName() method is called with viewName, it tries to add /WEB-INF/jsp as a prefix to the view name and to add JSP as a suffix. And it checks if /WEB-INF/jsp/View.jsp exists. If it does exist, it returns the object of JstlView wrapping View.jsp. After control is returned to the doRenderService() method, it creates the object PortletRequestDispatcher, which points to /WEB-INF/servlet/view – that is, ViewRendererServlet. Then it sets the object of JstlView in the request and dispatches the request to ViewRendererServlet. After ViewRendererServlet gets control, it reads the JstlView object from the request attribute and creates another RequestDispatcher pointing to the /WEB-INF/jsp/View.jsp URL and passes control to it for actual markup generation. The markup generated by View.jsp is returned to user. At this point, you may question the need for ViewRendererServlet. Why can't DispatcherPortlet directly forward control to View.jsp? Adding ViewRendererServlet in between allows Spring Portlet MVC Framework to reuse the existing View infrastructure. You may appreciate this more when we discuss how easy it is to integrate Apache Tiles Framework with your Spring Portlet MVC Framework. The attached project SpringPortlet.zip should be used to import the project in to your OEPE Workspace. SpringPortlet_Jars.zip contains jar files required for the application. Project is written on Spring 2.5.  The same JSR 168 portlet should work on Webcenter Portal as well.  Downloads: Download WeblogicPotal Project which consists of Spring Portlet. Download Spring Jars In-addition to above you need to download Spring.jar (Spring2.5)

    Read the article

< Previous Page | 1 2 3 4