ASP.net and WCF some clarification on "overriding" - c#

Recently I faced few interview questions.The interviewer asked the to give the detailed answer.
1)Can we override a WCF service (Its is not OOPS overriding) ?.Explain the reason on either end. (WCF Related).
2)Can we override Page events (Page_Load())?.Explain reason.(ASP.NET related).
3)What is the primary responsibility of Pre_Init( page) event ,apart from user preference
setting,skinning?
4) Can we override Static methods.Explain the reason.(C# related)
can anyone help me to understand the reasons?

You can't really override WCF service operations. If your Service Contract class has two Service Operation methods with the same name but different parameters (i.e. legitimate C# overloads), WCF will throw an InvalidOperationException when the service is started. If you really want to do this, you can change the exposed operation name of one of the methods in the OperationContract attribute:
[OperationContract(Name = "GetDataWithString")]
public string GetData(string input)
{
...
}
[OperationContract(Name = "GetDataWithNumber")]
public string GetData(int input)
{
...
}
You can override Page events in ASP.Net; this is pretty widely used and usually pretty crucial. You can either explicitly override the methods from the Page class your custom page inherits from, or you can name your methods in such a way that ASP.Net knows that they're to be treated as overrides. For example, declaring a method in a page's code-behind with the signature below will automatically override the Page_Init method.
void Page_Init(object sender, EventArgs e)
The Page_Init method is where ASP.Net starts tracking ViewState. This means that anything done to any of the page's controls is now marked as Dirty in the ViewState StateBag, and so will be base-64 encoded and sent down to the client in the ViewState hidden input field, and therefore sent back to the server on a postback. Changing controls' values before ViewState is being tracked will help stop ViewState getting too large. See this seminal article for more details.
Only class instance methods can be marked as virtual, as the compiler-created v-table is attached to class instances. Static class members are not attached to instances but to the class itself, therefore there's no way to override them. This article explains this in more detail, and gives some workarounds.

Related

windows store application page refresh

I am new to windows store application development and currently i am developing a news application and i want to refresh the page to get news updated. i stated developing the default layout which is given to us when starting a project and i am lost with the page dictionary because once the page is created. It gets save so is there a way to refresh a page!!! LoadState method is called when application runs for the first time when refresh is clicked the view get clear but all the data is saved in the dictionary according to my knowledge is there a easy way to clear data inside the groups and recall the methods so that the new data will get filled in.can some one please guide me with the relevant steps
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
this.DefaultViewModel["Groups"] = sampleDataGroups;
}
private void refresh(object sender, RoutedEventArgs e)
{
this.DefaultViewModel.Clear();
}
There is no excellent answer to this question. But let me talk you through some concepts. Of course, there is no refresh, and the reason for this is many fold. Refresh might be added to the Frame someday, but it's problematic right now.
Consider a navigation service
A good way to navigate in your app is to offload this work to a NavigationService class. This is a simple class that has (something like) custom GotoAppHub() and GotoItemDetail(Item) methods.
The purpose of these methods is not because navigation is difficult, it is because navigation can be centralized. It can check & create the Frame; rather than leaving this erroneously in App.xaml.cs.
If your view model wants to navigate to a page, it simply calls NavigationService.GotoItemDetail(item); to do it, passing the item. This is smart for a few reasons, let me talk you through them.
The first reason this is smart is because you may not want to navigate at all. In some cases navigation relies on data being loaded or the user having permissions. Using the navigation service lets you centralize both the navigation logic and the tests necessary to validate the action.
The second reason this is smart is it allows you to retain the parameter passed to the navigation request. Remember that the Frame does NOT serialize custom, complex types. As a result, passing item in this case is a bad practice. The navigation service can persist this parameter somewhere so the target view model can come pick it up. Moreover, it can persist it for your Refresh().
Consider a static repository class
When a view model is loaded, it should be unnecessary for it to know what previous view model caused it to load. Instead the view model should know what it is supposed to do. And to do its work, it needs data. Every view model can use the repository class to ask for the "current" record. That current record will be set by the navigation service when navigation occurs. In addition, the repository class knows what to do when there is no current record, fetching it should it need.
In addition to holding a reference to the current record, the repository class also understands persistence. What I mean is, when the app is loaded, it knows how to fill the lists. When the app is suspended, it knows how to save the data to a file or web service, or whatever you use. The view model, as a result, does not know this and is, as a result, simpler and easier to maintain.
Consider the Reload() method
It is in the navigation service where you need the reload method. Even more than that, it is only in the navigation service where the reload method can be most effective since the navigation service knows the current type and the current parameter value. The navigation service can store these values in local fields and the reload method can simple repeat the navigation.
Remember the back stack, however. This is like a browser's navigation and repeating the navigation will mean that the same page will exist twice and the GoBack() method you also have in your navigation service will not go back until you go back twice. The solution is simple, just remember to remove with Services.NavigationService.Instance.Frame.BackStack.Remove().
Remember the cost of loading
Sometimes when a page loads there is a considerable cost in loading the UI. This is because whatever you are doing isn't trivial. Calling the Reload() will cause the load of the page to repeat. This is a cost you simply cannot overcome. But, there might be dependencies on the loading of the page that should be bypassed. For example, you might initiate a web service operation when the page is loaded - and that operation should not be repeated. This is up to you to retain a static Boolean that indicates the page has already loaded. But it's important you do not forget it.
One more benefit of the repository
A few paragraphs above I mentioned that your navigation service is the one that can remember the last passed parameter for the reload method to work. If you have an internal rule that only the navigation service can write to the concurrency class then your navigation service doesn't really have to remember. It just has to remember the last navigated-to type. That's because the concurrency class will already have the reference to the item passed in. This is, however, not always useful. Sometimes reload is called to throw away the current changes, which means the current item needs to be reloaded or current changes must be flushed. This will all have to be custom, but I would feel bad if I didn't at least mention it.
Conclusion
This should only be taken as a recommendation. Having said that, I have described here the bulk of large, successful WPF and Windows apps in the marketplace. Using the MVVP pattern, the service pattern for navigation, the repository pattern for concurrency - it's all pretty well proven. But you are the developer. In the end, you should choose what is best.
If you don't like any of that, you can do this:
public bool Reload()
{
if (!this.Frame.BackStack.Any())
return false;
var current = this.Frame.BackStack.First();
this.Frame.BackStack.Remove(current);
return this.Frame.Navigate(current.SourcePageType, current.Parameter);
}
Best of luck!
How about:
private string parameter;
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
parameter = (string)navigationParameter;
reloadData();
}
private void reloadData()
{
var sampleDataGroups = SampleDataSource.GetGroups(parameter);
this.DefaultViewModel["Groups"] = sampleDataGroups;
}
private void refresh(object sender, RoutedEventArgs e)
{
reloadData()
}

Attempting to generalize a authentication (Including parameter changing)

In our MVC project we are attempting to make everything as generic as possible.
Because of this we want to have one authentication class/method which covers all our methods.
As a example: The following code is a MVC class which can be called to from a client
public class Test
{
public void Test()
{
}
public int Test2(int i)
{
return i
}
public void Test3(string i)
{
}
}
A customer of our webservice can use a service reference to get access to Test(), Test2() and Test3().
Now i'm searching for a class, model, interface or anything else which I can use to alter the access to the method (Currently using [PrincipalPermission] attribute) as well as alter the parameter value.
Example:
Customer A calls Test2(150)
The class/method checks whether Customer A has access to Test2. The class/method validates the user but notices that the user does not have access to 150. He only has access to 100.So the class/method sets the parameter to 100 and lets it follow through on it's journey.
Customber B class Test()
The class/method checks whether Customer B has access to Test. After validation it shows that the user does not have access so it throws a SecurityException.
My question:
In what class, interface, attribute or whatever can I best do this?
(ps. As example i've only used authentication and parameter handling, but we plan to do a lot more in this stage.)
Edit
I notice most, if not all, assume I'm using actionResults. So i'd like to state that this is used in a webservice where we provide our customers with information from our database. In no way will we come in contact with a ActionResult during the requests to our webservice. (Atleast, not our customers)
Authentication can also be done through an aspect. The aspect oriented paradigm is designed to honor those so-called cross-cutting concerns. Cross-cutting concerns implemented in the "old-fashioned" oo-way make your business logic harder to read (like in Nick's example above) or even worse to understand, because they don't bring any "direct" benefit to your code:
public ActionResult YourAction(int id) {
if (!CustomerCanAccess(id)) {
return new HttpUnauthorizedResult();
}
/* the rest of your code */
}
The only thing you want here is /* the rest of your code */ and nothing more.
Stuff like logging, exception handling, caching and authorization for example could be implemented as an aspect and thus be maintained at one single point.
PostSharp is an example for an aspect-oriented C# framework. With PostSharp you could create a custom aspect and then annotate your method (like you did with the PrincipalPermissionAttribute). PostSharp will then weave your aspect code into your code during compilation. With the use of PostSharp aspects it would be possible to hook into the method invocation authenticating the calling user, changing method parameters or throw custom exceptions (See this blog post for a brief explanation how this is implemented).
There isn't a built-in attribute that handles this scenario.
I find it's usually best to just do something like this:
public ActionResult YourAction(int id) {
if (!CustomerCanAccess(id)) {
return new HttpUnauthorizedResult();
}
/* the rest of your code */
}
This is as simple as it gets and easy to extend. I think you'll find that in many cases this is all you need. It also keeps your security assertions testable. You can write a unit test that simply calls the method (without any MVC plumbing), and checks whether the caller was authorized or not.
Note that if you are using ASP.Net Forms Authentication, you may also need to add:
Response.SuppressFormsAuthenticationRedirect = true;
if you don't want your users to be redirected to the login page when they attempt to access a resource for which they are not authorized.
Here's how I've made my life simpler.
Never use simple values for action arguments. Always create a class that represents the action arguments. Even if there's only one value. I've found that I usually end up being able to re-use this class.
Make sure that all of teh properties of this class are nullable (this keeps you from running into default values (0 for integers) being automatically filles out) and thatallowable ranges are defined (this makes sure you don't worry about negative numbers)
Once you have a class that represents your arguments, throwing a validator onto a property ends up being trivial.
The thing is that you're not passing a meaningless int. It has a purpose, it could be a product number, an account number, etc. Create a class that has that as a property (e.g An AccountIdentifier class with a single field called 'id). Then all you have to do is create a [CurrentUsedCanAccessAccountId] attribute and place it on that property.
All your controller has to do is check whether or not ModelState.IsValid and you're done.
There are more elegant solutions out there, such as adding an action filter to the methods that would automatically re-direct based on whether or not the user has access to a specific value for the parameter, but this will work rather well
First, just to say it, that your own methods are probably the most appropriate place to handle input values (adjust/discard) - and with the addition of Authorize and custom filter actions you can get most done, and the 'MVC way'. You could also go the 'OO way' and have your ITest interface, dispatcher etc. (you get more compiler support - but it's more coupled). However, let's just presume that you need something more complex...
I'm also assuming that your Test is a controller - and even if it isn't it can be made part of the 'pipeline' (or by mimicking what MVC does), And with MVC in mind...
One obvious solution would be to apply filters, or action filters via
ActionFilterAttribute
Class
(like Authorize etc.) - by creating your own custom attribute and
overriding OnActionExecuting etc.
And while that is fine, it's not going to help much with parameters manipulation as you'd have to specify the code 'out of place' - or somehow inject delegates, lambda expressions for each attribute.
It is basically an interceptor of some sort that you need - which allows you to attach your own processing. I've done something similar - but this guy did a great job explaining and implementing a solution - so instead of me repeating most of that I'd suggest just to read through that.
ASP.NET MVC controller action with Interceptor pattern (by Amar, I think)
What that does is to use existing MVC mechanisms for filters - but it exposes it via a different 'interface' - and I think it's much easier dealing with inputs. Basically, what you'd do is something like...
[ActionInterceptor(InterceptionOrder.Before, typeof(TestController), "Test1")]
public void OnTest1(InterceptorParasDictionary<string, object> paras, object result)
The parameters and changes are propagated, you have a context of a sort so you can terminate further execution - or let both methods do their work etc.
What's also interesting - is the whole pattern - which is IOC of a
sort - you define the intercepting code in another class/controller
all together - so instead of 'decorating' your own Test methods -
attributes and most of the work are placed outside.
And to change your parameters you'd do something like...
// I'd create/wrap my own User and make this w/ more support interfaces etc.
if (paras.Count > 0 && Context.User...)
{
(paras["id"] as int) = 100;
}
And I'm guessing you could further change the implementation for your own case at hand.
That's just a rough design - I don't know if the code there is ready for production (it's for MVC3 but things are similar if not the same), but it's simplistic enough (when explained) and should work fine with some minor adjustments on your side.
I'm not sure if I understood your question, but it looks like a model binder can help.
Your model binder can have an interface injected that is responsible for determining if a user has permissions or not to a method, and in case it is needed it can change the value provided as a parameter.
ValueProviders, that implement the interface IValueProvider, may also be helpful in your case.
I believe the reason you haven't gotten ay good enough answer is because there are a few ambiguities in your question.
First, you say you have an MVC class that is called from a client and yet you say there are no ActionResults. So you would do well to clarify if you are using asp.net mvc framework, web api, wcf service or soap (asmx) web service.
If my assumption is right and you are using asp.net mvc framework, how are you defining web services without using action results and how does your client 'call' this service.
I am not saying it is impossible or that what you may have done is wrong, but a bit more clarity (and code) would help.
My advice if you are using asp.net mvc3 would be to design it so that you use controllers and actions to create your web service. all you would need to do would be to return Json, xml or whatever else your client expects in an action result.
If you did this, then I would suggest you implement your business logic in a class much like the one you have posted in your question. This class should have no knowledge of you authentication or access level requirements and should concentrate solely on implementing the required business logic and producing correct results.
You could then write a custom action filter for your action methods which could inspect the action parameter and determine if the caller is authenticated and authorized to actually access the method. Please see here for how to write a custom action filter.
If you think this sounds like what you want and my assumptions are correct, let me know and I will be happy to post some code to capture what I have described above.
If I have gone off on a tangent, please clarify the questions and we might be one step closer to suggesting a solution.
p.s. An AOP 'way of thinking' is what you need. PostSharp as an AOP tool is great, but I doubt there is anything postsharp will do for you here that you cannot achieve with a slightly different architecture and proper use of the features of asp.net mvc.
first create an attribute by inheriting from ActionFilterAttribute (system.web.mvc)
then override OnActionExecuting method and check if user has permission or not
this the example
public class CheckLoginAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!Membership.IslogedIn)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "area",""},
{ "action", "login" },
{ "controller", "user" },
{ "redirecturl",filterContext.RequestContext.HttpContext.Request.RawUrl}
});
}
}
}
and then, use this attribute for every method you need to check user permission
public class Test
{
[ChecklLogin]
public void Test()
{
}
[ChecklLogin]
public int Test2(int i)
{
return i
}
[ChecklLogin]
public void Test3(string i)
{
}
}

Can somebody link me to some code where there is a fantastic or a nice use of Inheritance

I strongly believe that, reading code and reading good code is key to great programming. If not one of the many.
I had been facing some problems in visualizing and having a "feel" of using inheritance to better my code architecture.
Can somebody give me some link to good code to emulate, where folks have used inheritance in an absolute "kung-fooey ruthless" manner [in a good way]
I strongly believe that, reading code and reading good code is key to great programming
Hard to disagree.
Actually the qestion is pretty hard - becouse there is some alternatives to inheritance, such as composite reuse principle, so sometimes it's very hard to diside if inheritance is used in "kung-fooey ruthless" manner or there ware some better way to implement the same wich will make code esier to understand/test/make it lossely coupled and so on.
In my humble opinion Enterprise Library Application validation block whith it's Microsoft.Practices.EnterpriseLibrary.Validation.Validator class with all it's descendants
is a very good example of inheritance, becouse
concept of validation is easy to understand
there is good example how to find common in objects of with pretty different nature (i.e. OrCompositeValidator/DateTimeRangeValidator/ObjectCollectionValidator)
many of us tried to implement something more or less like this, so this background will give more quality for understanding
this is clear(for me, but I can be wrong:) that inheritance has no alternatives there
You can download source code from codeplex.
An example of good usage of inheritance would be the .NET framework classes. You can download the MONO project to gain access to some source code. If you want to better your code architecture, invest some time in studying architectural design patterns.
Here is a personal example where I've made use of inheritance to greatly benefit a development situation:
I needed to develop a asp.net (c#) form control set, which would allow both standard web forms (bunch of form fields with submit button), as well as a secure version which talks to a web service to submit the information over SSL.
Because of all of the similarities between the controls and concepts, I developed a number of classes:
BaseWebControl
custom base control class that inherits from System.Web.UI.WebControl class (part of .NET framework
has custom properties and methods that are used in our application by all custom controls (control state info, etc.)
BaseFormControl
inherits from BaseWebControl, gaining all of its underlying functionality
handles base form functionality, such as dynamically adding fieldsets, marking required fields, adding submit button, etc. etc.
contains a label and associated control index for easy lookups
marked as an abstract class, with abstract method called SubmitForm. This method is not defined on this class, however it is called by the submit button click event. This means that any specific form control class that inherits from this base class can implement the abstract SubmitForm functionality as needed.
EmailFormControl
Inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
contains very little, except overrides the abstract method SubmitForm, and generates an email based on the form fields.
all other control functionality and event handling is dealt with by the base class. In the base class when the submit button is clicked and handled, it calls this specific implementation of SubmitForm
SecureFormControl
Again inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
In its implementation of SubmitForm, it connects to a WCF web service and passes the information in over SSL.
no other functionality is required because base class handles the rest.
In stripped down code form, the general outline is as such:
public class BaseWebControl : System.Web.UI.WebControl
{
//base web control with application wide functionality built in
}
public abstract class BaseFormControl : BaseWebControl
{
//handles all 'common' form functionality
//...
//...
//event handler for submit button calls abstract method submit form,
//which must be implemented by each inheriting class
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitForm();
}
protected abstract SubmitForm();
}
public class EmailFormControl : BaseFormControl
{
protected override SubmitForm()
{
//implement specific functionality to email form contents
}
}
public class SecureFormControl : BaseFormControl
{
protected override SubmitForm()
{
//connect to WCF web service and submit contents
}
}
As a result of the above, BaseFormControl has about 1000 lines of code in a whole bunch of methods, properties, etc. SecureFormControl and EmailFormControl each have about 40 lines. All other functionality is shared and controlled by the base class. This promotes:
maintainability
efficiency
flexibility
consistency
Now I can create any type of web form, such as DataBaseFormControl, etc. etc. very easily. I can add great new functionality to all forms by adding methods and properties to the base classes, etc.
And the list goes on.
Phew that was a lot of typing. Hope this helps give you a good example. This was one instance where I found inheritance to be a key success point in a project.
I agree with the recommendation to look at the .NET base class library, as it has excellent examples of abstraction via both inheritance and interfaces. The goal is to insulate consumer code from having to care about the details of a particular implementation. The WinForms designer works with Controls, but it has no idea what specific kinds of Controls will be implemented. It doesn't care, because inheritance abstracts away the unnecessary details. LINQ works similarly with IEnumerable; it doesn't really matter what's being enumerated, as there are algorithms you can write that work with anything enumerable. Both are excellent examples of abstraction used well.

retrieve webservice containing page control in C#

is there a way to reference the page control in a webservice? something like this:
[WebService(Namespace = "http://test.org/")]
public class Search : System.Web.Services.WebService
{
public Search()
{
Page.Controls.Add(new Control()); // can I get a reference to Page?
}
}
This seems like a very odd design approach. In general a called method should have no knowledge about, or dependencies on the caller. In this case the web method would need knowledge about the page calling it. I don't think this is possible, and even if it was, consider the possibility that it may not even be a page calling the web service. It could be any kind of application.
What you are trying to do (at least the way you are trying to do it) is impossible. The web service cannot, at server side, modify the page by modifying the control tree, server side. The page object that was rendered to the user does not exists any more.
I think that what you should be doing instead is using an update panel. That will allow you to do exactly what you want to.

Common inheritance for pages, web services and web controls

I have a set of functions I want to be available to my web pages and user controls in my c# .net 3.5 web project. My standard approach for pages is to create a "base page" that extends the System.Web.UI.Page class and then have my pages inherit from this, rather than directly from the Page class.
I now want to expose some of these functions to my web controls (ascx) and web services. I can think of a number of ways to do this, but they seem a little clumsy and I think I'm missing a trick.
Is there an easy way to provide some common functions to both my pages, web services and controls using inheritance, or do I need to wrap these functions in a class that all of them can access?
An example to clarify:
I have a singleton that handles most functionality for my web application.
At the start of each request I want to check that the class exists in the web cache and initialise it if not.
Initially this was handled in a page base that the pages all used. Now I need to be able to access my singleton safely from services and controls, with the same checks. I have therefore extracted the checking and initialisation logic into another class, that then each of my base page, control and web service, all instantiate. Even with this model I have the same code repeated in 3 places (each of my base classes for controls, ws and pages), albeit not much code, this seems wrong too!
It works, but it seems clumsy...I look forward to you guys humbling me with your wisdom!
Sounds to mee like a case of aspect-oriented programming. .NET is ill equipped for this. I'm afraid that your solution is one of the best.
Alternatively perhaps you can move all or some of those functions to a static class/singleton and then use that class from your aspx/ascx/asmx? Not much in the way of inheritance, but at least less code duplication.
My solution to this is to put all the methods and functions I want to share in my base master page class. I then put an equivalent for each method and function in the user control base class as follows:
//Property in masterpage base
public string QsSearchTerm
{
get
{
if (!String.IsNullOrEmpty(Request.QueryString["q"]))
{
return Helpers.SanitiseString(Server.UrlDecode(Request.QueryString["q"]));
}
return String.Empty;
}
}
//Property in usercontrol base
public string QsSearchTerm
{
get
{
if (Page.Master is BaseMasterPage)
{
return ((BaseMasterPage)Page.Master).QsSearchTerm;
}
return string.Empty;
}
}
What this doesn't help with, is your code repetition with web service base classes. I would think that refactoring the above into a class with a constructor that accepts an HttpContext instance would be the way forward. You can then expose a singleton instance of this class in your base web service, master page, user control, page etc.
Hope this helps, but I too would be interested in hearing if there's a better way.
In your Singleton you could provide a Strategy interface to allow variations of the code depending on the configured environment. This would allow you to switch between web/windows/wcf...and so on.
I think using a BasePage is the right approach.
I have multiple base pages and custom user controls that load differently depending on which basepage is used by the current page.
In your custom user control you can use something like:
if (this.Page is BasePageName)
{
BasePageName bp = (BasePageName)this.Page;
bp.BasePageFunction();
}
No you can get ride of the repetitive code in the custom user control and just call it from the base page.
You can also have a hierarchy of inherited base pages depending on page functionality and needs. ie.) BasePageName2 : BasePageName

Categories

Resources