Execute Powershell in ASP MVC - asp.net

Do any out there know how to Execute Powershell code on ASP MVC 5? Or maybe some link to a guide.
I know this guide but the writter use ASP Web Form, I'm new using MVC (actually ASP in general) so is kind of hard to transalte the stuff.
Guide: http://jeffmurr.com/blog/?p=142

This article tells pretty much everything.
If you are unfamiliar with ASP.NET MVC, I'd advise you to go through the basics first. Then everything should become way clearer.
Instead of using ExecuteCode_Click to execute your script, you need to create a controller and some action in it and put the code in there.
Action should accept a string value with your script, do the processing, and return the result a ViewResult with script result as a property on your model.
The view could then render the result as you see fit (eg. inside an HTML textbox).

Related

Could I create ASP.net page method in web form code behind file?

Could I declare asp.net page method in side Web form code behind file using [System.Web.Services.WebMethod] attribute?
Yes, you can add the code inline if you want - it's pretty messy though. Take a look at this blog post for help. Also, take a look at this MSDN reference for a comparison. There is also another tutorial here.
In my opinion, if you need to use webforms, then you should stick to the code behind model and keep the minimum about of code in there for the event handlers only. Move any business logic, or utility code into separate classes.

How unit testing is better in ASP.NET MVC than Web Forms?

I have just started to learn ASP.NET MVC. When comparing ASP.NET MVC with Web Forms one of the main advantage of MVC is always told to be better support of Unit Testing. Can I got a good explanation of how it has better support?
Edit :
If possible please provide example in both.
Asp.Net MVC has better unit testing support for one main reason - the whole architecture is built to use HttpContextBase, HttpRequestBase and HttpResponseBase.
Asp.Net webforms is dependent on HttpContext.Current, which is a singleton that you have no control over - it is set up and passed to your pages as part of the HttpApplication executing the request. In most cases, in order to get the page to execute correctly, you need to execute it in a real HttpContext. Since many of the properties of HttpContext are not settable (like Request and Response), it is extremely difficult to construct fake requests to send to your page objects.
This makes unit testing webforms pages a nightmare, since it couples all your tests to needing all kinds of context setup.
Contrast that to ASP.Net MVC, where you can mock an HttpContext! Now your code doesn't even need a web server to give it context, you can just set up the bits you need, and hand the mocked context to your method.
The ASP.NET page lifecycle makes it incredibly difficult to unit test classes that derive from Page, which starts out with too many responsibilities and becomes a god object when you add application logic to it. Even worse, it has hidden dependencies on static classes and requires a default parameterless constructor, which limits your ability to inject dependencies.
So, to make an ASP.NET WebForms page testable, you need to take all the logic out of your code-behinds and put it in another class - typically a Presenter as in the Model-View-Presenter pattern.
ASP.NET MVC controllers are already separated from their templates and aren't encumbered by the ASP.NET page lifecycle.
Because you can create a controller object in your unit test, call some actions on it, and see the result right away, then you can Assert.IsBlahBlahBlah(); on it.
For example,
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
Assert.IsNotNull(result);
}
With that method, you now know that your Index view is returned from the Home controller.
If you want to use ASP.Net WebForms (like i do) and unit tests together, take a look at this:
WebForms MVP on codeplex
Works for me.
It's far more cumbersome to test a code behind page than to test a controller. With the MVC pattern, there's a more logical separation of presentation logic thus making it easier to write tests.
You can do exactly the same thing with Web Forms, it's just that people who don't know better write code that can't be tested this way.
There's no reason to have business logic in a codebehind class. Same with data access logic. Even right there, that lets you test the parts of the application most subject to both bugs and testing.
Some might say that doesn't allow you to test for button clicks and other user-interface events. If you want to do that, then you can go ahead and create your own MVC or MVP or other such pattern, that does use a separate interface for the user interface actions. Then do exactly the same kind of test you'd do if using ASP.NET MVC.
And you still have the problem of not being able to test client-side code.
Slightly OT but you may want to look at Selenium for Unit Testing webpages....
In reference to Lawrences suggestion about Selenium, there is also WatiN.
This is not specific to MVC, but I think MVC definitely helps in that it keeps element ids and classes clean and easier to target from the test.
With WatiN you can do the following (example from their site).
[Test]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
}
}

Running ASP / ASP.NET markup outside of a web application (perhaps with MVC)

Is there a way to include some aspx/ascx markup in a DLL and use that to generate text dynamically? I really just want to pass a model instance to a view and get the produced html as a string. Similar to what you might do with an XSLT transform, except the transform input is a CLR object rather than an XML document. A second benefit is using the ASP.NET code-behind markup which is known by most team members.
One way to achieve this would be to load the MVC view engine in-process and perhaps have it use an ASPX file from a resource. It seems like I could call into just the ViewEngine somehow and have it generate a ViewEngineResult. I don't know ASP.NET MVC well enough though to know what calls to make.
I don't think this would be possible with classic ASP or ASP.NET as the control model is so tied to the page model, which doesn't exist in this case.
Using something like SparkViewEngine in isolation would be cool too, though not as useful since other team members wouldn't know the syntax. At that point I might as well use XSLT (yes I am looking for a clever way to avoid XSLT).
You can host ASP.NET Runtime in another application. See :- http://msdn.microsoft.com/en-us/magazine/cc188791.aspx
Also see http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp

Which ASP.NET Page event is the best place for this type of code?

I have a relatively simple page that will do most of its operations on the client side using Javascript or JQuery. However, initially I do need to retrieve some data from the DB server based on QueryString parameters.
I plan on passing this data in the form of a JSON string to the script by an old-fashioned ASP manner ( var severData = <%=MyPublicData %>) block where MyPublicData is defined in CodeBehind as:
Public string MyPublicData;
The question is, which event in the ASP.NET page lifecycle is the best for this? Page_Init ? Page_Load? Also, is it worth the effort to do this in ASP.NET MVC. I did look at this possiblity but it seemed a little too much for a simple page like this where I do more 90% of the work on the client. Any thoughts on this?
Page_Load is more appropriate, but either will work.
It's very difficult to say if MVC is more appropriate for you application than webforms without knowing more about the application. However, if you don't want to abstract away the traditional web model then I'd go with MVC.
This kind of simple property or field assignment can go anywhere in the lifecycle. For lack of any other reason, you might as well stick it in Page_Load, since that method is usually waiting for you in the code-behind anyway.
well, on the contrary, if it uses mostly javascript with jQuery, I would recommend you to use MVC. you will not have any problem with the ids for instance.
There are workaround to use jQuery with webforms, but it is never perfectly clean regarding selecting the DOM.
MVC : a single action method where you will retrieve your data (preferably from a small repository) and 1 view where you display your data with total control over your html elements.
and jQuery will just fit perfectly for your clientside work.
You can get either to work; you can write public variables/fields to the client in ASP.NET web forms, although MVC has an edge due to the way it renders the UI.
So for MyPublicData, you could assign it a value at any part of the lifecycle; you can assign it in code-behind to a label or something like that, or if it's JS markup you can write it out using Page.ClientScript.RegisterStartupScript or RegisterClientScriptBlock... so you have multiple options.
In MVC, you would assign the value in the controller and render it in the UI, or with JQuery you can do controller requests real easy with $.ajax.

What is the unit of reusability in .NET MVC apps?

In traditional ASP.NET Web Form applications, UserControls are a great way to encapsulate functionality so that it can be reused. However, UserControls don't fit well into the MVC model. They often make heavy use of ViewState and they blur the seperation of concerns that MVC promotes.
My question is, how do you best bundle a piece of functionality so it can be shared across MVC applications?
As an example, consider a from/to date-selector UserControl that:
allows a user to select two dates, either using a javascript overlay or by typing in day, month and year into seperate fields
can be configured to default to either today and tomorrow's dates or to dates of the developer's choosing
validates the dates that comes back from the user to ensure the from date is before the to date
exposes From and To properties that can be accessed by code-behind
How would I best build something like this in .NET MVC so that I can easily reuse it?
Note that to fully emulate User Control's functionality the MVC component would have to manage the submitted form data and validation - not just the presentation.
In general I would agree that user controls are nice in terms of encapsulating UI stuff, but I don't think too much has really changed in MVC. If I remember right re-using user controls across classic Asp.net projects was a pain and was never really the best way to truly create reusable components. Most UI toolkits that you bought for classic ASP.net didn't give you user controls, they gave you essentially server controls and javascript controls.
In your example, I would probably create or find a jquery (or ur framework of choice) plugin that did what you wanted on the client side. You could also build a C# wrapper around it similar to what Telerik did with some of the jquery UI controls. I do think that the word code-behind and even viewstate will disappear from your vocabulary the more you get into MVC.
If you look at what open source projects are out there for MVC you will get your answer in terms of what you should be doing.
The MVC Contrib app adds a lot of features by creating extension methods and helpers. Their grid control is a typical way to create a reusable component that you could use across projects
Telerik, created some extensions that wrap jquery controls and do asset management.
Finally I think if you look to the future, MVC has areas, which if I interpret it right will give you the ability to break your project apart into multiple smaller projects.
Besides what is already suggested, ASP.NET MVC v2 will have generic templated input controls, see here. You can read how other people do similar techniques, for example, here:
We have
exactly 1 method call for generating a
form element, “Html.InputFor”. As
part of that “InputFor”, it examines
an input specification, that collects
the PropertyInfo, any attributes, the
type, any modifiers called, and
selects an appropriate InputBuilder.
Call InputFor(p => p.Id) and Id is a
GUID? That creates a hidden input
element. Call InputFor(p =>
p.Customer.Address) and Address is a
complex type? That looks for a
partial with the same name of the type
Having considered the helpful answers from others, I will have a go at answering my own question.
It seems to me that the key difficulty with emulating UserControls in MVC is that they crosscut the concerns that MVC aims to seperate. The from/to date selector UserControl in my example incorporates elements of Model, View, Control and interation. UserControls' ability to bundle all this together is exactly the reason that they don't fit well into MVC.
That means that to create a psuedo-UserControl in MVC requires four seperate pieces:
A Model class - in this case an Interval class or similar
A PartialView that knows how to render the Model to HTML
A jQuery script to layer interactivity on top of the PartialView's HTML
A ModelBinder that can deserialise postdata into an instance of the Model class.
The ModelBinder is important because it deals with data coming back from the user. Without it, every Controller that wanted to display a to/from date selector in any of its Views would have to know how to assemble the six postdata fields - and how to cope if they were invalid or some were missing.
Two ways that I can think of. A partial view though this doesn't really transfer well from app to app because you are moving around ascx files. Not a big pain but not my flavour.
I prefer to use WebControls. They are super easy in mvc and all you need to do is reference the library in the project and possibly in your config file and there you go.
I think some of the answers have missed out on the postback functionality of controls. One way you could handle that is to pass any generic information via ViewData when rendering your partial view. That could then post back to its own control, which in turn could redirect to the UrlReferrer.
Its a little messy and use of UrlReferrer poses a security risk. But it is one way around the problem
You can create a jQuery plugin.
As user-controls provided in ASP.NET Webforms, MVC provide a lot of ways to make the controls and code that can be reused in other app.
Using Partials If your partial code have some C# logic and render the html using Razor/aspx code then it's bst to maintain them in razor file.
Write JavaScript Functionality as plugin If you maintain your code and write it as better as it can be used in other app then it would be a huge advantage for you. Next time when you work on other app just open this solution copy it and modify it. Write JavaScript code that can be used as plugin maybe take some more brainstorming.
Write Code As a Separate C# library If some code is too common for every app you make.for example you write a member authentication system or some global function (C#) that are used in every app you made then maintain them in a separate solution so it can be used in other app you made whenever you trying to make a new app in future.

Resources