I would like to move some SQL code from the aspx page to the code behind page. The SQL code is bound to a DataSource object.
I am unsure whether to add this code to OnInit, or to PageLoad. Does it matter which one, or is there a better place to put it than another? I would think OnInit would make more sense since I am binding the Select/Update commands and parameters prior to actually using them with an active connection.
Init is better. This is where control properties are set anyway so you will get the closest thing to setting them in markup. On a side note my advice is that you move to ObjectDataSource and extract the Data Access code from your code behind as well. Your markup + code behind are equivalent to the View in MVC terms and data access code does not belong there. If you are doing serious refactoring it may be worth looking into the MVP pattern. With this pattern you get MVC equivalent separation of concerns and testability with Web Forms. In fact MVP is a kind of MVC pattern.
Related
I'm fairly new to ASP.NET and programming in general, and one of the problems I'm currently struggling to grasp is reducing repetitive code.
My goal is to have a master page that contains a grid view, then numerous pages can contain the grid. However, I want to be able to share code between my grids but at the same time be able to adapt unique code to each and everyone of them as some will have different attributes and data.
I've looked into separation of concerns, and other various posts/blogs but haven't found a definitive answer to how I can actually achieve what I want.
I've already tried using master pages and it worked quite well until my application continued to expand, plus I'd prefer to only use my master pages for presentation.
Could anyone provide a simple example of how I can achieve this?
Happy to provide additional information!
After spending the day doing research and testing numerous possibilities I've pretty much answered my own question.
I've setup a master page that contains the grid, the content page then retrieves the grid using accessors. This grid is then set to a property in the base class which makes it accessible where I need it to be.
edit
Event handlers were created to handle the grid events in the content pages, then those methods were overridden to allow the calls to bubble up to the base class thus allowing me to assign unique, page specific and common code where I needed it to be.
Sorry for the vague title. I am pretty ashamed to ask this but I really need my awareness right now. I cannot identify whether I am following an MVC pattern or MVVM pattern.
In my previous internship, we had C# code (.NET) which had a controller and connected directly to the database (there wasn't a service layer). The controller would fetch information, format into JSON and give it to Angular's controller, which would display it on the view.
In my current internship, we don't use Angular. We use .cshtml files. The service layer provides its information to the controller, which formats the MODEL and gives it to the .cshtml view and which displays the content.
My questions:
Which one is MVC and which one is MVVM? Please drop down to my level and explain. Most of what I've read on the web seems to confuse me more with what I observe at work.
Everyone at work calls both of them MVC and, I am really confused now. If both are MVC, what's the difference between the two?
Angular is definitely more Model-View-ViewModel-ish. Whereas what you're doing now definitely sounds like MVC.
MVVM is a special pattern where the UI state is encapsulated in a ViewModel, so that the rendering of the final UI is fairly dumb and just data-binding. The state logic to say, show this button, or hide this area is all encapsulated in the ViewModel. One benefit, is that this allows for unit tests to be built to test the ViewModel and thereby implicitly testing all of the UI behaviors. (see: Wikipedia article on MVVM and Martin Fowler's Introduction to Presentation Model which MVVM is a variation of.)
In MVC, the view itself has the latitude to control it's behaviors, what you want to show/hide, etc based off of the data provided, the model. This means that in MVC, you can't test the UI behaviors (e.g. if something is correctly showing or hiding based on data changes) without testing the UI itself.
So in summary, MVVM, the ViewModel controls the UI behavior and the UI itself is dumb and just uses data-binding and does what it's told to do based on the logic in the ViewModel.
In MVC, the UI is 'intelligent' and re-shapes and renders itself however it feels it needs to based on the data it receives from the model.
You can basically look at how the UI is rendered and if you see the UI rendering logic making a lot of its own decisions about how to render itself based on the decision, then you pretty much know you're using MVC. If you just see a lot of data-binding, where almost every behavior is driven by a separate class that encapsulates all of the logic for showing and hiding pieces of the UI and this data is passed to the UI via data-binding, then it's probably MVVM.
I hope that helps.
In both cases, you are using MVC (or at least an MVC-ish pattern). When using the .cshtml files, you are using server-side MVC. When using Angular, you are using client-side MVC (which is probably more like MVVM). The biggest difference is where the model is rendered into HTML elements; on the client, or on the server.
In my opinion, this is a better way to view the differences in what you have done.
I have a WPF application implemented using MVVM. But for some small operations, such as scroll, confirmation box button click, left click operation, right click operation, etc, I am using click events directly in views.
I know MVVM does not recommend this, but is it ok to have such click events or its a bad coding practice while using MVVM? What are pros and cons of using this?
the MVVM pattern gives you:
Seperation of concerns (which is true for all UI patterns)
Unit testing of view logic, by executing the view-model without the view.
Developer-Designer workflow, allowing designers using Blend to work on the same code.
If handling UI events in code behind doesn't prohibit the above, then there is no problem. Personally I use commands if I can, but am not concerned if there is a little code-behind required.
Events can be used, but the problem with allowing codebehind events is that it's a slippery slope. you add one thing, then you add another, and all of a sudden you create actual logic in the codebehind class. (It's even more prominent if you are working with other less experienced programmers in your team).
That's why some programmers prefer, to almost no exceptions, to not write codebehind AT ALL.
Every code that fits the codebehind without being really application-logic code can also be written within a Behavior, which makes the architecture much more strict and simple to define.
If your button does something that is specific to your UI then yes you should use event handlers over commands.
e.g. If you have a button that scrolls a ScrollViewer control to the bottom then it would be bad practice to use an MVVM style command as your ViewModel would need knowledge and direct control of the view. For these situations the view should be self contained.
If your button needs to do something with data then you should use a command and perform the operation in the ViewModel.
I fully agree with #Noam M. Just to extend his answer:
Whether it's violation of MVVM or not depends on what you acually do in eventhandlers. If it's logic that is covered by the view responsibility, it's perfectly ok.
For example, PasswordBox password property cannot be databound, because it is not DependencyProperty and using PasswordChanged eventhander to set viewmodel property is perfectly ok. However, if you wrote password validation against server, that would be violation of mvvm.
I often use Loaded/Unloaded events to call Activate/Deactivate methods on my VM. When I use it too often I create behavior implemented as attached property, that does it for me, so I don't have to repeat the same code in code behind multiple times
I often use DataGrid's events in codebehind, like sorting etc.
I use TextBox.GotFocus event to select all text. Again, I create behavior when I need to reuse it.
I use codebehind to trigger, or create animations if it would be too complicated in xaml. In that case I just leave comment in xaml for other developers.
In MVVM application not all assets must be strictly written using MVVM. For example I have just written my ModalDialogWindow, where I inject content and buttons. I don't have viewmodel for this control and I do everything from codebehind. However, my application has solid MVVM architecture and I show modal dialogs from my page viewmodels using IDialogService. The ModalDialogWindow does not break testability, blendability, or readbility of my application, because in test I mock the IDialogService anyway and I don't need to test ModalDialogWindow UI itself.
I try to avoid code behind in views, within my WPF MVVM project.
However I have some things that are very specific to the view. For example when a control gets focus I want the full text to be highlighted (even if a user clicks into the text box).
Here I have a choice to handle this in the view model (which would then need to know about the view, which I want to avoid).
I also have some other code like that does things to the UI when the user presses up down left or right on the keyboard (and they only make changes to the view, not the model or viewmodel) and again I'm thinking the best place for these is in the code behind of the view.
So I'm asking if the code only affects the view (e.g. things like cursor movement, selecting all text in a text box etc..., and not the model or view model, is it okay to put it in code behind, rather than elsewhere.
Wondering what is best practise here, or if anyone else has a better suggestion where to put this code.
So I'm asking if the code only affects the view (e.g. things like
cursor movement, selecting all text in a text box etc..., and not the
model or view model, is it okay to put it in code behind, rather than
elsewhere.
Not only it is OK, but it is strongly encouraged.
MVVM is not here for you to write thousands of ugly lines of code in ViewModels, it's here to make the code testable and to introduce a separation of concerns.
If it's purely related to the view (your "focus" example is a perfect example), then just write it in the code behind.
If the behavior is UI related only, then you should not put it in the ViewModel. The highlighting example you gave is a good example of such a case. Having said that, I would suggest you avoid repeating your code by (for example) creating a custom control that highlights the text when it has the focus. This way, you can reuse the control in as many views as you can, your views stay free of codebehind, and if you optimize your control, the optimizations happen across the board.
EDIT:
In light of Ravi's answer, Behaviors are also a way to introduce UI related logic while leaving the View free of codebehind. However, if you are finding yourself repeatedly declaring the same controls with the same behaviors, in my opinion it is better to create a control that incorporates the behavior.
That being said, if said UI logic is going to appear only once in one view, you may consider putting it in codebehind. Although it is quite rare to know in advance that you are not going to need that logic elsewhere.
EDIT:
I think #ken2k 's use of strong encouragement refers to not putting it in the ViewModel, which I also advocate. UI logic should be implemented in the View, as he says. Now, there are a few ways of doing that. One of these is coding it directly in your codebehind, which can lead to repetitious code and maintenance issues. Also, if you employ unit testing, it could put you in a difficult spot. The second is coding such logic into behaviors, which is a good way to encapsulate UI code. You can then unit test the behavior to make sure it works OK. However, you can find (as I did, in many projects) that you have started to pepper every TextBox in your XAML's with behavior tags. If that starts to happen, I would (and have) create a 'HighlightedTextBox' control and use that in my XAML. In summary, my suggestion does not contradict ken2k's, but is a pointer in the direction of resolving some issues you may have when placing logic for your View.
Using Custom controls as #Boluc Papuccuoglu suggested, is good option but before using that i want you to take look here Behaviors in WPF introduction
It is strongly recommended to have all your view stuff logic at one place. Instead of polluting ViewModel you should always keep View stuffs in XAML and code behind.
ViewModel responsibility is to contain only data part which can be unit tested. With UI stuff in ViewModel, you will make it hard to be unit tested.
As per link here at MSDN, definition of code behind:
Code-behind is a term used to describe the code that is joined with
markup-defined objects, when a XAML page is markup-compiled.
As you can see, code behind is partial class of your view. One half is declared via x:Class attribute at root element and other half in form of code behind. So, as per me all UI stuff should be at one place and you should not think twice before placing the view stuff in code behind. (that's what it is meant for). MVVM never meant design without any code behind.
Also ViewModel responsibility is to just provide data to your view via data binding. It should never be aware of UI stuff.
Read more about it here - Code behind and XAML in WPF.
How much of your code do you want to unit test? If your view can trigger a command when a control gets focus and your view model can programatically fire an event to highlight the text in that control then you have everything you need to unit test that behaviour with mocked objects. And even if you don't want to unit test (or can't because the bean-counters at your company won't give you the time/budget to do so) then placing that functionality in attached behaviours means they can be used elsewhere. I'm not quite the hard-core MVVM purist as some others on this site but I can honestly say that even in the largest enterprise applications I've worked on I've never once seen a case where WPF code-behind was absolutely required.
I use update panels all the time when i wanna to update specific part of my page but recently i face performance problems ( i mean it 's slow in rendering the intended control and sometimes it doesn't work and need multiple click to work !!
so my question is :
Is the page method could be considered as an efficient alternative to
the update panel and do the ajax magic ?
What are the other alternatives?
please if possible a simple example to clarify how to replace the update panel using with page methods ?
I used to be like you some years ago, I used to use UpdatePanel to gain performance, to have the wrong idea I was increasing the performance of my applications...
Well I was totally wrong, UpdatePanel is the root of all UI-evil, first of all it hides the complexity of using AJAX which makes it easy for most of us, giving us the wrong idea that we are creating responsive applications, which is worst than if we weren't using it at all (that's the main reason I used to use it in all my pages, and I am sure that's the reason why many developers use it... 'cos it's easy).
Consider the following articles:
Why you should not place your whole site in an UpdatePanel
UpdatePanel is evil
When you understand what the UpdatePanel really does against a simple call to a PageMethod or a REST WCF Service, you will see the huge difference between them.
UpdatePanel. When you perform a post from an UpdatePanel, the whole page life-cycle has to be executed, this means, it requires to send all the page ViewState on each post, when your page grows in complexity with several controls, the ViewState will certainly be huge and this will certainly be a performance issue. Using them you only gain partial rendering, the controls inside your UpdatePanel will be rendered without a full post back although you need to send the whole ViewState on each request.
PageMethod. Page methods are static, they are called like if they were a service method, they do not need to create the whole page life-cycle in order to be executed, therefore, they execute faster.
So it would seem that using PageMethods would be the solution, the problem is that PageMethods are usually used to return JSON objects which means, that you will have to render these objects manually. This means that if you want to get rid-off all your UpdatePanel you will have to change the controls used in your views, you won't be able to use the GridView out-of-the-box for example, instead you would have to change it for the JQGrid (or similars).
This is natural if you are creating a MVC application, but with traditional ASP.Net this is not straightforward.
You also need to consider something very important, the ViewState is validated by default on each post, you can turn it off, but it is not recommended if you want to be sure your ViewState has not been corrupted (take a look at this question).
Consider this example, you have two DropDownList controls, (named: ddl1, ddl2) ddl2 depends on ddl1 so using the SelectedIndexChanged event you fill the second drop down list. But if you attempt to do the same using AJAX calls (without an UpdatePanel), you will face two problems
Rendering, you need to manually add objects to the HTML select control representing the DropDownList. You could use a third party framework to bind these controls using javascript, I can recommend you knockoutjs (it's awesome)
This is the problem. After you have changed the content of the second DropDownList using javascript, you cannot do a simple post to your page because the ViewState will not be valid, and you will see the following exception:
Invalid postback or callback argument.
The workaround is to specify which values will be valid in the server side, in order to do that you need to override the page Render method and specify each one of the values of the second drop down list, but this will increase the page size and obviously, this is not a good option
Take a look:
ASP.NET Event Validation and “Invalid Callback Or Postback Argument” : Part I
ASP.NET Event Validation and “Invalid Callback Or Postback Argument” : Part II
So as a summary, if you want to get rid-off all your UpdatePanel controls, you will need to replace the existing server controls for javascript-friendly controls. Also remmeber that if you do that, instead of relying on the page post mechanism, you would have to use AJAX to perform operations on the server, otherwise, you will get the Invalid postback or callback argument. exception. In other words it would be better to consider moving to a MVC application if possible.
There is an alternative to UpdatePanels, but still using PageMethods. It is a combination between jQuery and jQuery templates. It is proven to be faster than the UpdatePanels. Further reading on the resource below, where you can find more articles dedicated to this topic.
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/
You might read about the coming WebAPI in .NET 4.5. It's for WebForms as well as MVC and may be a viable solution to your problem if you can wait on 4.5.
Just use it in combination with any jQuery template engine.
http://weblogs.asp.net/scottgu/archive/2012/02/23/asp-net-web-api-part-1.aspx
Have a look at http://uframe.codeplex.com/