Fast method to change aspx extension - c#

I use this way to rewite requested URL that have abc extension to aspx extension(found in SO):
void Application_BeginRequest(object sender, EventArgs e)
{
String fullOrigionalpath = Request.Url.ToString();
String[] sElements = fullOrigionalpath.Split('/');
String[] sFilePath = sElements[sElements.Length - 1].Split('.');
if (fullOrigionalpath.Contains(".abc") )
if (!string.IsNullOrEmpty(sFilePath[0].Trim()))
Context.RewritePath(sFilePath[0] + ".aspx");
}
but it seems this way is too slow. Can you say me How can I do this in web.config or other fast way?

Use Path.ChangeExtension. Don't Invent the wheel.
string aspxPath = Path.ChangeExtension(fullOrigionalpath, "aspx");

Related

SEO friendly URl in asp.net

Im creating a web application. There are a default page where a list of questions. When user click the question that will redirect to the user to ViewQuestion that is in the Question folder. At the default.aspx page im using the datalist control to display question title . And there i am generating the url with id to the question . For this code is below .
protected void listQuestion_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
LinkButton lnkTitle = (LinkButton)e.Item.FindControl("lnkQuestion");
// lnkTitle.Style.Add("text-decoration", "none");
PostEntity Item = (PostEntity)e.Item.DataItem;
lnkTitle.PostBackUrl = GenerateURL(Item.Title, Item.Id);
}
}
public static string GenerateURL(string title, int Id)
{
string strTitle = title.Trim();
strTitle = strTitle.ToLower();
//strTitle = strTitle.Replace();
strTitle = strTitle.Replace(" ", "-");
strTitle = strTitle.Trim();
strTitle = strTitle.Trim('-');
strTitle = "~/Questions/ViewQuestion.aspx?QuestionID=" + Id.ToString().Trim() + "/" + strTitle + ".aspx";
return strTitle;
}
in global.asax the code is
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoute(RouteTable.Routes);
}
static void RegisterRoute(RouteCollection route)
{
route.MapPageRoute("Default", "Default", "~/Default.aspx");
route.MapPageRoute("ViewQuestion", "Questions/ViewQuestion{QuestionID}", "~/Questions/ViewQuestion.aspx");
}
And the viewpage to get the Querystring as below :
lblQustionText.Text = this.Page.RouteData.Values["QuestionID"].ToString() as string; // giving me object reference exception
my pageurl is generating like this
/Questions/ViewQuestion.aspx?QuestionID=1376/get-the-current-logged.aspx
How can i make this example for SEO friendly url . Thanks for your answer.
There are two things about your code that seem to be wrong:
Your page route should probably include a forward slash between the page name (ViewQuestion) and the question ID:
Questions/ViewQuestion/{QuestionID}
The page URL you generate does not match the route, it should not contain the aspx suffix and the order of the route parameter and the query parameter is mixed up. It should be something like
String.Format("~/Questions/ViewQuestion/{0}?QuestionID={1}", strTitle, Id.ToString().Trim())
As a sidenote, I find it a bit confusing that you include a query parameter with the exact same name as your route parameter. My advice would be to use a route parameter for both, stackoverflow-style:
/Questions/ViewQuestion/numerical-id/question-description

Is this a good way to pass variables between asp.net pages

It's the first time I'm passing variables between two pages in my asp.net project.
It works, but I'm wondering if it is a good way to do it? Is it secure? Is there a better way?
The reason why I ask is that I've have learned never to use concatenation in sql, but instead use parameters (which I always do from now on). Is there a similar risk in this case?
In web page1:
protected void Button1_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string date = txtDate.Text;
string time = txtTime.Text;
string name = txtName.Text;
string url = "~/change.aspx?newemail="+mail+"&newdate="+date+"&newtime="+time+"&newname="+name+"";
Response.Redirect(url);
}
In web page2:
protected void Page_Load(object sender, EventArgs e)
{
String email = Request.QueryString["newemail"];
String date = Request.QueryString["newdate"];
String time = Request.QueryString["newtime"];
String name = Request.QueryString["newname];
TextBox1.Text = email;
TextBox2.Text = date;
TextBox3.Text = time;
TextBox4.Text = name;
}
if it is a good way to do it?
Not really. You need to url encode the values because if they contain special characters the receiving page will not parse them correctly:
string url = "~/change.aspx?" +
"newemail=" + HttpUtility.UrlEncode(mail) +
"&newdate=" + HttpUtility.UrlEncode(date) +
"&newtime=" + HttpUtility.UrlEncode(time) +
"&newname=" + HttpUtility.UrlEncode(name);
Is it secure?
No, not at all. Anyone could send a request to your target page with whatever values he feels good for him.
Is there a better way?
That would depend on your specific requirements and whether the information you are transmitting is sensitive or not. If it is sensitive information, then you might consider storing the values on the server instead of passing them as query string parameters. For example you could use the ASP.NET Session for this purpose.
Is it secure? No, of course not, the values are on the query string which gets sent to the browser. If you want to keep it secure put the values in session on the server side.
You are using QueryString Way to pass variables from one page to another page.its not a problem if the parameters are not secure like you cant pass secure info(Sensitive Information) like passwords,any important ids...
if you want to handle with secure parameters(Sensitive Information) you can use Sessions,Cookies..
In your case you are passing names.i hope it doesnt create any problems because this are not secure parameters(Sensitive info).even though if you feel any security risks you can use encryption and decryption concepts like encrypt your parameter name and pass it with url and then decrypt that parameter where you want to use.
Refer :
http://msdn.microsoft.com/en-us/library/6c3yckfw%28v=vs.100%29.aspx
http://www.codeproject.com/Articles/8055/Transferring-page-values-to-another-page
For better understanding about passing variables from one page to another page
Thank you guys for you help!
I have now changed it to Sessions. My code now looks like this:
In web page1:
string email = txtEmail.Text;
string date = txtDate.Text;
string time = txtTime.Text;
string name = txtName.Text;
Session["email"] = email;
Session["date"] = date;
Session["time"] = time;
Session["name"] = name;
Response.Redirect("~/change.aspx");
In web page2:
protected void Page_Load(object sender, EventArgs e)
{
string email = (string)(Session["email"]);
string date = (string)(Session["date"]);
string time = (string)(Session["time"]);
string name = (string)(Session["name"]);
TextBox1.Text = email;
TextBox2.Text = date;
TextBox3.Text = time;
TextBox4.Text = name;
}

Writing from a list to a text file C#

How do I code the whole list into the text file with commas in between each bit of data? Currently it is creating the file newData, but it is not putting in the variables from the list. Here is what I have so far.
public partial class Form1 : Form {
List<string> newData = new List<string>();
}
Above is where I create my list. Below is where I am reading it from.
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
TextWriter tw = new StreamWriter("NewData.txt");
tw.WriteLine(newData);
buttonSave.Enabled = true;
textBoxLatitude.Enabled = false;
textBoxLongtitude.Enabled = false;
textBoxElevation.Enabled = false;
}
And below is where the variables are coming from.
private void buttonSave_Click(object sender, EventArgs e) {
newData.Add (textBoxLatitude.Text);
newData.Add (textBoxLongtitude.Text);
newData.Add (textBoxElevation.Text);
textBoxLatitude.Text = null;
textBoxLongtitude.Text = null;
textBoxElevation.Text = null;
}
While you can use String.Join as others have mentioned they're ignoring three important things:
The fact that what you're really trying to do is write a comma-separated values file
The input that you're receiving and whether or not it will have commas in it
If you sanitize your input, what the current culture on the thread is when you write it out to the file
You want to write a comma-delimited file. There's no standardized format for this, but you do have to be careful of string content, especially in your case, where you're getting user input. Consider the following input:
latitude = "39,41"
longitude = "41,20"
There are a number of countries where the comma is used as a decimal separator, so this kind of input is very possible, depending on how distributed your application is (I'd be even more concerned if this was a website, personally).
And when getting the elevation, it's absolutely possible in most other places that use a comma as the thousands separator:
elevation = 20,000
In all of the other answers, your output for the line in the file will be:
39,41,41,20,20,000
Which when parsed (assuming it will be parsed, you're creating a machine-readable format) will fail.
What you want to do is parse the content first into a decimal and then output that.
Assuming you sanitize your input like so:
decimal latitude = Decimal.Parse(textBoxLatitude.Text);
decimal longitude = Decimal.Parse(textBoxLongitude.Text);
decimal elevation = Decimal.Parse(textBoxElevation.Text);
You would then format the values so that there are no commas (if you want).
To that end, I really recommend that you want to use a dedicated CSV writer/parser (try ServiceStack's serializer on NuGet, or others, if you prefer), which accounts for commas within the content you want separated by commas.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
TextWriter tw = new StreamWriter("NewData.txt");
tw.WriteLine(String.Join(", ", newData));
// Add appropriate error detection
}
In response to the discussion in both main answer threads, here is an example from my older code of a more robust way to handle CSV output:
The above not checked for syntax, but the key concept is String.Join.
public const string Quote = "\"";
public static void EmitCsvLine(TextWriter report, IList<string> values)
{
List<string> csv = new List<string>(values.Count);
for (var z = 0; z < values.Count; z += 1)
{
csv.Add(Quote + values[z].Replace(Quote, Quote + Quote) + Quote);
}
string line = String.Join(",", csv);
report.WriteLine(line);
}
This could be made slightly more general with an IEnumerable<object> but in the code I took this form, I didn't have the need to.
You cannot output the list just by calling tw.WriteLine(newData);
But something like this will achieve that:
tw.WriteLine(string.Join(", ", newData));
you could:
StringBuilder b = new StringBuilder();
foreach (string s in yourList)
{
b.Append(s);
b.Append(", ");
}
string dir = "c:\mypath";
File.WriteAllText(dir, b.ToString());
You have to iterate the List (not tested) or use string.Join, as the other users suggested (you need to convert your list to an array then)
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
TextWriter tw = new StreamWriter("NewData.txt");
for (int i = 0; i < newData.Count; i++)
{
tw.Write(newData[i]);
if(i < newData.Count-1)
{
tw.Write(",");
}
}
tw.close();
buttonSave.Enabled = true;
textBoxLatitude.Enabled = false;
textBoxLongtitude.Enabled = false;
textBoxElevation.Enabled = false;
}

Asp.Net Query String

I am using Querystring to pass values from one page to other. I am tring to implement encoding and decoding using the Server.UrlDecode and urlEncode.
Query string returns a null value, but I can check the values are been sent in URL.
The two pages are:
QueryString.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string id = "1";
string name = "aaaa";
string url = string.Format("QueryStringValuesTransfer.aspx?{0}&{1}", Server.UrlEncode(id), Server.UrlEncode(name));
Response.Redirect(url);
}
;;
In another page :
QueryStringValuesTransfer.aspx:
public partial class QueryStringValuesTransfer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id1 = Server.UrlDecode(Request.QueryString["id"]);
string name1 = Server.UrlDecode(Request.QueryString["name"]);
Response.Write(id1 + name1);
}
}
I am get null values in the id1 and name1.
Any help please..
Change this line:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));
Right now you are only setting the values in the querystring, you need to assign them names so you can grab them again:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));
That's because your query string should be something like
MyPage.aspx?id=xxx&name=yyy
You are not passing the values, only the names...
string url = string.Format("QueryStringValuesTransfer.aspx?{0}&{1}", Server.UrlEncode(id), Server.UrlEncode(name));
Should be:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));
You aren't specifying a name for the values. You need:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));
When constructing the URL in the first page you should do this:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));
The query string consists of key-value pairs, you should provide the keys.

Getting only the Referrer page not complete address in .NET

I am using C#. Below is my sample code.
private void Page_Load(object sender, System.EventArgs e)
{
string str = Request.UrlReferrer.ToString();
Label1.Text = str;
}
The result in Label1.Text is http://localhost:82/data/WebForm1.aspx.
Now I want the result "WebForm1.aspx" in Label1.Text
can you please help me?
Thanks.
If you want only the part after the last / in the URL, calling the System.IO.Path.GetFileName() method on the Uri.LocalPath should do the trick:
System.IO.Path.GetFileName(Request.UrlReferrer.LocalPath);
If you want the output to keep query string information from the URI, use the PathAndQuery property:
System.IO.Path.GetFileName(Request.UrlReferrer.PathAndQuery);
Try the LocalPath property on the UrlReferrer:
Label1.Text = Request.UrlReferrer.LocalPath;
It should provide you with just the filename.
Edit: this seems to also include the path, so only works for root.
In which case, you're better off just using Substring():
string str = Request.UrlReferrer.ToString();
Label1.Text = str.Substring(str.LastIndexOf('/')+1);

Categories