Use ASP.Net MVC only for mobile clients - c#

We currently have a large ASP.Net webforms website , and we just started converting some parts of it to asp.net MVc
We want to create a version of the site specifically for mobile clients, and we would like to start off using MVC for that.
I know that MVC supports by convention that views files ending in .mobile are served for mobile clients. But my question is - how would i set things up in general that desktop clients still use default.aspx but that mobile clients get redirected to /home

The code for browser detection should be put in a base class that all your pages will derive from. Try below code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsMobileBrowser())
{
Response.Redirect("/home");
return;
}
// your other code
}
public static bool IsMobileBrowser()
{
//GETS THE CURRENT USER CONTEXT
HttpContext context = HttpContext.Current;
//FIRST TRY BUILT IN ASP.NT CHECK
if (context.Request.Browser.IsMobileDevice)
{
return true;
}
//THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
{
return true;
}
//THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
{
return true;
}
//AND FINALLY CHECK THE HTTP_USER_AGENT
//HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
{
//Create a list of all mobile types
string[] mobiles =new[]
{
"midp", "j2me", "avant", "docomo",
"novarra", "palmos", "palmsource",
"240x320", "opwv", "chtml",
"pda", "windows ce", "mmp/",
"blackberry", "mib/", "symbian",
"wireless", "nokia", "hand", "mobi",
"phone", "cdm", "up.b", "audio",
"SIE-", "SEC-", "samsung", "HTC",
"mot-", "mitsu", "sagem", "sony"
, "alcatel", "lg", "eric", "vx",
"NEC", "philips", "mmm", "xx",
"panasonic", "sharp", "wap", "sch",
"rover", "pocket", "benq", "java",
"pt", "pg", "vox", "amoi",
"bird", "compal", "kg", "voda",
"sany", "kdd", "dbt", "sendo",
"sgh", "gradi", "jb", "dddi",
"moto", "iphone"
};
//Loop through each item in the list created above
//and check if the header contains that text
foreach (string s in mobiles)
{
if(context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower()))
{
return true;
}
}
}
return false;
}
See more at:
http://www.codeproject.com/Articles/213825/ASP-net-Mobile-device-detection
http://www.codeproject.com/Articles/34422/Detecting-a-mobile-browser-in-ASP-NET

try like this
if (request.Browser.IsMobileDevice)
{
//rediret the user to mobile views
}
make sure you remove webform View Engine. like this. MobileCompatibleViewEngine
ViewEngines.Engines.Remove(ViewEngines.Engines.OfType<WebFormViewEngine>().First());
ViewEngines.Engines.Add(new MobileCapableWebFormViewEngine()); // this will come from Nuget Package.

Write the below code in to Global.asax.
If user will access the website through Desktop it will automatically redirect to Desktop website weather user access through Android phone it will
automatically redirect to mobile website
protected void Application_Start()
{
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("Android")
{
ContextCondition = (context => context.Request.UserAgent.IndexOf
("Android", StringComparison.OrdinalIgnoreCase) >= 0)
});
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("WindowsPhone")
{
ContextCondition = (context => context.Request.UserAgent.IndexOf
("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0)
});
}

Related

C# Method - Publish Entire Sitecore Site

I have an odd request. I am wondering if it is possible to have your C# solution file publish the entire Site from the master database to the web database. I am in my development environment and the amount of items in Sitecore is changing daily as I am working with multiple people. This is not something that is going to be used to Production Content Management or Content Delivery. Purely development.
Is it possible to trigger a full Site publish in C# just like pressing the publish button in the content editor? And what would the code look like?
/sitecore/shell/Applications/Publish.aspx
I assume this C# method would work with Sitecore.Publishing.PublishManager?
Thanks!
We also use that on our projects...
We have that placed in a regular .aspx page. I hope that helps:
protected void Page_Load(object sender, EventArgs e)
{
PublishMode publishMode = PublishMode.Full;
using (new Sitecore.SecurityModel.SecurityDisabler())
{
var webDb = Sitecore.Configuration.Factory.GetDatabase("web");
var masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
try
{
foreach (Language language in masterDb.Languages)
{
//loops on the languages and do a full republish on the whole sitecore content tree
var options = new PublishOptions(masterDb, webDb, publishMode, language, DateTime.Now) { RootItem = masterDb.Items["/sitecore"], RepublishAll = true, Deep = true };
var myPublisher = new Publisher(options);
myPublisher.Publish();
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("Could not publish", ex);
}
}
}

The current user has insufficient permissions to perform this operation. Add Termset in sharepoint

I am trying to bind a field to a termset, and if the termset does not exist I want to create it by code. However, even when the code is running with elevated privileges I get the following exception.
The current user has insufficient permissions to perform this operation.
public static void BindTaxonomyField(string taxonomyFieldId, string taxonomyNoteFieldId, string termSetName, string termGroup, SPWeb web)
{
try
{
if (web != null)
{
// get the taxonomyfield from the sitecollection
var field = web.Fields[new Guid(taxonomyFieldId)] as TaxonomyField;
if (field != null)
{
// attach the note field
field.TextField = new Guid(taxonomyNoteFieldId);
// set up the field for my termstore
var session = new TaxonomySession(web.Site);
if (session.TermStores.Count > 0)
{
// get termstore values
TermStore ts = session.TermStores[0];
Group group = GetGroup(termGroup, ts);
if (group == null)
{
ts.CreateGroup(termGroup);
//throw new Exception("Group was not found in the termstore");
}
// ReSharper disable PossibleNullReferenceException
TermSet termSet = group.TermSets.Any(s => s.Name == termSetName) ? group.TermSets[termSetName] : group.CreateTermSet(termSetName);
// ReSharper restore PossibleNullReferenceException
//TermSet termSet = group.TermSets[termSetName];
// actually setup the field for using the TermStore
field.SspId = ts.Id;
field.TermSetId = termSet.Id;
}
field.Update();
}
}
}
catch (Exception ex)
{
}
}
private void BindColumnsToTermStore(string url)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
if (!web.AllowUnsafeUpdates)
web.AllowUnsafeUpdates = true;
BindTaxonomyField("EF810CD2-F2D2-4BD2-9ABF-C19815F13568",
"67E6E777-0D1E-4840-B858-17400CFABD14",
"Business Audience", "IctDocumentation",
web);
web.AllowUnsafeUpdates = false;
}
}
});
}
If you go in to central administration and navigate to your term store(this is in the left hand nav) in the main container of the page there is a box with a few usernames. Is the account you are running the code in listed? If not stick them in there.
i think the path is something like Central admin -> Manage service application -> Managed meta data service - and the are on the page is call Term store Administrators
There is also one more place you must check but check this first and them run again.
The next place to check is to highlight your Manage metadata service which is located
Central admin -> Manage service application
and click on permissions on the ribbon and make sure the users your running the code with has the correct access.
I always start by making sure i know who i am running the code as first of all then do the checks

Sign in as different user when using Integrated Windows Authentication

I have restricted access to a site by using Integrated Windows Authentication and turning off anonymous access. This way I can then show them their real name (from looking up on Active Directory and using the server variable LOGON_USER) and do other related Active Directory tasks.
How can I then prompt again for their user credentials, through a 'sign in as other user' link , showing the browser prompt (like you would get on a browser like Chrome or Firefox, or if the site was not in the 'Intranet' zone in IE) rather than a Web Form?
Since SharePoint offers this functionality, I assume there is a way to do this through code, but I don't know what code can do this (using C#). I can send a 401 header which makes the prompt appear, but how do you then confirm if they are logged in?
Maybe this can help you out.
ASP .NET – C# – How to “Sign in as Different User” like in Microsoft SharePoint with Windows Authentication
Try this approach. It is based on disassembled code of the method Microsoft.SharePoint.ApplicationPages.AccessDeniedPage.LogInAsAnotherUser()
First of all, I'm accessing the AccessDeniedPage page using javascript because Sharepoint does something similar:
function GoToSignAs() {
window.location.replace("./SignAs.aspx?signAs=true&returnUrl=" + window.location.toString());
}
<a onclick="GoToSignAs(); return false;" href="javascript:;">SignAs</a>
Then, in your page AccessDeniedPage you use this:
public partial class SignAs : Page
{
private const string LoginAttempts = "LoginAttempts";
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HttpContext current = HttpContext.Current;
if (current == null)
{
throw new InvalidOperationException();
}
if (GetUrlParameter<bool>("signAs"))
{
HandleSignAs(current, GetUrlParameter<string>("returnUrl"));
}
}
// ...
private static void HandleSignAs(HttpContext context, string returnUrl)
{
int attempts = 0;
HttpCookie attemptsCookie = context.Request.Cookies[LoginAttempts];
if (attemptsCookie == null || string.IsNullOrEmpty(attemptsCookie.Value))
{
attemptsCookie = new HttpCookie(LoginAttempts);
}
else
{
attempts = int.Parse(attemptsCookie.Value, CultureInfo.InvariantCulture);
}
if (!string.IsNullOrEmpty(context.Request.Headers["Authorization"]))
{
// Attempts are counted only if an authorization token is informed.
attempts++;
}
if (attempts>1)
{
attemptsCookie.Value = string.Empty;
context.Response.Cookies.Add(attemptsCookie);
context.Response.Redirect(returnUrl, true);
}
else
{
attemptsCookie.Value = attempts.ToString(CultureInfo.InvariantCulture);
context.Response.Cookies.Add(attemptsCookie);
SendEndResponse(context, 401, "401 Unauthorized");
}
}
private static void SendEndResponse(HttpContext context, int code, string description)
{
HttpResponse response = context.Response;
context.Items["ResponseEnded"] = true;
context.ClearError();
response.StatusCode = code;
response.Clear();
response.StatusDescription = description;
response.AppendHeader("Connection", "close");
response.AddHeader("WWW-Authenticate", "Negotiate");
response.AddHeader("WWW-Authenticate", "NTLM");
response.End();
}
}
FIX: you must use the IIS to work properly

Fck Editor upload images

I have a problem with images in FCK editor. when i try to upload images it gives me Connector disabled error and the images are not showing in the editor page. i am programming with visual studio 2008. please help
Have a look at the following code:
private bool CheckAuthentication()
{
// WARNING : DO NOT simply return "true". By doing so, you are allowing
// "anyone" to upload and list the files in your server. You must implement
// some kind of session validation here. Even something very simple as...
//
// return ( Session[ "IsAuthorized" ] != null && (bool)Session[ "IsAuthorized" ] == true );
//
// ... where Session[ "IsAuthorized" ] is set to "true" as soon as the
// user logs in your system.
MembershipUser m = Membership.GetUser();
if (m != null)
{
return true;
} else {
return false;
}
//return false;
}
Then update both App and Root files.

When user hit's the site the custom error page is shown. Why? This is to few users and sporadic

Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.

Categories