There are many ways to implement an url rewrite system in your web application.
This post shows the easiest way.
First, create a page called "default.aspx" with a Panel called "pnlMain".
In the page load event insert this code:
Code Snippet
- //Test the different page
- if (Request.QueryString["id"] == "1")
- pnlMain.Controls.Add(new LiteralControl("<b>Login</b>"));
- else if (Request.QueryString["id"] == "2")
- pnlMain.Controls.Add(new LiteralControl("<b>Content</b>"));
- else
- pnlMain.Controls.Add(new LiteralControl("<b>Home Page</b>"));
Add a global.asax file, create the Application_BeginRequest event and paste the follow code:
Code Snippet
- void Application_BeginRequest(object sender, EventArgs e)
- {
- string originalUrl = Request.Url.ToString();
-
- if (originalUrl.Contains("Login"))
- {
- Context.RewritePath("default.aspx?id=1");
- }
- else if (originalUrl.Contains("Content"))
- {
- Context.RewritePath("default.aspx?id=2");
- }
- else
- {
- Context.RewritePath("default.aspx?id=3");
- }
- }
Now you can launch your application in Debug mode. Add in the address bar the string "Login" and press Enter. You can try with another value "Content".
This example is very simple but it is a good way to understand how url rewrite class works.
There are more ways to get the console output text from C#.
In this example I created a function with two parameters.
The first called "cmdPath" is the path of the process to launch.
The second called "arguments" are the arguments of the process.
Code Snippet
- void RunWithRedirect(string cmdPath,string arguments)
- {
- var proc = new Process();
- proc.StartInfo.FileName = cmdPath;
- proc.StartInfo.Arguments = arguments;
-
- // set up output redirection
- proc.StartInfo.RedirectStandardInput = true;
- proc.StartInfo.RedirectStandardOutput = true;
- proc.StartInfo.RedirectStandardError = true;
-
- proc.StartInfo.UseShellExecute = false;
-
- proc.EnableRaisingEvents = true;
- proc.StartInfo.CreateNoWindow = true;
-
- proc.Start();
-
- StreamReader reader = proc.StandardOutput;
- string s = reader.ReadToEnd();
- txtConsole.Text += s;
-
- proc.WaitForExit();
- }
This HOW TO describes one of the various built-in methods .NET provides to use XML returned by a web service.
The simplest way to view the returned data is to get the response stream and put it into a string. This is especially handy for debugging. The following code gets a web page and put the the contents in a string.
public static string GetPageAsString(string address)
{
string result = string.Empty;
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Get the web response
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Get the stream from response
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
reader.Dispose();
reader = null;
request = null;
return result;
}
To call this method write this code:
GetPageAsString("http://weather.yahooapis.com/forecastrss?p=ITXX0042&u=f");
Here there is the complete sourcecode.
GetXmlFromWebIntoString.rar (37.00 kb)
Few days ago LinkedIn has released a first version of APIs to work with LinkedIn data.
It was the only social network without this possibility. In the future you can access on linkedin information directly from outlook 2010 (so they say).
For much information follow this
http://developer.linkedin.com.
Tags:
This evening I created a project in C# that explains how to remove html tags from string with regular expressions.
I created a function to semplify this operation.
private string removeHmtlFromString(string strInput)
{
try
{
Regex objRegExp = new Regex("<(.|\n)+?>");
return objRegExp.Replace(strInput, String.Empty).Trim();
}
catch
{
return string.Empty;
}
}
You can download the full work project from this article.
RemoveHtmlFromString.rar (36.17 kb)
When you got a string array and you want turn into a string, you have two ways.
This way is useful if you work with every single string before convert.
string[] strings = { "hello", "world", "I", "am", "an", "array" };
string result = "";
foreach(string s in strings) {
result += s + " ";
}
This way is the best for performance and for best code.
string output = string.Join(" ", strings);
That's all folks!!!
By default When web pages fire a post back to the server, the browser scroll is returned to the top of the page.
When the page is tall, it is very annoying.
You are three ways to kill this behaviour.
1. Application level: To set the property by default for all pages in the website, open web.config and add the attribute to the pages node.
<pages maintainScrollPositionOnPostBack="true">
2. Page Level: for a particular page, open the aspx and set the property
<%@ Page MaintainScrollPositionOnPostback="true" >
3. Code level: to set the property programmatically
Page.MaintainScrollPositionOnPostBack = true;
Tags:
StopWatch class can measure elapsed time for one interval.
We can use for measuring performance of the new code blocks or algorithms. Use IsRunning method to determine the state of StopWatch object.
Use Start method to begin measuring elapsed time, and Stop method to stop measuring elapsed time.
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
textBox1.Text = DateTime.Now.TimeOfDay.ToString();
Application.DoEvents();
// Perform a long process
Thread.Sleep(34564);
stopwatch.Stop();
textBox2.Text = DateTime.Now.TimeOfDay.ToString();
textBox3.Text = stopwatch.Elapsed.Milliseconds.ToString();
Application.DoEvents();
}
With Log4net, you can configure the layout of the string that you want to log.
It's very simple, because you can change the pattern layout string in few seconds and without compiling the application.
You don't compile everytime change the pattern layout string, because it is in the application config.
For web application it is in the web.config file and for desktop application it is in the app.config.
Each pattern member starts with % and is followeb by the name of pattern member.
You can change the width, padding, left and right justification for each pattern member.
Sometimes, I use this layout pattern: %type %file %line %method %location %class %C %F %L %l %M %n , but below I explain every single member in order to you can create your pattern layout.
a or appdomain Friendly name of appdomain
c or logger Used to output the logger of the logging event
C or class or type The fully type name of the caller class
d or date The date of logging event in the local time zone
exception The exception
F or file The file name where the logging request was issued
identity or u The active user
l or location Location information of the caller
L or line The line number from where the logging request was issued
level or p The level of the logging event
m or message Application supplied message associated with the logging event
M or method The method name where the logging request was issued
n or newline Line separator
r or timestamp The timestamp when the logging request was issued
t or thread The name of thread that generated the logging event
username or w The Windows Identity for active user
By default, the ViewState encryption is disabled in the web applications.
So it is recommended not send private data through Viewstate at least that you are not using SSL.
There are two ways to encrypt your ViewState:
1. Encrypt ViewState in every Page
2. Encrypt ViewState in web.config for all pages in your applications In the first case, add the attribute in the directive <%@Page ViewStateEncryptionMode="Always" %> in your single page.
In the second case, add the attribute viewSateEncryptionMode="Always" in your web.config.
Then add the algorithm of decryption in your web.config.
There are much key of decryption, but the key AES is the best for performance and for security.
See the example:
<configuration>
<system.web>
<machineKey decryptionKey="AutoGenerate,IsolateApps" decryption="AES" />
</system.web>
</configuration>
For more informations go to http://msdn2.microsoft.com/en-us/library/ms998288.aspx
Sometimes, some network configurations don't allow to access directly to web services.
One way is download the xml file that xml web services returns and load that in a dataset.
I wrote a small function to download xml file from web services.
It's simple, but it's a good starting point to develop other things.
public bool DownloadXmlFromService()
{
string result = "";
try
{
WebProxy proxy = new WebProxy(" proxy address ", port number );
proxy.Credentials = new NetworkCredential( user id , password, domain );
WebRequest request = WebRequest.Create("http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry?CountryName=Italy");
request.Proxy = proxy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding ec = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader reader = new System.IO.StreamReader(stream, ec);
char [] chars = new Char[256];
int count = reader.Read(chars, 0, 256);
while(count > 0)
{
string str = new String(chars, 0, 256);
result = result + str;
count = reader.Read(chars, 0, 256);
}
response.Close();
stream.Close();
reader.Close();
result = result.Replace("<","<");
result = result.Replace(">",">");
if (File.Exists("temp.xml"))
{
File.Delete("temp.xml");
}
System.IO.StreamWriter ToFile = new StreamWriter("temp.xml");
ToFile.Write(result);
ToFile.Close();
}
catch(Exception exp)
{
string str = exp.Message;
return false;
}
return true;
}