Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, January 04, 2015

Solved: Facebook App throws error: HTTP verb used to access this page is not allowed

Problem:
"HTTP verb used to access this page is not allowed"

Solution:
If you are getting the above error message on your Facebook App page, probably you are trying to access a static html page on your server. Rename the html page to server side extension (aspx / php).

How to force redirect all HTTP requests to HTTPS in IIS through Web.Config setting?

Web.config configuration setting to force redirect all http requests to https with all query string parameters in IIS 7.5 / 8.0 on Windows Servers.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Notes:

  1. The above solution will work well with all hosts including shared hosting servers
  2. Ensure your https URL is functioning properly

Tuesday, May 14, 2013

Insert a Line of Text or Record to the Beginning of a Text File Using Windows Batch Script


I would like to share a Windows batch script that would add a line of text / record to the beginning of a text file.

Text File: example.txt
Text to be inserted: Hello World!

Script:
COPY example.txt temp.txt
ECHO Hello World!>example.txt
TYPE temp.txt >>example.txt
DEL temp.txt

Explanation:
1) Copy the example.txt content to a temporay file
COPY example.txt temp.txt

2) Overwrite the example.txt content with new text we need to add to the beginning
ECHO Hello World!>example.txt


3) Append  the content of temp.txt to example.txt
TYPE temp.txt >>example.txt

4) Delete the temp.txt file
DEL temp.txt

It worked well! Share your comments for queries, improvements and suggestions.

Wednesday, January 16, 2013

JavaScript: console.log() - Best Practice

JavaScript developers, must be well aware of the console.log() function to log messages to the console window.

Today, I share my experience to write a wrapper function for console.log().

Simple Code 1: Ignore log message if the console object is missing


<script type="text/javascript" language="javascript">
    window.console = window.console || { log: function (d) {} };
    
    /* write your JavaScript code below this line */
    console.log("Message: Testing Console.log");

</script>


Simple Code 2: Modified to show log message as alert if the console object is missing and the global variable for debug is set to true. You can turn it off when you publish to production.


<script type="text/javascript" language="javascript">

    var debug = true;

    window.console = window.console || { log: function (d) 
        {if(debug){alert("Sorry! Logger not available on this 
            browser. \n\n" + d);} } };


    /* write your JavaScript code below this line */
    console.log("Message: Testing Console.log");

</script>


Simple Code 3: Same as above but with JQuery.


<script type="text/javascript" language="javascript">

    var debug = true;

    $(function(){
      window.console = window.console || { log: function (d) 
        {if(debug){alert("Sorry! Logger not available on this 
            browser. \n\n" + d);} } };
    });


    /* write your JavaScript code below this line */
    console.log("Message: Testing Console.log");

</script>



More Info:

This is a best practice to avoid errors with browsers that don't handle console.log missing object by default. For example, Internet Explorer don't handle the missing object and ignores all scripts following the error. Unfortunately, IE will not throw any error on this condition and eat your time debugging and tracing for the invisible error.

Note 1: console object is not a standard object in ECMA Script. However, it is one of the most widely used objects by developers for debugging JavaScript programs.

Note 2: In Internet Explorer 8 and Internet Explorer 9, console object is exposed only when Developer Tools (Shortcut - F12) are opened for the active tab.

Happy Coding!




Saturday, March 17, 2012

Database Programming with ASP.NET C# & MySql

Today I find some time to discuss Database Programming with ASP.NET C# & MySql

A BRIEF INTRODUCTION ON ASP.NET C#, MYSQL AND WINDOWS STACK

Software Requirements
  1. MySQL DB with Work Bench
    DOWNLOAD LINK: http://www.mysql.com/downloads/
  2. MySql Connector for .NET
    DOWNLOAD LINK: http://www.mysql.com/downloads/connector/net/
    Download the binary and install to your machine where you need to run your application.
  3. .NET Platform / Visual Studio
    DOWNLOAD LINK: http://msdn.microsoft.com/hi-in/netframework/default.aspx
    You may download and install the .NET framework of your required version 1.1/2/3.5 or 4.
    This article supports all the above mentioned versions.
MySql Database Creation and Table Creation
I assume that you can create MySql Database and Tables I proceed to the C# Programming part

Web.config File
The following is a simple connection string statement I use in my development practice. You may also ignore Web.config and write the connection string inline on the code page. But it is not recommended as it is vulnerable to disclose your database credentials (Database Username and Password) in the code page. Say you may have more than one developers working on the project and you many not want to share the database credentials with them, this practice will help you the most. Apart from this the content in the web.config file is more secured than content in other pages by the ASP.NET architecture.

Syntax:

<add  name="<give some name to call this connection string>"
              connectionstring="server=<server ip address or name>
              initial catalog=<database name>
              uid=<database username="">;
              pwd=<database password>"
              providerName="MySql.Data.MySqlClient"/>

Example:

<add  name="MyConnection1"
              connectionstring="server=localhost;
              initial catalog=mysampledb; 
              uid=root;
              pwd=mypassword" 
              providerName="MySql.Data.MySqlClient"/>

ASP.NET C#
Here I use ASP.NET and C# to explain the database programming with MySql. I assume that you have basic knowledge of ASP.NET and C# programming.

Go to the code behind and proceed with the following code.

  1. Incluse the usings.

    using MySql.Data.MySqlClient;

  2. Declare the private variables inside the main class (pls not the class not the main function)

    //CREATING CONNECTION INSTANCE / NOTE: CONNECTION WILL NOT OPEN HERE
    MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings[
                          "myconnstr"].ConnectionString);

    //CREATING INSTANCE OF COMMAND AND DATA READER / REQUIRED FOR ACCESSING DATA MANUALLY

    MySqlCommand cmd;
    MySqlDataReader dr;
    //CREATING INSTANCE OF DATA SET / REQUIRED FOR BINDING DATA WITH DATAGRID/DATALIST
    DataSet ds = new DataSet();
  3. Opening Database Connection

    if (con.State == ConnectionState.Closed)
    {
      con.Open();
    }
  4. Adding Data to the Database

    string qry = "INSERT INTO sample_table(first_name, last_name)";
    cmd = new MySqlCommand(qry, con);
                cmd.ExecuteNonQuery();

Introduction to C# / ASP.NET with C#

ASP.NET is a Microsoft technology for web applications. ASP stands for Active Server Pages. As the name specifies the pages are programs that are stored and executed on the server. When a call is made to the page the page gets compiled (if not already compiled) and returned to the client browser as a file in HTML and JavaScript combination. The .NET platform is a proven Microsoft technology for applications. ASP.NET is limited to Windows platform. We will discuss more about the ASP.NET and C# in a separate article soon.

Introduction to MySql Database
MySql is an opensource database backed by Oracle Corporation. It is a powerful and efficient database that you can rely on it for your enterprise needs. Most companies prefer MySql for their data storage needs and high transaction processing. MySql is reliable and programmer friendly too. It has a large user base and strong community to support. However, the PHP & MySql combination is the best pair on internet! It is not that C# doesn't go well with MySql but the opensource PHP beat the C# or any other language on Internet. Let us not worry about that! We have enough articles and resources for C# integration and programming with MySql and abundant help content for MySql. We will discuss more about the MySql in a separate article soon.

Wednesday, March 14, 2012

Difference between Struct and Class in c# (Struct Vs Class)

There is a FAQ I get from people: What is the difference between Struct and Class as we can design an object using both?

Class is a Reference type and struct is a Value type. This means Class instance refers the address of another instance assigned to it but a Struct instance copies the values of assigned object.

In other words if we create 2 class instances A and B, and assign B to A then any changes made to B will reflect in A also. But in Struct, A will hold a copy of values of B and any changes to B will be independent.

Example (ASP.NET/C#):

public class Class1
    {
        public string TestValue { get; set; }
        public Class1() { }
    }

protected void Page_Load(object sender, EventArgs e)
    {
        Class1 A = new Class1(); //Create an instance of a class Class1

        A.TestValue = "1";

        Response.Write("A.TestValue: " + A.TestValue);
        Response.Write("<br />");

        //Assign B to A

        Class1 B = A; //Create another instance of the same class Class1

        B.TestValue = "2";

        Response.Write("B.TestValue: " + B.TestValue);
        Response.Write("<br />");
        Response.Write("A.TestValue: " + A.TestValue);
    }

Thursday, October 20, 2011

How to fetch nth row from SQL Server 2008 R2 / 2005


Example Code:

Note: Code explained below

WITH temp_table AS
(
    SELECT TOP (SELECT COUNT(*) FROM [table_1])
        firstname, lastname, mobile, email,
        ROW_NUMBER() OVER (ORDER BY zip_code) AS row_no
    FROM
        [table_1]
    ORDER BY zip_code
)
SELECT
    first_name,
    last_name,
    email

FROM
    temp_table
WHERE
    row_no BETWEEN 1 AND 10


Code Explanation:

WITH temp_table AS
--create a temporary table named temp_table
(
    SELECT TOP (SELECT COUNT(*) FROM [table_1])
    --table_1 is the original table
    --top is an essential keyword when you use orderby keyword in this sub query else you can ignore TOP keyword
    -- I have fetched the rows count to fetch the entire rows, this means no difference when considered as a independent query but just to obey the inner query Syntax, that is TOP keyword should be used while using order by in the sub query
        firstname, lastname, mobile, email,
        --just fetching some fields
        ROW_NUMBER() OVER (ORDER BY zip_code) AS row_no
        --generate row number with a custom field in the temp_table for the rows fetched from the original table
    FROM
        [table_1]
        --original table
    ORDER BY zip_code
    --order by inside sub query is the complex part. I remind, use TOP keyword when using order by keyword.
)
SELECT
    first_name,
    last_name,
    email
    --simple select query from the temp_table
FROM
    temp_table
WHERE
    row_no BETWEEN 1 AND 10
    --now we can set between values to fetch records. Hope this is self explanatory, you can set 11 and 20 to fetch the next set of 10 records and so on.


Please share your comments and suggestions. You may also post your questions and doubts here.

Wednesday, October 19, 2011

How to fetch first 10 rows in SQL Server 2008 R2 / 2005

It is pretty simple to fetch first n records in SQL Server 2008 R2. Following is the syntax and example SQL Query to fetch the first 10 rows from a SQL Server 2008 R2 / 2005 database.

Syntax:

SELECT TOP (n) * FROM

--n could be any unsigned bigint value
-- You may also use TOP n without parenthesis. Using TOP keyword without parenthesis gives backward compatibility with SQL Server 2000 but I guess most don't require such a backward compatibility. So it is recommended by Microsoft to use TOP with parenthesis.


For advanced users: 

n is actually an expression. That is, it is capable of performing calculations to derive the final number of records to be retrieved.

Optionally you may also use PERCENT keyword next to the n to denote the input for fetching number of records is on percentage. That is, the following Example 2 will fetch 10 records from a table containing 100 records. When n is used as percentage, n will be treated as float.

Example 1:

SELECT TOP (10) * FROM  employees



Example 2:

SELECT TOP (10) PERCENT * FROM employees


It is as simple as above. I am publishing this on my blog because this is the most frequent database related question most people asked me.

Wednesday, April 06, 2011

C#: Difference between int and int32


I’ll take this opportunity to explain int16, int32 and int64 as well.

int” is a data type keyword defined by the language, C#.

Int32 is a data type defined by the .NET Common Type System (CTS). I mentioned it as data type just for the understanding but it is actually a Struct. 

When you declare a variable as int or Int32 it will point to System.Int32 only. int is the same as System.Int32 and when compiled it will turn into the same thing in IL. If you disassemble your code with ILDASM, you'll see that the underlying types are used. So there is no difference in it technically. However, for readability factor including myself, most developers suggest to use int to declare a variable and all MSDN sample code uses int.

System.Int32 is a signed integer. So the minimum and maximum capacity of int or Int32 would be -2147483648 and 2147483647 respectively.

How I calculated this?
Simple for Int32, -2^32/2+1 to 2^32/2. Similarly for Int64, -2^64/2+1 to 2^64/2.

Int16 & Int64
System.Int16 is defined as short in C#. It can store a minimum & maximum of -32,769 & 32,768
System.Int64 is defined as long in C#. It can store a minimum & maximum of -9,223,372,036,854,775,808 & 9,223,372,036,854,775,807 respectively.

Unsigned
You may use unsigned short, integer or long if you are sure that you will not store any negative values to the variable. By going for unsigned variables you can double the capacity of the data type. For uint the max value is, 2^32, for ulong it is 2^64.Following are the keywords and examples for using unsigned data types.

int a = 2147483647; // CORRECT
int a = 2147483648; // INCORRECT. THIS WILL THROW ERROR.
uint a = 2147483648; // CORRECT, BECAUSE WE ADDED u TO SPECIFY THIS AS UNSIGNED

Similarly you may use the same technique for short as ushort and long as ulong.

Friday, June 25, 2010

Open a new browser window using javascript window.open() method

This article is to explain opening a new browser window using JavaScript. The window.open() function of JavaScript has been explained in detail with example code. For further help don't hesitate to contact me or our friends on the network. Just post your queries on the comment section.


Syntax:
winRef = window.open( URL, name [ , features [, replace ] ] )
Example:
mySearchWin = window.open('http://www.google.com','mysearchwindow',
'left=30,top=30,width=600,height=400,toolbar=0,resizable=0')
Returns:
Reference to the newly opened window.

The return value, stored in the variable winRef, is the reference to your new window. You can use this reference later, for example, to close this window (winRef.close()), give focus to the window (winRef.focus()) or perform other window manipulations.

The parameters URL, name, features, replace have the following meaning:

URL String specifying the location of the Web page to be displayed in the new window. If you do not want to specify the location, pass an empty string as the URL (this may be the case when you are going to write some script-generated content to your new window).
name String specifying the name of the new window. This name can be used in the same constructions as the frame name provided in the frame tag within a frameset name ...>. For example, you can use hyperlinks of the form name href="page.htm">, and the hyperlink destination page will be displayed in your new window. If a window with this name already exists, then window.open() will display the new content in that existing window, rather than creating a new one.
features An optional string parameter specifying the features of the new window. The features string may contain one or more feature=value pairs separated by commas.
replace An optional boolean parameter. If true, the new location will replace the current page in the browser's navigation history. Note that some browsers will simply ignore this parameter.
The following features are available in most browsers:
toolbar=0|1 Specifies whether to display the toolbar in the new window.
location=0|1 Specifies whether to display the address line in the new window.
directories=0|1 Specifies whether to display the Netscape directory buttons.
status=0|1 Specifies whether to display the browser status bar.
menubar=0|1 Specifies whether to display the browser menu bar.
scrollbars=0|1 Specifies whether the new window should have scrollbars.
resizable=0|1 Specifies whether the new window is resizable.
width=pixels Specifies the width of the new window.
height=pixels Specifies the height of the new window.
top=pixels Specifies the Y coordinate of the top left corner of the new window. (Not supported in version 3 browsers.)
left=pixels Specifies the X coordinate of the top left corner of the new window. (Not supported in version 3 browsers.)