View engines for non-mvc web application - c#

I'd like to achieve the MVC View Engine behavior in an web forms application. To register a mobile channel in MVC I normally would do something like this
public static List<string> UaSurfpads = new List<string>()
{
"iPad",
"MicrosoftRt",
"PlayBook"
};
protected void Application_Start(object sender, EventArgs e)
{
// register surfpads
foreach (string device in UaSurfpads)
{
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("mobile")
{
ContextCondition = (context => context != null && context.GetOverriddenUserAgent().IndexOf(device, StringComparison.OrdinalIgnoreCase) >= 0)
});
}
// ...
}
This will enable me to create shadow views like myView.mobile.cshtml.
Is there any similar way to work using regular web forms in asp.net?

ASP.NET WebForm also have mobile features, as well as MVC. Just read this article
Also, official MS web source for mobile development

There is nothing native live MVC to handle this. However, you can achieve this by putting some code in your app to detect and redirect. 51 degrees used this approach and created a freely available framework to do all of this. I'd recommend looking at it, or at least how they achieve their mobile implementation, and mimic it for your site.

Related

Call WebAPI to .NET Framework from .NET Core

I have backend project on ASP .NET Core. I write a web api into this project. Also, I have UI project on .NET Framework. I want to call web apis from .NET Frameowork and use it. What's best approches is it?
Seems you are trying to call Web API from your Windows Form application.
You can try this way:
On your Windows from Button Click event you can write this code snippet
private void Button2_Click(object sender, EventArgs e)
{
HttpClient _httpClient = new HttpClient();
string uri = "http://localhost:11951/api/MsAgent/GetMSAgentByAlias?alias=TestParam";
var _http_response = _httpClient.GetAsync(uri);
_http_response.Wait();
var _read_response = _http_response.Result.Content.ReadAsStringAsync();
_read_response.Wait();
if (_read_response.Result.Contains("No Data Found!"))
{
// Your Logic what you would like to do when no response
}
var data = JsonConvert.DeserializeObject<MSAgentViewModel>(_read_response.Result);
//Do what you wants to do with your API response
//Can Bind Data With From Property
}
This is one way, you can make the API Service Class in diffrent class its up to you. Lot of best practice out there. Let me know if you require more help on this.

Restrict URL to specific database username ASP.NET

I am making a website tool isch with ASP.NET Framework, that lets a user/customer preview their website.
I have a simple database that gathers a SESSION["username"] and creates a with the source to the customer project file.
But if I have multiple users how am I supposed to prevent users from accessing each other's files using the URL? like if the directory for the customer projects is ? "~/Customer/SESSION["username"]/Default.aspx and user1 enters user2 in the directory instead. I will post some content of the page here to make it easier to understand.
Directory of my project
In the Default.aspx page I direct everyone that is not the user "admin". And inside the Default.aspx i have an IFrame that looks like this <iframe id="contentPanel1" runat="server" /> and it gets its src attribute from my Default.aspx.cs that looks like this:
using System;
using System.Web.UI;
namespace MyFeedbackWebsite
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Redirect("~/login");
}
if ((string)Session["username"] == "admin")
{
Response.Redirect("~/admin");
}
this.contentPanel1.Attributes["src"] = "https://localhost:44350/Customer/" + Session["username"].ToString();
}
}
}
In my Admin.aspx.cs I check if the username = admin and if the user is logged in:
using System;
namespace MyFeedbackWebsite
{
public partial class admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((string)Session["username"] == null)
{
Response.Redirect("~/Login");
}
if ((string)Session["username"] != "admin")
{
Response.Redirect("~/Default");
}
}
}
}
And in the /Customer/ Directory I want the customers project to be located. But as I mentioned, if the directory is /Customer/user1/Default.aspxI want the user1 value to match the current session. Thanks beforehand!
Best regards Max
A few observations
Now, I don't know the background of this project you're working on, but it seems you are relatively new to some of the concepts, so I'll just list a few things for you to think about:
If this is a new project I would highly recommend you to stop and instead look at ASP.NET Core or similar. .NET Framework is slowly being replaced by .NET Core, so a new project based on .NET Framework (such as ASP.NET Web Forms) will quickly become outdated (if it isn't already from the start).
If this is just a spare time/personal little project, all good (except for above point) - playing around with it is a good way to learn. If it's a commercial or otherwise serious project, however, I would recommend you to read up on security best practices in web applications. Restricting access to a page using a construct like Session["username"] != "admin" is bad business and very error prone. Take a look here for an example of configuring which users or roles can access which pages.
The problem in question
It's still a little unclear to me what part of your code handles/is run when accessing /Customer/user1/Default.aspx. But I would recommend you, that instead of having the username be part of the URL, you are getting the username from the session in the backend instead, and then serving the proper page matching that username:
User accesses the URL /Customer/Default.aspx
Backend verifies that user is logged in. If not, user is redirected to login page
Backend gets the username from the session and returns the page <username>/Default.aspx (note: this is not a URL, but a file path or something similar that points to the page you are serving - the user never sees this)
Now, the user will not be able to see another user's page because /Customer/user1/Default.aspx is not a valid URL - /Customer/Default.aspx is.

How to view an ASP.NET MVC mobile page on Visual Studio 2012

I have an open source ASP.NET MVC(nopcommerce) or nopcommerce.com it is developed in ASP.NET MVC and razor view, it is both desktop and mobile version for example it has index.cshtml and Index.Mobile.cshtml but I have no experience on mobile viewing,
I do highly appreciate if someone give a a clue on how to view mobile pages on the browsers like Chrome and IE.
In MVC you would declare display-modes
For example in the link above they declare a mode called WP, to access that mode you would have a index.cshtml (normal mode) and a index.wp.cshtml (detected mode)
Once you got that, you can set up all the modes you like by testing pretty much anything you like
For example my /APP_Start/DisplayModeConfig.cs
public class DisplayModeConfig
{
public static void RegisterDisplayModes(DisplayModeProvider provider)
{
// INFO: Allows to name views/partials/masters like viewname.iphone.cshtml, and MVC will choose this automatically
// INFO: Lets remove the default "Mobile" mode, since it's pretty useless
var mobileDefault = DisplayModeProvider.Instance.Modes.First(m => m.DisplayModeId == "Mobile");
if (mobileDefault != null)
{
DisplayModeProvider.Instance.Modes.Remove(mobileDefault);
}
// INFO: Now add one that actually works
provider.Modes.Insert(0,
new DefaultDisplayMode("Mobile")
{
ContextCondition = (context => (!string.IsNullOrEmpty(context.GetOverriddenUserAgent()) && Regex.IsMatch(context.GetOverriddenUserAgent(), #"mobile|android|kindle|silk|midp", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)))
});
// INFO: Order from least to most important (since we insert at position 0)
provider.Modes.Insert(1,
new DefaultDisplayMode("Win8")
{
ContextCondition = (context => (!string.IsNullOrEmpty(context.GetOverriddenUserAgent()) && context.GetOverriddenUserAgent().IndexOf("Windows NT 6.2", StringComparison.OrdinalIgnoreCase) >= 0))
});
}
}
You also have a bunch of goodies in #Request.Browser.* like #Request.Browser.IsMobileDevice, #Request.Browser.Version, ..most work fine, but i would test those helpers before relying on them.
Depending on how mobile detection done by the site you may need:
tweak "user agent" string coming from browser. There are many tools/plugins for that.
set some sort of cookies
see if "use mobile view" supported directly on the site (i.e. http://www.xbox.com have such link at the bottom).

Maintain URL when going from ASP.NET WebForms to ASP.NET MVC

I am converting an old ASP.NET WebForms app to ASP.NET MVC 4. Everything is fine, except that I have a need to maintain backward compatibility with a specific URL. I found this great post on using UrlRewrite, but sadly that isn't something I can count on (this app gets deployed to lots of servers). At the bottom, he mentions using routing if you only have a small set of URLs to deal with, but doesn't provide any example.
Since I only have one url to deal with, I think routing would be the simple approach, but I've never dealt with anything except the default route /Controller/Action/{id} so I am looking for a solution that
Has no external dependencies
Will work on old crappy browsers
Doesn't matter if my app knows about this old url or not
The Old URI
https://www.mysite.com/default.aspx?parm1=p1&parm2=p2&etc=soforth
The New URI
https://www.mysite.com/Home/Index/?parm1=p1&parm2=p2&etc=soforth
Background: this app gets deployed to lots of servers at different locations. There are other apps (that I cannot update) that display the "Old URI" in a web-browser control, so I need them to continue to work after the app is updated to asp.net mvc.
Something like following should work (untested, may need to make this route to be one of the first):
routes.MapRoute(
"legacyDefaultPage",
"default.aspx",
new {Controller = "Legacy", Action="Default"});
class LegacyController {
ActionResult Default (string param1,...){}
}
Something that you could try is to create an httpModule this will get executed just before hit any route to in your MVC app.
In your http module you can perform a 301 or 302 redirection if seo matters doing that will give you more flexibility to transform all the parameters from your legacy to your new app.
public class RecirectionModule :IHttpModule{
public void Init(HttpApplication context)
{
_context = context;
context.BeginRequest += OnBeginRequest;
}
public void OnBeginRequest(object sender, EventArgs e)
{
string currentUrl = HttpContext.Current.Request.Url.AbsoluteUri;
string fileExtention = Path.GetExtension(currentUrl);
string[] fileList= new[]{".jpg",".css",".gif",".png",".js"};
if (fileList.Contains(fileExtention)) return;
currentUrl = DoAnyTranformation(currentUrl);
Redirect(currentUrl);
}
private void Redirect(string virtualPath)
{
if (string.IsNullOrEmpty(virtualPath)) return;
_context.Context.Response.Status = "301 Moved Permanently";
_context.Context.Response.StatusCode = 301;
_context.Context.Response.AppendHeader("Location", virtualPath);
_context.Context.Response.End();
}
public void Dispose()
{
}
}
I think that doing a redirection could be a cleaner solution if you need to change the parameter list in your new application also dealing with a lot of routes can get ugly pretty quickly.

Search engine friendly urls in ASP dot NET

Objective was:
To change pages like details.aspx?GUID=903901823908129038 to clean ones like /adrian_seo
Achieved:
Now using Response.AddHeader("Location", url);
I am able to remove all uppercase urls. I use the following function:
protected void Page_Load(object sender, EventArgs e)
{
string url = Request.Url.ToString();
if (url != Request.Url.ToString().ToLower())
{
url = Request.Url.ToString().ToLower();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", url);
}
}
Question is:
How do I change these to clean urls like /adrian_seo
I mean how do I handle requests coming to /adrian_seo and how do I show my old pages with new urls.
Do I need to use Global.asax?
Have a look into ASP.NET routing.
Use an HttpModule:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (context.Request.RawUrl.ToLowerInvariant().Equals("YOURSEOURL"))
context.RewritePath("YOURNONSEOURL");
}
Note that you don't want to hard code all this. Find some sort of regex to match your need, like if the SEO url is: /page/234234/This-is-my-page-title, you grab the 234234 and rewrite the path to page.aspx?pageid=234234
UPDATE
You can also use the IIS 7 Rewrite Module
I recommend using the UrlRewritingNet component. When writing your own library you need to overcome some difficulties, this library already handles that stuff for you...
It is a rewrite-module tuned for
ASP.NET 2.0, and offers support for
Themes and Masterpages
Regular Expressions
Good Postback-Urls
Cookieless Sessions
Runs in Shared-Hosting or Medium-Trust enviroments
OutputCache is supported
Redirects possible, even to other Domains
To enable extenionless urls in asp.net with IIS 6 or lower your also need to configure IIS to let asp.net handle all incoming requests.
You could use http://urlrewriter.net/ which can be used on asp.net 1.1 ->
After some Read up on Routing in Asp.net:
http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx
Which brings both 301 redirects for SEO page rank and Asp.net Routing for permanent organic SEO solution.

Categories

Resources