Tuesday, July 31, 2012

Sachi Kahanian Digest July 2012 – Pakistani Urdu Digest


Sachi Kahanian Digest July 2012 [ Download ]

Sarguzasht Digest August 2012 – Pakistani Urdu Digest in Pdf

Sarguzasht Digest August 2012 – Pakistani Urdu Digest [ Download ]

Pakiza Digest - August 2012

Pakiza Digest - August 2012 [ Download ]

Tuesday, July 24, 2012

Tip/Trick: Url Rewriting with ASP.NET


People often ask me for guidance on how they can dynamically "re-write" URLs and/or have the ability to publish cleaner URL end-points within their ASP.NET web applications. This blog post summarizes a few approaches you can take to cleanly map or rewrite URLs with ASP.NET, and have the option to structure the URLs of your application however you want.
Why does URL mapping and rewriting matter?
The most common scenarios where developers want greater flexibility with URLs are:
1) Handling cases where you want to restructure the pages within your web application, and you want to ensure that people who have bookmarked old URLs don't break when you move pages around. Url-rewriting enables you to transparently forward requests to the new page location without breaking browsers.
2) Improving the search relevancy of pages on your site with search engines like Google, Yahoo and Live. Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites, which can often increase the chance of someone clicking your link. Moving from using querystring arguments to instead use fully qualified URL's can also in some cases increase your priority in search engine results. Using techniques that force referring links to use the same case and URL entrypoint (for example: weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) can also avoid diluting your pagerank across multiple URLs, and increase your search results.
In a world where search engines increasingly drive traffic to sites, extracting any little improvement in your page ranking can yield very good ROI to your business. Increasingly this is driving developers to use URL-Rewriting and other SEO (search engine optimization) techniques to optimize sites (note that SEO is a fast moving space, and the recommendations for increasing your search relevancy evolve monthly). For a list of some good search engine optimization suggestions, I'd recommend reading the SSW Rules to Better Google Rankings, as well as MarketPosition's article on how URLs can affect top search engine ranking.
Sample URL Rewriting Scenario
For the purpose of this blog post, I'm going to assume we are building a set of e-commerce catalog pages within an application, and that the products are organized by categories (for example: books, videos, CDs, DVDs, etc).
Let's assume that we initially have a page called "Products.aspx" that takes a category name as a querystring argument, and filters the products accordingly. The corresponding URLs to this Products.aspx page look like this:
http://www.store.com/products.aspx?category=books
http://www.store.com/products.aspx?category=DVDs
http://www.store.com/products.aspx?category=CDs

Rather than use a querystring to expose each category, we want to modify the application so that each product category looks like a unique URL to a search engine, and has the category keyword embedded in the actual URL (and not as a querystring argument). We'll spend the rest of this blog post going over 4 different approaches that we could take to achieve this.
Approach 1: Use Request.PathInfo Parameters Instead of QueryStrings
The first approach I'm going to demonstrate doesn't use Url-Rewriting at all, and instead uses a little-known feature of ASP.NET - the Request.PathInfo property. To help explain the usefulness of this property, consider the below URL scenario for our e-commerce store:
http://www.store.com/products.aspx/Books
http://www.store.com/products.aspx/DVDs
http://www.store.com/products.aspx/CDs
One thing you'll notice with the above URLs is that they no longer have Querystring values - instead the category parameter value is appended on to the URL as a trailing /param value after the Products.aspx page handler name. An automated search engine crawler will then interpret these URLs as three different URLs, and not as one URL with three different input values (search engines ignore the filename extension and just treat it as another character within the URL).
You might wonder how you handle this appended parameter scenario within ASP.NET. The good news is that it is pretty simple. Simply use the Request.PathInfo property, which will return the content immediately following the products.aspx portion of the URL. So for the above URLs, Request.PathInfo would return "/Books", "/DVDs", and "/CDs" (in case you are wondering, the Request.Path property would return "/products.aspx").
You could then easily write a function to retrieve the category like so (the below function strips out the leading slash and returning just "Books", "DVDs" or "CDs"):

Function GetCategory() As String

If
(Request.PathInfo.Length = 0) Then
Return
""
Else
Return
Request.PathInfo.Substring(1)
End If

End Function

Sample Download: A sample application that I've built that shows using this technique can be downloaded here. What is nice about this sample and technique is that no server configuration changes are required in order to deploy an ASP.NET application using this approach. It will also work fine in a shared hosting environment.
Approach 2: Using an HttpModule to Perform URL Rewriting
An alternative approach to the above Request.PathInfo technique would be to take advantage of the HttpContext.RewritePath() method that ASP.NET provides. This method allows a developer to dynamically rewrite the processing path of an incoming URL, and for ASP.NET to then continue executing the request using the newly re-written path.
For example, we could choose to expose the following URLs to the public:

http://www.store.com/products/Books.aspx
http://www.store.com/products/DVDs.aspx
http://www.store.com/products/CDs.aspx

This looks to the outside world like there are three separate pages on the site (and will look great to a search crawler). By using the HttpContext.RewritePath() method we can dynamically re-write the incoming URLs when they first reach the server to instead call a single Products.aspx page that takes the category name as a Querystring or PathInfo parameter instead. For example, we could use an an Application_BeginRequest event in Global.asax like so to do this:
void Application_BeginRequest(object sender, EventArgs e) {

string fullOrigionalpath = Request.Url.ToString();

if
(fullOrigionalpath.Contains("/Products/Books.aspx")) {
Context.RewritePath(
"/Products.aspx?Category=Books");
}
else if (fullOrigionalpath.Contains("/Products/DVDs.aspx")) {
Context.RewritePath(
"/Products.aspx?Category=DVDs");
}
}

The downside of manually writing code like above is that it can be tedious and error prone. Rather than do it yourself, I'd recommend using one of the already built HttpModules available on the web for free to perform this work for you. Here a few free ones that you can download and use today:
These modules allow you to declaratively express matching rules within your application's web.config file. For example, to use the UrlRewriter.Net module within your application's web.config file to map the above URLs to a single Products.aspx page, we could simply add this web.config file to our application (no code is required):

<?xml version="1.0"?>
<configuration>

<configSections>
<section name="rewriter"
requirePermission
="false"
type
="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</
configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
</
httpModules>

</system.web>

<rewriter>
<rewrite url="~/products/books.aspx" to="~/products.aspx?category=books" />
<
rewrite url="~/products/CDs.aspx" to="~/products.aspx?category=CDs" />
<
rewrite url="~/products/DVDs.aspx" to="~/products.aspx?category=DVDs" />
</
rewriter>
</configuration>

The HttpModule URL rewriters above also add support for regular expression and URL pattern matching (to avoid you having to hard-code every URL in your web.config file). So instead of hard-coding the category list, you could re-write the rules like below to dynamically pull the category from the URL for any "/products/[category].aspx" combination:

<rewriter>
<rewrite url="~/products/(.+).aspx" to="~/products.aspx?category=$1" /> </rewriter>

This makes your code much cleaner and super extensible.
Sample Download: A sample application that I've built that shows using this technique with the UrlRewriter.Net module can be downloaded here.
What is nice about this sample and technique is that no server configuration changes are required in order to deploy an ASP.NET application using this approach. It will also work fine in a medium trust shared hosting environment (just ftp/xcopy to the remote server and you are good to go - no installation required).
Approach 3: Using an HttpModule to Perform Extension-Less URL Rewriting with IIS7
The above HttpModule approach works great for scenarios where the URL you are re-writing has a .aspx extension, or another file extension that is configured to be processed by ASP.NET. When you do this no custom server configuration is required - you can just copy your web application up to a remote server and it will work fine.
There are times, though, when you want the URL to re-write to either have a non-ASP.NET file extension (for example: .jpg, .gif, or .htm) or no file-extension at all. For example, we might want to expose these URLs as our public catalog pages (note they have no .aspx extension):

http://www.store.com/products/Books
http://www.store.com/products/DVDs
http://www.store.com/products/CDs
With IIS5 and IIS6, processing the above URLs using ASP.NET is not super easy. IIS 5/6 makes it hard to perform URL rewriting on these types of URLs within ISAPI Extensions (which is how ASP.NET is implemented). Instead you need to perform the rewriting earlier in the IIS request pipeline using an ISAPI Filter. I'll show how to-do this on IIS5/6 in the Approach 4 section below.
The good news, though, is that IIS 7.0 makes handling these types of scenarios super easy. You can now have an HttpModule execute anywhere within the IIS request pipeline - which means you can use the URLRewriter module above to process and rewrite extension-less URLs (or even URLs with a .asp, .php, or .jsp extension). Below is how you would configure this with IIS7:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<configSections>
<section name="rewriter"
requirePermission
="false"
type
="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</
configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
</
httpModules>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
</
modules>

<validation validateIntegratedModeConfiguration="false" />

</
system.webServer>

<rewriter>
<rewrite url="~/products/(.+)" to="~/products.aspx?category=$1" />
</
rewriter>
</configuration>

Note the "runAllManagedModulesForAllRequests" attribute that is set to true on the <modules> section within <system.webServer>. This will ensure that the UrlRewriter.Net module from Intelligencia, which was written before IIS7 shipped, will be called and have a chance to re-write all URL requests to the server (including for folders). What is really cool about the above web.config file is that:
1) It will work on any IIS 7.0 machine. You don't need an administrator to enable anything on the remote host. It will also work in medium trust shared hosting scenarios.
2) Because I've configured the UrlRewriter in both the <httpModules> and IIS7 <modules> section, I can use the same URL Rewriting rules for both the built-in VS web-server (aka Cassini) as well as on IIS7. Both fully support extension-less URLRewriting. This makes testing and development really easy.
IIS 7.0 server will ship later this year as part of Windows Longhorn Server, and will support a go-live license with the Beta3 release in a few weeks. Because of all the new hosting features that have been added to IIS7, we expect hosters to start aggressively offering IIS7 accounts relatively quickly - which means you should be able to start to take advantage of the above extension-less rewriting support soon. We'll also be shipping a Microsoft supported URL-Rewriting module in the IIS7 RTM timeframe that will be available for free as well that you'll be able to use on IIS7, and which will provide nice support for advanced re-writing scenarios for all content on your web-server.
Sample Download: A sample application that I've built that shows using this extension-less URL technique with IIS7 and the UrlRewriter.Net module can be downloaded here.
Approach 4: ISAPIRewrite to enable Extension-less URL Rewriting for IIS5 and IIS6
If you don't want to wait for IIS 7.0 in order to take advantage of extension-less URL Rewriting, then your best best is to use an ISAPI Filter in order to re-write URLs. There are two ISAPI Filter solutions that I'm aware of that you might want to check-out:
  • Helicon Tech's ISAPI Rewrite: They provide an ISAPI Rewrite full product version for $99 (with 30 day free trial), as well as a ISAPI Rewrite lite edition that is free.
  • Ionic's ISAPI Rewrite: This is a free download (both source and binary available)
I actually don't have any first-hand experience using either of the above solutions - although I've heard good things about them. Scott Hanselman and Jeff Atwood recently both wrote up great blog posts about their experiences using them, and also provided some samples of how to configure the rules for them. The rules for Helicon Tech's ISAPI Rewrite use the same syntax as Apache's mod_rewrite. For example (taken from Jeff's blog post):

[ISAPI_Rewrite]
# fix missing slash on folders
# note, this assumes we have no folders with periods!
RewriteCond Host: (.*)
RewriteRule ([^.?]+[^.?/]) http\://$1$2/ [RP]

# remove index pages from URLs
RewriteRule (.*)/default.htm$ $1/ [I,RP]
RewriteRule (.*)/default.aspx$ $1/ [I,RP]
RewriteRule (.*)/index.htm$ $1/ [I,RP]
RewriteRule (.*)/index.html$ $1/ [I,RP]

# force proper www. prefix on all requests
RewriteCond %HTTP_HOST ^test\.com [I]
RewriteRule ^/(.*) http://www.test.com/$1 [RP]

# only allow whitelisted referers to hotlink images
RewriteCond Referer: (?!http://(?:www\.good\.com|www\.better\.com)).+
RewriteRule .*\.(?:gif|jpg|jpeg|png) /images/block.jpg [I,O]

Definitely check out Scott's post and Jeff's post to learn more about these ISAPI modules, and what you can do with them.
Note: One downside to using an ISAPI filter is that shared hosting environments typically won't allow you to install this component, and so you'll need either a virtual dedicated hosting server or a dedicated hosting server to use them. But, if you do have a hosting plan that allows you to install the ISAPI, it will provide maximum flexibility on IIS5/6 - and tide you over until IIS7 ships.
Handling ASP.NET PostBacks with URL Rewriting
One gotcha that people often run into when using ASP.NET and Url-Rewriting has to-do with handling postback scenarios. Specifically, when you place a <form runat="server"> control on a page, ASP.NET will automatically by default output the "action" attribute of the markup to point back to the page it is on. The problem when using URL-Rewriting is that the URL that the <form> control renders is not the original URL of the request (for example: /products/books), but rather the re-written one (for example: /products.aspx?category=books). This means that when you do a postback to the server, the URL will not be your nice clean one.
With ASP.NET 1.0 and 1.1, people often resorted to sub-classing the <form> control and created their own control that correctly output the action to use. While this works, it ends up being a little messy - since it means you have to update all of your pages to use this alternate form control, and it can sometimes have problems with the Visual Studio WYSIWYG designer.
The good news is that with ASP.NET 2.0, there is a cleaner trick that you can use to rewrite the "action" attribute on the <form> control. Specifically, you can take advantage of the new ASP.NET 2.0 Control Adapter extensibility architecture to customize the rendering of the <form> control, and override its "action" attribute value with a value you provide. This doesn't require you to change any code in your .aspx pages. Instead, just add a .browser file to your /app_browsers folder that registers a Control Adapter class to use to output the new "action" attribute:


You can see a sample implementation I created that shows how to implement a Form Control Adapter that works with URLRewriting in my sample here. It works for both the Request.PathInfo and UrlRewriter.Net module approaches I used in Approach 1 and 2 above, and uses the Request.RawUrl property to retrieve the original, un-rewritten, URL to render. With the ISAPIRewrite filter in Approach 4 you can retrieve the Request.ServerVariables["HTTP_X_REWRITE_URL"] value that the ISAPI filter uses to save the original URL instead.
My FormRewriter class implementation above should work for both standard ASP.NET and ASP.NET AJAX 1.0 pages (let me know if you run into any issues).
Handling CSS and Image Reference Correctly
One gotcha that people sometime run into when using Url Rewriting for the very first time is that they find that their image and CSS stylesheet references sometimes seem to stop working. This is because they have relative references to these files within their HTML pages - and when you start to re-write URLs within an application you need to be aware that the browser will often be requesting files in different logical hierarchy levels than what is really stored on the server.
For example, if our /products.aspx page above had a relative reference to "logo.jpg" in the .aspx page, but was requested via the /products/books.aspx url, then the browser will send a request for /products/logo.jpg instead of /logo.jpg when it renders the page. To reference this file correctly, make sure you root qualify CSS and Image references ("/style.css" instead of "style.css"). For ASP.NET controls, you can also use the ~ syntax to reference files from the root of the application (for example: <asp:image imageurl="~/images/logo.jpg" runat="server"/>
Hope this helps,

Monday, July 23, 2012

How to: Configure Published Web Sites


Publishing a Web site compiles the executable files in the Web site and then writes the output to a folder that you specify. Because of configuration differences between your test environment and the location where you publish your application, the published application might behave differently than application does in the test environment. If so, you might need to change configuration settings after publishing the site. For more information, see Configuring ASP.NET Applications.

To configure a published Web site

  1. Check the configuration of your original site and note the settings that need to be made for the published Web site. Settings that commonly differ between a development site and a production site include:
    Because configuration settings are inherited, you might need to look at local versions of the Machine.config file or the root Web.config file in the %SystemRoot%\Microsoft.NET\Framework\version\CONFIG directory as well as in any Web.config files in your application.
    NoteNote
    If you do not have permission to view the root configuration files, you can create a file that contains a complete list of configuration settings for your Web site, formatted as a configuration file, using the code described in How to: View Inherited and Local Configuration Settings Programmatically.
    For definitions of configuration settings, see General Configuration Settings (ASP.NET) and ASP.NET Configuration Settings.
  2. After you publish a Web site, test all of the Web pages of your published site under different user accounts.
    If your published Web site behaves differently than the original, you might need to make configuration changes on the published site.
  3. To view configuration settings on the published site, open the remote site in Visual Web Developer and edit the remote site's Web.config file directly. Alternatively, you can use the other configuration methods described in Editing ASP.NET Configuration Files.
    NoteNote
    You cannot use the Web Site Administration Tool to configure remote Web sites.
  4. Compare the configuration settings of the published Web site to those of the original Web site. On the Web server where the published site is located, you might need to look at the Machine.config file or the root Web.config file in the %SystemRoot%\Microsoft.NET\Framework\version\CONFIG directory of the remote computer in addition to your application's Web.config file. You can create a file that contains a complete list of configuration settings for your Web site, formatted as a configuration file, using the code described in How to: View Inherited and Local Configuration Settings Programmatically.
  5. In the configuration file of the published site, edit the deployment element and set its retail attribute to true.
    This overrides the local settings for tracing and debug mode in the page or in an application-level Web.config file, which improves the security of the Web site to fit into a production environment.
  6. Encrypt sensitive configuration settings such as security settings and connection strings. For more information, see Encrypting Configuration Information Using Protected Configuration.

How to: Publish Web Sites (Visual Studio) (ASP.NET)


Before publishing a Web site

  1. Check the configuration of your original site and make note of any settings that need to exist at the remote location. Specifically, check settings such as connection strings, membership settings, and other security settings.
  2. Check the configuration of your original site and make note of any settings that need to be changed on the published Web site. For example, you might want to disable debugging, tracing, and custom errors after you publish your Web site.
    Because configuration settings are inherited, you might need to look at the Machine.config file or the root Web.config file in the SystemRoot\Microsoft.NET\Framework\version\CONFIG directory as well as any Web.config files in your application. If you do not have permission to view the root configuration files, you can output a file that contains a complete list of configuration settings for your Web site, formatted as a proper configuration file, using the code example in How to: View Inherited and Local Configuration Settings Programmatically.
    For definitions of configuration settings, see General Configuration Settings (ASP.NET) and ASP.NET Configuration Settings.

To publish a Web site

  1. On the Build menu, click Publish Web Site.
  2. In the Publish Web Site dialog box, click the ellipsis button (…) to browse to the location to which you want to publish the Web site.
    You can write the Web site output to a local or shared folder, to an FTP site, or to a Web site that you access with a URL. You must have Create and Write permissions in the target location.
  3. To be able to change the layout (but not the code) of .aspx files after publishing the Web site, select the Allow this precompiled site to be updateable check box.
  4. To name strongly named assemblies using a key file or a key container, select the Enable strong naming on precompiled assemblies check box, and then click OK.
    Publishing status is displayed in the taskbar. Depending on the connection speed, the size of the site and the types of content files, publishing time can vary. When publishing is completed, the status of Publish succeeded is displayed.
  5. Make any configuration changes that are necessary for your site. For more information, see How to: Configure Published Web Sites. You might also want to encrypt specific configuration settings. For more information, see Encrypting Configuration Information Using Protected Configuration.

Sunday, July 22, 2012

How to use autopostback in asp.net ?


  • AutoPostBack is built into the form-based server controls, and when enabled, automatically posts the page back to the server whenever the value of the control in question is changed. Because of the additional server requests it causes, it's not something you'll want to enable for all your controls, but for things that affect page display or change choices further down the form, it can be really handy. Not to mention the fact that it will save you a lot of time and headaches over trying to implement something similar on your own. Not that it's really all that complex to do on your own if you're good with javascript, but it's hard to get any simpler then just setting

    AutoPostBack="True"
    
    
  • AutoPostBack is a feature that is availabel on a few controls,the main purpose of it is that if any change happened on a control by the client,it should postback to the server to handle that change at serverside,handling that change at serverside could be for many reasons i.e storing a value to DB,make changes to the page depending on it,..etc
i.e. You have a dropdownlist that has items (department names for example),if a user selected a department,depending on selected item you want to fill a gridview (fill all the employess of that department),as you can see,what must be shown at the gridview depends on what the user selects from the dropdownlist,this is the general concept,right now I don't have a code example on that,but I have link to a simple example but it's not different than the general concept I menthioned(in the example,instead of changing the label text,you can connect to DB,fetch records then fill it to a gridview

Monday, July 16, 2012

Why the Genocide of Burmese Muslims?


After reading and watching helplessly the recent massacre of minority Burmese Muslims by the Buddhist majority, let not another hypocrite sing that phoney and repugnant 'song' about Buddhists being "peaceful."

In June 2012, hundreds Burmese Muslims have been butchered, and many more injured and made homeless in Burma as a result religious intolerance by the Buddhist majority. The Burmese military government, far from trying to resolve the problem and protect the minority, has been silently conniving with the rioters by creating greater hardships for the Muslim minority.

The reason of this June 2012 riot is unknown except for the periodical outbursts of the Burmese Buddhists to show their might and vent their anger on the helpless minority. It is commonly accepted that the June 2012 massacre of Burmese Muslims was intentionally orchestrated by the rioters in collaboration with the government. Yet the world, including the UN, is conveniently silent. The brazenly hypocritical and unscrupulous woman, Aung San Suu Kyi, is very prompt at accusing the Burmese military of human rights violations when she is under house arrest. But she finds nothing wrong when the military helps the Buddhist mobs to murder the innocent Muslim minority of her country.

As in India, anti-Muslim riots are nothing unusual in Burma. Violence in Burma against Muslims have been erupting periodically since the 1920s based simply on religious intolerance by the Buddhist majority.

The Muslims of Burma mainly belong to the Arakan state in western Burma. They are known as Rohingya or Burmese Muslims. The term "Rohingya" has been derived from the Arabic word "Raham" meaning sympathy. Muslim settlements began being established in the Arakan province of Burma since the arrival of the Arabs in the 8th century. Presently about 800,000 Rohingya live in Burma. The United Nations describes them as "one of the world’s most persecuted minorities." Yet it has never bothered to help them.

Religious freedom for Muslims in Burma has been systematically curbed. In the post 9/11 era, random accusations of "terrorism" against Muslims have become a common form of persecution and harassment by Burmese Buddhists. Burmese Government does not consider Rohingya Muslims as citizens and they are hated by the Buddhist majority. Rohingya Muslims in Burma have long demanded recognition as an indigenous ethnic group with full citizenship by birthright. But the Government regards them as illegal immigrants from neighboring Bangladesh and denies them citizenship.

"Nobel Prize winner," Aung San Suu Kyi, does not consider Muslims as citizens. Speaking at London School of Economics meeting on June 2012 during her visit to the UK, she said "Rohingya Muslims should not be considered citizens." Later during her press conference at Downing Street, she did not condemn the killings of Rohingya Muslims taking place in Burma. Instead, she simply said that this "ethnic conflict should be investigated and dealt with wisdom." It wasn't just an insufficient response but a very shocking one from someone supposed to have won a "Noble Peace Prize."

The notorious master hypocrite and undercover CIA agent, Dalai Lama, continues to globe trot without mentioning a single word of the dangerously growing Buddhist intolerance in Burma, Thailand, Tibet and across the world. Such intolerance and persecution invariably result in resistance by the oppressed. Many Muslims have joined armed resistance groups, fighting for greater freedom in Burma.

On June 3rd 2012, eight Muslims returning to Rangoon in a bus after visiting a Masjid in the Arakan province were attacked by a mob of hundreds of Buddhists and slaughtered brutally. An eye-witness reported that after the mass murder "the culprits were celebrating triumph spitting and tossing wine and alcohol on the dead bodies lying on the road."

"These innocent people have been killed like animals," said Abu Tahay, of the National Democratic Party for Development, which represents the country’s much-persecuted stateless Muslim Rohingya community.

The Rohingya Muslims of Burma have continued to suffer from human rights violations under the Burmese junta since 1970s. Over the years thousands of Rohingya refugees have fled to neighboring countries like Thailand, Indonesia and Bangladesh etc. Even as refugees they have been facing hardships and have suffered persecution by the Thai government. In February 2009, a group of 5 boats packed with Burmese Rohingya Muslims were taken out and abandoned in the open sea by the Thai army. Four of these boats sank in a storm and one was washed ashore near the Indonesian islands. The few survivors who were rescued by Indonesian authorities told horrific stories of being captured and beaten by the Thai military and then abandoned at open sea.

Being "peaceful" or "humble" (as claimed by their biased supporters) is a far cry concerning the Burmese Buddhists. Their vindictive temperament prowls for vendetta, waiting to use even the most insignificant occurrence as an excuse to perpetrate violence on Burmese Muslims. At any time, if there's some ethnic disturbance between Muslims and Buddhists/Hindus in any other country, the Burmese Buddhists waste no time going on a murderous spry killing the Muslim minority in Burma. If there is the slightest of trouble between Muslims and non-Muslims in Indonesia, it's taken as a pretext to kill Muslims in Burma by Buddhist mobs. The destruction of the statues in Bamiyan (Afghanistan), created an immediate excuse to commit violence against Muslims in Burma in 2001. The firebrand Buddhist monks demanded a Muslim masjid to be destroyed in retaliation. Mobs of Buddhists led by monks, vandalized Muslim-owned businesses and property in Burma, and attacked and killed Muslims in Muslim communities.

Gruesome images of murdered Rohingya Muslims in the recent June 2012 riots in Burma have been circulated on websites, resulting in protests in several Muslim countries and by various human rights activists around the world demanding justice & protection in Burma for the minority, but has fallen on deaf ears as usual, getting little or no coverage from mainstream news channels.

Thursday, July 12, 2012

SIMPLE - How to Know Country Location of a user - asp.net C#


using System.Globalization; 
 
string name = RegionInfo.CurrentRegion.DisplayName;

ASP.NET C# - IP to Country Name and Flag


Below code will display country flag of an ip.

It can be modified to display country name too.
Code is build on c# class found at http://www.maxmind.com/app/csharp and uses data from http://www.maxmind.com/app/geolitecountry

You need to download http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz and extract it to same folder with your aspx page (try winrar to extract .gz files)

You also need to download flag icons from http://www.famfamfam.com/lab/icons/flags/ and extract in to flags folder



Upload it to your server and call it like
<img src="iptoflag.aspx?ip=IPHERE" alt="" />


iptoflag.aspx

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
protected void Page_Load(object sender, EventArgs e)
{
string visitorIp = ReturnAlphaNumeric(Request.QueryString["ip"]);
if (visitorIp==null)
visitorIp = Request.ServerVariables["REMOTE_ADDR"];
Response.StatusCode = 200;
Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
Response.Cache.SetCacheability(HttpCacheability.Public);
try
{
Response.ContentType = "image/png";
FileStream flag = new FileStream(Server.MapPath("flags/" + GetCountryFlag(visitorIp) + ".png"), FileMode.Open, FileAccess.Read, FileShare.Read);
long FileSize;
FileSize = flag.Length;
byte[] getContent = new byte[(int)FileSize];
flag.Read(getContent, 0, (int)flag.Length);
flag.Close();
Response.BinaryWrite(getContent);
}
catch (Exception ee)
{
Response.ContentType = "text/html";
Response.Write(ee.ToString());
}
}
public static string ReturnAlphaNumeric(string input)
{
try
{
return Regex.Replace(input, @"[^0-9\.]", "").ToString();
}
catch
{
return "127.0.0.1";
}
}
public static string GetCountryFlag(string ip)
{
string cc = "-";
//string cn = "Unknown";
using (CountryLookup cl = new CountryLookup(HttpContext.Current.Server.MapPath("GeoIP.dat")))
{
try
{
cc = cl.lookupCountryCode(ip);
}
catch (Exception ex)
{
cc = "-";
}
}
return cc;
}
public class CountryLookup : IDisposable
{
private FileStream fileInput;
private bool _close;
private static long COUNTRY_BEGIN = 16776960;
private static string[] countryCode =
{ "-","AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR","AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ",
"EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ",
"LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA",
"RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","RS","ZA","ZM","ME","ZW","A1","A2",
"O1","AX","GG","IM","JE","BL","MF"
};
private static string[] countryName =
{"Unknown","Asia/Pacific Region","Europe","Andorra","United Arab Emirates","Afghanistan","Antigua and Barbuda","Anguilla","Albania","Armenia","Netherlands Antilles","Angola","Antarctica","Argentina","American Samoa","Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina","Barbados","Bangladesh","Belgium",
"Burkina Faso","Bulgaria","Bahrain","Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas","Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada","Cocos (Keeling) Islands","Congo, The Democratic Republic of the","Central African Republic","Congo","Switzerland","Cote D'Ivoire",
"Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba","Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany","Djibouti","Denmark","Dominica","Dominican Republic","Algeria","Ecuador","Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland","Fiji","Falkland Islands (Malvinas)",
"Micronesia, Federated States of","Faroe Islands","France","France, Metropolitan","Gabon","United Kingdom","Grenada","Georgia","French Guiana","Ghana","Gibraltar","Greenland","Gambia","Guinea","Guadeloupe","Equatorial Guinea","Greece","South Georgia and the South Sandwich Islands","Guatemala","Guam","Guinea-Bissau","Guyana",
"Hong Kong","Heard Island and McDonald Islands","Honduras","Croatia","Haiti","Hungary","Indonesia","Ireland","Israel","India","British Indian Ocean Territory","Iraq","Iran, Islamic Republic of","Iceland","Italy","Jamaica","Jordan","Japan","Kenya","Kyrgyzstan","Cambodia","Kiribati","Comoros","Saint Kitts and Nevis",
"Korea, Democratic People's Republic of","Korea, Republic of","Kuwait","Cayman Islands","Kazakstan","Lao People's Democratic Republic","Lebanon","Saint Lucia","Liechtenstein","Sri Lanka","Liberia","Lesotho","Lithuania","Luxembourg","Latvia","Libyan Arab Jamahiriya","Morocco","Monaco","Moldova, Republic of","Madagascar",
"Marshall Islands","Macedonia","Mali","Myanmar","Mongolia","Macau","Northern Mariana Islands","Martinique","Mauritania","Montserrat","Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique","Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua","Netherlands",
"Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama","Peru","French Polynesia","Papua New Guinea","Philippines","Pakistan","Poland","Saint Pierre and Miquelon","Pitcairn Islands","Puerto Rico","Palestinian Territory","Portugal","Palau","Paraguay","Qatar","Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia",
"Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena","Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino","Senegal","Somalia","Suriname","Sao Tome and Principe","El Salvador","Syrian Arab Republic","Swaziland","Turks and Caicos Islands","Chad","French Southern Territories","Togo",
"Thailand","Tajikistan","Tokelau","Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey","Trinidad and Tobago","Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda","United States Minor Outlying Islands","United States","Uruguay","Uzbekistan","Holy See (Vatican City State)","Saint Vincent and the Grenadines",
"Venezuela","Virgin Islands, British","Virgin Islands, U.S.","Vietnam","Vanuatu","Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia","South Africa","Zambia","Montenegro","Zimbabwe","Anonymous Proxy","Satellite Provider",
"Other","Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy","Saint Martin"};
public CountryLookup(string fileName)
{
try
{
fileInput = new FileStream(fileName, FileMode.Open, FileAccess.Read);
}
catch (FileNotFoundException e)
{
throw new IOException("File " + fileName + " not found.");
}
}
public string lookupCountryCode(string str)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
catch (FormatException e)
{
return "-";
}
return lookupCountryCode(addr);
}
private long addrToNum(IPAddress addr)
{
long ipnum = 0;
byte[] b = addr.GetAddressBytes();
for (int i = 0; i < 4; ++i)
{
long y = b[i];
if (y < 0)
{
y += 256;
}
ipnum += y << ((3 - i) * 8);
}
//HttpContext.Current.Response.Write(ipnum);
return ipnum;
}
public string lookupCountryCode(IPAddress addr)
{
return (countryCode[(int)seekCountry(0, addrToNum(addr), 31)]);
}
public string lookupCountryName(string str)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
catch (FormatException e)
{
return "Unknown";
}
return lookupCountryName(addr);
}
public string lookupCountryName(IPAddress addr)
{
return (countryName[(int)seekCountry(0, addrToNum(addr), 31)]);
}
private long seekCountry(long offset, long ipnum, int depth)
{
byte[] buf = new byte[6];
long[] x = new long[2];
if (depth < 0)
{
//HttpContext.Current.Response.Write("Error seeking country.");
return 0; // N/A
}
try
{
fileInput.Seek(6 * offset, 0);
fileInput.Read(buf, 0, 6);
}
catch (IOException e)
{
throw new IOException("IO Exception");
}
for (int i = 0; i < 2; i++)
{
x[i] = 0;
for (int j = 0; j < 3; j++)
{
int y = buf[i * 3 + j];
if (y < 0)
{
y += 256;
}
x[i] += (y << (j * 8));
}
}
if ((ipnum & (1 << depth)) > 0)
{
if (x[1] >= COUNTRY_BEGIN)
{
return x[1] - COUNTRY_BEGIN;
}
return seekCountry(x[1], ipnum, depth - 1);
}
else
{
if (x[0] >= COUNTRY_BEGIN)
{
return x[0] - COUNTRY_BEGIN;
}
return seekCountry(x[0], ipnum, depth - 1);
}
}
public void Dispose()
{
if (_close && fileInput != null)
{
fileInput.Close();
fileInput = null;
}
}
}