Simple way to implement Url Rewrite Class

By Emanuele Bartolesi at April 05, 2010 17:50
Filed Under: Asp.net, C#

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
  1. //Test the different page
  2. if (Request.QueryString["id"] == "1")
  3.     pnlMain.Controls.Add(new LiteralControl("<b>Login</b>"));
  4. else if (Request.QueryString["id"] == "2")
  5.     pnlMain.Controls.Add(new LiteralControl("<b>Content</b>"));
  6. else
  7.     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
  1. void Application_BeginRequest(object sender, EventArgs e)
  2. {
  3.     string originalUrl = Request.Url.ToString();
  4.  
  5.     if (originalUrl.Contains("Login"))
  6.     {
  7.         Context.RewritePath("default.aspx?id=1");
  8.     }
  9.     else if (originalUrl.Contains("Content"))
  10.     {
  11.         Context.RewritePath("default.aspx?id=2");
  12.     }
  13.     else
  14.     {
  15.         Context.RewritePath("default.aspx?id=3");
  16.     }
  17. }

 

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.

 

How to get console output text from C#

By Emanuele Bartolesi at March 28, 2010 16:56
Filed Under: C#

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
  1. void RunWithRedirect(string cmdPath,string arguments)
  2. {
  3. var proc = new Process();
  4. proc.StartInfo.FileName = cmdPath;
  5. proc.StartInfo.Arguments = arguments;
  6.  
  7. // set up output redirection
  8. proc.StartInfo.RedirectStandardInput = true;
  9. proc.StartInfo.RedirectStandardOutput = true;
  10. proc.StartInfo.RedirectStandardError = true;
  11. proc.StartInfo.UseShellExecute = false;
  12.  
  13. proc.EnableRaisingEvents = true;
  14. proc.StartInfo.CreateNoWindow = true;
  15. proc.Start();
  16.  
  17. StreamReader reader = proc.StandardOutput;
  18. string s = reader.ReadToEnd();
  19. txtConsole.Text += s;
  20.  
  21. proc.WaitForExit();
  22. }

 

How to get string from Http Request

By Emanuele Bartolesi at February 24, 2010 18:05
Filed Under: Asp.net, C#, WebServices

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)

LinkedIn API Launch

By Emanuele Bartolesi at November 26, 2009 09:27
Filed Under: C#, Online Tool
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.
 
For an example in C# you can follow this http://developer.linkedin.com/message/1408
 
 
 
 
 

How to remove html tags from string with Regular Expressions

By Emanuele Bartolesi at October 27, 2009 15:53
Filed Under: C#

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)

How to convert string array to string in C#

By Emanuele Bartolesi at September 08, 2009 04:56
Filed Under: C#

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!!! Wink

How to maintain scrollposition after post back?

By Emanuele Bartolesi at June 09, 2009 06:31
Filed Under: Asp.net, C#

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;

 

How to measure elapsed time in C# with StopWatch

By Emanuele Bartolesi at March 20, 2009 04:50
Filed Under: Asp.net, C#

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();
}

How to configure the pattern layout of Log4net

By Emanuele Bartolesi at March 20, 2009 04:48
Filed Under: Asp.net, Log, C#

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

Encrypt the ViewState

By Emanuele Bartolesi at March 20, 2009 04:45
Filed Under: Asp.net, C#

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

Download xml file from webservices

By Emanuele Bartolesi at March 20, 2009 04:39
Filed Under: Asp.net, C#, WebServices

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("&lt;","<");
result = result.Replace("&gt;",">");

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;
}

About me

I will also give you some useful tips, based on the modest wisdom gained during the years that I've worked as a developer and project manager.

Widget

Ohloh profile for Emanuele Bartolesi

 

Wakoopa

Software tracking

 

Software tracking

from Amazon



hacker emblem



Scarica il pdf di Game
Rivista Game di videogiochi
Trucchi videogiochi