Friday, November 28, 2014

when consuming web services in .net hosted over IIS, getting error "Request format is unrecognized for URL ....."

Server Error in '/' Application.

Request format is unrecognized for URL unexpectedly ending in '/JsonCityList'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/JsonCityList'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[InvalidOperationException: Request format is unrecognized for URL 
unexpectedly ending in '/JsonCityList'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler
(Type type, HttpContext context, HttpRequest request, 
HttpResponse response)+713315
System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler
(HttpContext context, String verb, String url, String filePath) +308
System.Web.Script.Services.ScriptHandlerFactory.GetHandler
(HttpContext context, String requestType, String url, 
String pathTranslated) +89
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication
.IExecutionStep.Execute() +516
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously) +288



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408



Fixing this issue need to add the following in web.config file.



<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>

Saturday, November 1, 2014

Difference Between Stored Procedure and User Defined Function in SQL Server



User Defined FunctionStored Procedure
 Function must return a value.Stored Procedure may or not return values.
Will allow only Select statements, it will not allow us to use DML statements.Can have select statements as well as DML statements such as insert, update, delete and so on
 It will allow only input parameters, doesn't support output parameters.It can have both input and output parameters.
It will not allow us to use try-catch blocks.For exception handling we can use try catch blocks.
Transactions are not allowed within functions.Can use transactions within Stored Procedures.
We can use only table variables, it will not allow using temporary tables.Can use both table variables as well as temporary table in it.
Stored Procedures can't be called from a function.Stored Procedures can call functions.
 Functions can be called from a select statement.Procedures can't be called from Select/Where/Having and so on statements. Execute/Exec statement can be used to call/execute Stored Procedure.
A UDF can be used in join clause as a result set.Procedures can't be used in Join clause

Friday, October 24, 2014

Get client's Geo location, country, city,region using Google Apps and Java Script.



Get client's Geo location, country, city,region  using Google Apps and Java Script.


<!DOCTYPE html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Get web visitor's location</title>
     
    </head>
    <body>
    <div id="yourinfo"></div>
    <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
    <script type="text/javascript">
        if (google.loader.ClientLocation) {
            visitor_lat = google.loader.ClientLocation.latitude;
            visitor_lon = google.loader.ClientLocation.longitude;
            visitor_city = google.loader.ClientLocation.address.city;
            visitor_region = google.loader.ClientLocation.address.region;
            visitor_country = google.loader.ClientLocation.address.country;
            visitor_countrycode = google.loader.ClientLocation.address.country_code;
         
            document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
        }
        else {
            document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
        }
    </script>
    </body>
</html>

RSS feed is not working in Chrome browser.




Chrome browser does not support RSS feed while working with Mozila and IE. When I want to open RSS feed in Chrome browser, it shows in XML format.when I applied XSL with RSS file, it was working fine.




I have copied here sample XML file and XSL as well. Need to put in same folder and host at IIS and try to access rssfeeds.xml at chrome browser.

File Name - rssfeeds.xml (.rss can also be as extension of this)

<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet href="rss.xsl" type="text/xsl" media="screen"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">

  <channel>
    <title>xyz Updates</title>
    <link>http://www.xyz.com/</link>
    <description>xyz Updates</description>
    <language>en-us</language>
    <pubDate>26 Nov 2013 21:29:00 CST</pubDate>
    <lastBuildDate>26 Nov 20013 20:00:00 CST</lastBuildDate>
    <docs>http://xyz.com</docs>
    <generator>Weblog Editor 2.0</generator>
    <managingEditor>admin@xyz.com (WEBSITE Webmaster)</managingEditor>
    <webMaster>admin@xyz.com (WEBSITE Webmaster)</webMaster>
    <atom:link href="http://www.xyz.com" rel="self" type="application/rss+xml" />

    <item>
      <title>xyz</title>
      <link>http://www.xyz.com</link>
      <description>Connecting Homeowners to Contractors</description>
      <pubDate>26 Nov 2013 21:05:00 CST</pubDate>
      <guid>http://www.xyz.com</guid>
    </item>
    <item>
      <title>Find a pro in Vancouver</title>
      <link>http://www.xyz.com/city/vancouver</link>
      <description>Connecting Homeowners to Contractors</description>
      <pubDate>26 Nov 2013 21:05:00 CST</pubDate>
      <guid>http://www.xyz.com/city/vancouver</guid>
    </item>
  </channel>
</rss>

--------------------------------------------------------------------------------------------
File Name - rss.xsl



<?xml version="1.0"?>


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wfw="http://wellformedweb.org/CommentAPI/">
 <xsl:output method="html"/>
 <xsl:template match="/">
 <xsl:apply-templates select="/rss/channel"/>
 </xsl:template>
 <xsl:template match="/rss/channel">
 <div>
 <h3><xsl:value-of select="title"/></h3>
   <br/>
 <p><xsl:value-of select="description"/></p>
   <br/>
   <br/>
 </div>
 <div>
 <xsl:apply-templates select="item"/>
 </div>
 </xsl:template>
 <xsl:template match="/rss/channel/item">
 <div>
 <a href="{link}" rel="bookmark"><xsl:value-of select="title"/></a>
   <br/>
   <br/>
 <xsl:value-of select="description"/>
   <br/>
 </div>
 </xsl:template>

<xsl:output method="html"
            encoding="UTF-8"
            indent="no"/>
</xsl:stylesheet>


How to get IP of Client?

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "//freegeoip.net/json/",
             
                dataType: "text",
                timeout: 2000,
                success: function (data) {

                   var json = $.parseJSON(data);
                     alert(json.ip);
                   
                },
                error: function (data) {
                    alert("error");
                }
             
            });
         
        });

     
    </script>
</head>
<body>
 
</body>
</html>

ASP.NET Caching: Techniques and Best Practices

http://msdn.microsoft.com/en-us/library/aa478965.aspx

Improve the Performance of an Web Application using ASP.NET

  1. Viewstate
    View state is the wonder mechanism that shows the details of the entry posted on the server. It is loaded every time ifrom the server. This option looks like an extra feature for the end users. This needs to be loaded from the server and it adds more size to the page but it will affect the performance when we have many controls in the page, like user registration. So, if there is no need for it then it can be disabled.

    EnableViewState = "false" needs to be given based on the requirements. It can be given at the control, page and config level settings.
     
  2. Avoid Session and Application Variables
    A Session is a storage mechanism that helps developers to take values across the pages. It will be stored based on the session state chosen. By default it will be stored in the Inproc. That default settings uses IIS. When this Session variable is used in a page that is accessed by many numbers then it will occupy more memory allocation and gives additional overhead to the IIS. It will make the performance slow.

    It can be avoided for most scenarios . If you want to send the information across pages then we can use a Cross Post-back, Query string with encryption. If you want to store the information within the page then caching the object is the best way.
     
  3. Use Caching
    ASP.Net has the very significant feature of a caching mechanism. It gives more performance and avoids the client/server process. There are three types of caching in ASP.Net.

    If there is any static content in the full pages then it should be used with the Output cache. What it does is, it stores the content on IIS. When the page is requested it will be loaded immediately from the IIS for the certain period of time. Similarly Fragment paging can be used to store the part of the web page.
     
  4. Effectively use CSS and Script files
    If you have large CSS files that are used for the entire site in multiple pages, then based on the requirements, it can be split and stored with different names. It will minimize the loading time of the pages.
     
  5. Images sizes
    Overuse of images in the web site affect the web page performance. It takes time to load the images, especially on dial-up connections. Instead of using the background images, it can be done on the CSS colors or use light-weight images to be repeated in all of the pages.
     
  6. CSS based layout
    The entire web page design is controlled by the CSS using the div tags instead of table layout. It increases the page loading performance dramatically. It will help to enforce the same standard guideline throughout the website. It will reduce the future changes easily. When we use the nested table layout it takes more time for rendering.
     
  7. Avoid Round trips
    We can avoid unnecessary database hits to load the unchanged content in the database. We should use the IsPostBack method to avoid round trips to the database.
     
  8. Validate using JavaScript

    Manual validation can be done at the client browser instead of doing at the server side. JavaScript helps us to do the validation at the client side. This will reduce the additional overhead to the server.

    The plug-in software helps to disable the coding in the client browser. So, the sensitive application should do the server side validation before going into the process. 
     
  9. Clear the Garbage Collection

    Normally .Net applications use Garbage Collection to clean the unused resources from memory. But it takes time to clear the unused objects from memory.

    There are many ways to clean the unused resources. But not all of the methods are recommended. But we can use the dispose method in the finally block to clean up the resources. Moreover we need to close the connection. It will immediately free the resources and provides space in memory.
     
  10. Avoid bulk data store on client side

    Try to avoid more data on the client side. It will affect the web page loading. When we store more data on the hidden control then it will be encrypted and stored on the client side. It can be tampered with by hackers as well.
     
  11. Implement Dynamic Paging
    When we load a large number of records into the server data controls like GridView, DataList and ListView it will take time to load. So we can show only the current page data through the dynamic paging.
     
  12. Use Stored Procedure

    Try to use Stored Procedures. They will increase the performance of the web pages. Because it is stored as a complied object in the database and it uses the query execution plans. If you pass the query then it will make a network query. In the Stored Procedure a single line will be passed to the backend.
     
  13. Use XML and XSLT

    XML and XSLT will speed up the page performance. If the process is not more complex then it can be implemented in XSLT.
     
  14. Use Dataset

    A DataSet is not lightweight compared with DataReader. But it has the advantages of a disconnected architecture. A DataSet will consume a substantial amount of memory. Even though it can have more than one day. If you want to perform many operations while loading the page itself, then it might be better to go with a DataSet. Once data is loaded into the DataSet it can be used later also.
     
  15. Use String Builder in place of String

    When we append the strings like mail formatting in the server side then we can use StringBuilder. If you use string for concatenation, what it does every time is it creates the new storage location for storing that string. It occupies more spaces in memory. But if we use the StringBuilder class in C# then it consumes more memory space than String.
     
  16. Use Server.Transfer

    If you want to transfer the page within the current server then we can use the Server.Transfer method. It avoids roundtrips between the browser and server. But it won't update the browser history.
     
  17. Use Threads

    Threads are an important mechanism in programming to utilize the system resources effectively. When we want to do a background process then it can be called a background process.

    Consider the example of when clicked on send, it should send the mail to 5 lakhs members yet there is no need to wait for all the processes to complete. Just call the mail sending process as a background thread then proceed to do the further processing, because the sending of the mail is not dependent on any of the other processes.

Thursday, September 18, 2014

Custom CSS style for AJAX AutoComplete Extender



 <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"

     ...

     ...

     CompletionListCssClass="completionListCSS"

     CompletionListItemCssClass="listItemCSS"

     CompletionListHighlightedItemCssClass="itemHighlightedCSS">  

 </asp:AutoCompleteExtender>


 CSS style:

<style type="text/css">

        .completionListCSS {

        border:solid 1px Gray;

        margin:0px;

        padding:3px;

        height: 120px;

        overflow:auto;

        background-color: #FFFFFF;   

        }

        .listItemCSS {

        color: #191919;

        }

        .itemHighlightedCSS {

        background-color: #ADD6FF;     

        }

    </style>

Custom CSS style for AJAX AutoComplete Extender

Monday, July 14, 2014

Validation of viewstate MAC failed





Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.




The first option is to set the EnableViewStateMac to false in the web.config. This is an attribute of the Page tag. You also have the option to set the EnableViewStateMac to false at page level. The only drawback  with this option is that you need to do this for all page across the application.
In web.config

<pages enableViewStateMac="false">
.
.
</pages>

At page level
<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default.aspx.cs" Inherits="_Default"
 EnableViewStateMac="false" %>


Other option is to specify your own value for encryption and decryption key in the web.config . Now this key will be same across the servers.
Both the option will work perfectly, but it is always advisable to go with specifying the custom key for encryption and decryption in web.config. This is because when you set the EnableViewStateMac value to false you expose your application to security threats. This is because validation of view state will not happen in this case.

<machineKey validationKey="<encryptionkey>" decryptionKey="<decryptionkey>" validation="SHA1" decryption="Auto"/>

Machine key Generate from here -  
http://www.a2zmenu.com/utility/Machine-Key-Generator.aspx