load different css for site localization - asp.net

I need to load different css file depending on the language that the user selects. I need to do this only in my master page.

If you are using the built-in themes and globalization support you could use a httpModule: (untested)
public class PageModule : IHttpModule
{
public void Dispose()
{
}
public void Init(System.Web.HttpApplication context)
{
context.PreRequestHandlerExecute += Application_PreRequestHandlerExecute;
}
public void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//Adds a handler that executes on every page request
HttpApplication application = default(HttpApplication);
application = (HttpApplication)sender;
Page page = application.Context.CurrentHandler as Page;
if ((page != null))
page.PreInit += Page_PreInit;
}
public void Page_PreInit(object sender, EventArgs e)
{
//If current context has no session then abort
if (HttpContext.Current.Session == null)
return;
//Get current page context
Page page = (Page)sender;
switch (page.Culture) {
case "en-US":
page.Theme = "en-USTheme";
break;
case "fr-FR":
page.Theme = "fr-FRTheme";
break;
default:
page.Theme = "DefaultTheme";
break;
}
}
}

you could write the selected language in a cookie. Then in you master page inspect the value saved in the cookie and assign the correct stylesheet.

Related

ASP.Net Dynamically switch Master Pages

Never needed to do this before but is it possible to dynamically set/change which master page a page is using? Have an old asp.net web forms project which I have created a new bootstrap template for but the boss wants to give people the opportunity to switch on the new one instead of forcing it upon them.
I would recommend you to create a BasePage class than write this method in that class and inherit all of your pages from this class whose master page can be changed dynamically.
public class BasePage: System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
try
{
if (conduction1)
this.Page.MasterPageFile = "~/MasterPage.master";
else
this.Page.MasterPageFile = "~/Master.master";
}
catch (Exception ex)
{
}
}
}
And then in your page inherit page from BasePage like this
public partial class _Default:BasePage
The master page is changed only in preint event
protected void Page_PreInit(object sender, EventArgs e)
{
try
{
if (conduction1)
this.Page.MasterPageFile = "~/MasterPage.master";
else
this.Page.MasterPageFile = "~/Master.master";
}
catch (Exception ex)
{
}
}
or
void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
page.MasterPageFile = "string location of masterpage";
}

HTTP module re-writing the URL with some encryption

I am writing one class with the help of HTTPModule to check userIdentity in session before he access any page.If the variable in the session is null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx", false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of encryption in URL for which my Breadcrumbs are not working in the page. The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu

asp.net - global.asax in asp.net 2.0 app

I created a global.asax file for an asp.net application. I run some code in the session_start method. The code does not get executed. Is there some type of procedure for using a global.asax file in asp.net 2.0?
I have the asax file itself and also a codebehind file.
Thank you!
Edit:
asax file:
<%# Application Codebehind="Global.asax.cs" Inherits="GrowUp.Global" %>
The code behind file:
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
namespace Ligdol
{
/// <summary>
/// Summary description for Global.
/// </summary>
public class Global : System.Web.HttpApplication
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
Application["HostName"] = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
Application["counter"] = 1;
}
protected void Session_Start(Object sender, EventArgs e)
{
// Get the count from the application variable
int counter = int.Parse(Application["counter"].ToString());
//Check if a cookie exists.
if(HttpContext.Current.Request.Cookies["ligdolVersion"] != null)
{
//If a cookie exists, we need to redirect the user to the respective site.
if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "new")
{
Response.StatusCode = 302;
Response.Status = "Moved temporarily";
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "old")
{
return;
}
}
else if (counter == 40)
{
// If a cookie does not already exist,
//we need to check if the user is to be allowed to continue to the old site
//or be redirected to the new site.
//Note in a file that a user was redirected, so we can get an estimate of how many are being redirected.
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to new site.");
tw.Close();
// Reset counter.
Application["counter"] = 1;
//write cookie made to expire in 30 days, by then the experiment will be over (we hope!).
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "new";
Response.Cookies.Add(cookie);
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else
{
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to old site.");
tw.Close();
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "old";
Response.Cookies.Add(cookie);
return;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
}
protected void Application_Error(Object sender, EventArgs e)
{
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
}
#endregion
}
}
The issue was the codebehind file. Once I put the code inline inside the asax file, it worked. This might be the only solution for old website projects.

How can i make my MSI file download from my Website on Button click

I have my Href for downloading MSI and ZIP files directly by clicking on that. I can download those but when he clicks on that I will have a information where he has to fill the required details. After filling and clicking on Download button he can able to download the required file selected
I write the following but no use
Response.Redirect("/Download/ACHTest.msi");
Try this create 2 links instaed of one and ry to pass the values as follows on Linkbuttons page
protected void lnkMsi_Click(object sender, EventArgs e)
{
HttpContext _context = HttpContext.Current;
_context.Items.Add("val", "lnkMsi");
Server.Transfer("downloadInfo.aspx");
}
protected void lnkZip_Click(object sender, EventArgs e)
{
HttpContext _context = HttpContext.Current;
_context.Items.Add("val", "lnkZip");
Server.Transfer("downloadInfo.aspx");
}
On Download page
if (!IsPostBack)
{
HttpContext _context = HttpContext.Current;
if (_context.Items["val"].ToString() == "lnkMsi")
{
DownloadType = "Msi";
oDownInfo.DownloadType = DownloadType;
}
else if (_context.Items["val"].ToString() == "lnkZip")
{
DownloadType = "Zip";
oDownInfo.DownloadType = DownloadType;
}
else
{
Response.End();
}
}

How to log POSTed forms submissions?

Back in the ASP classic days when i needed to write out the name/value pairs of forms submitted by POST i thru this loop into the page:
on error resume next
for each x in Request.Form
Response.AppendToLog x & "=" & Request(x)
next
It threw all the form fields and values into the log just as GETs are. Does IIS7 .net give me any better method? (this is for the dev/testing portion of the project i don't have any concern about the space or cycles used to accomplish this).
thx
You can create an http module to log all posts. It allows you to log outside of the pages, a single point of logging instead of having to add the logic to all pages where you want to log activity.
Here you have some of the code. You would have to avoid logging viewstate since is tons of useless information. So you have to add some logic to achieve this.
public class ActivityLogModule: IHttpModule
{
public void Init(HttpApplication application)
{
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}
private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
if (RecordActivity(context))
{
ActivityLogger.Instance.Log(application.Context.User.Identity.Name,
application.Context.Request.Url.AbsoluteUri,
application.Context.Request.Form.ToString());
}
}
public void Dispose(){}
protected bool RecordActivity(HttpContext context)
{
if (!context.Request.RequestType.Equals("POST"))
{
return false;
}
return true;
}
}
You could have something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
LogPostValues();
}
private void LogPostValues()
{
string logPath = #"C:\PostedValuesLog.txt";
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Logging: {0}", Request.Path);
sb.Append("Form Values");
foreach (string key in Request.Form)
{
string val = Request.Form[key];
sb.AppendFormat("{0} = {1}<br/>", key, val);
}
sb.Append(Environment.NewLine);
sb.Append("QueryString Values");
foreach (string key in Request.QueryString)
{
string val = Request.QueryString[key];
sb.AppendFormat("{0} = {1}<br/>", key, val);
}
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
File.AppendAllText(logPath, sb.ToString());
}
This is a crude method though and shouldn't really be used in production code. However, as this is just for development & testing, it should suffice to track what data is being posted to your page via the querystring and form.

Resources