Wednesday, April 26, 2017

social profiles with schema.org markup on google


Google uses schema.org structured data to highlight the social profiles of a website(organization) or a person on their knowledge Panel. it is a good way as per SEO experts to show an organization company profile in google search knowledge base by using schema.org.
Whenever you will perform a search on Google to check any brand, you will be given that brand's information on Google right side of search. This google knowledge base box will give you an overlook about company CEO name, logo, stock exchange, contact information and social profile, which is now a days very important for any brand to compete in the market.
We can also add for our organization these information by using schema.org structured data to increase our SEO rank and our website traffic.
Now google is supporting a limited range of social media like, Facebook, Twitter, Google+, Instagram, YouTube, LinkedIn, Myspace, Pinterest, SoundCloud and Tumblr. we can use other social profiles also but google does not included that in search results. We can use two way one is JSON-LD and other is microdata.
Here is the example of JSON-LD:
<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Person",
  "name": "your name",
  "url": "http://www.your-site.com",
  "sameAs": [
    "http://www.facebook.com/your-profile",
    "http://instagram.com/yourProfile",
    "http://www.linkedin.com/in/yourprofile",
    "http://plus.google.com/your_profile"
  ]
}
</script>

If you want to set for your organization just need to change type to "Organization". you need to add this json-ld part in the head section of your website.
Here is the example for microdata:

<span itemscope itemtype="http://schema.org/Organization">
  <link itemprop="url" href="https://your-company.com">
  <a itemprop="sameAs" href="https://www.facebook.com/your-company">FB</a>
  <a itemprop="sameAs" href="https://www.twitter.com/YourCompany">Twitter</a></span>

you can change Organization to person as per your requirements. once you are finished with coding and you updated on your website then check with view source code its showing their perfectly and then you can check your markup with google structured data from here:
https://search.google.com/structured-data/testing-tool
you can enter directly your page url or paste that specific part of code in testing tool it will show you its working fine or not, if there is any error it will show there also.

Wednesday, April 19, 2017

Constraints in SQL Database

Today we will learn what are constraints in SQL. in our daily routine work we are using many constraints but in actual we don't know what are constrains. basically constraints are rules, such rules which are enforced on data column of a table. we can apply a constraint on a table or a column. these are used to check the accuracy of data and reliability of data in any circumstances.
So, let's have a look on constraints one by one which are mostly used in SQL.
NOT NULL Constraint − will make sure this column cannot be NULL.
For example we have a PRODUCTS table and we want to add NOT NULL constraint on PRICE Column:
ALTER TABLE PRODUCTS 
       MODIFY PRICE DECIMAL (18, 2) NOT NULL;


DEFAULT Constraint − it will set Default value for a column if none is given.
how to add Default Constraints:
ALTER TABLE PRODUCTS 
        MODIFY PRICE DECIMAL (18, 2) DEFAULT 10.00; 

To DROP a default Constraint we will use this query other than normal DROP constraint query:
ALTER TABLE PRODUCTS 
   ALTER COLUMN PRICE DROP DEFAULT;


UNIQUE Constraint − this will check Column Values are unique.
How to Add Unique Constraint:
ALTER TABLE PRODUCTS 
   MODIFY QTY INT NOT NULL UNIQUE;


PRIMARY Key − it will set unique identity for each row/record.
How to add:
ALTER TABLE PRODUCTS 
   ADD CONSTRAINT PK_PRODTID PRIMARY KEY (PROD_ID, PRODUCT_NAME);


FOREIGN Key − it will also Uniquely identifies a row/record for any given database table.
How to add:
ALTER TABLE ORDERS 
   ADD FOREIGN KEY ((PRODUCT_ID) REFERENCES PRODUCTS (PROD_ID);


CHECK Constraint − it used to check that all values of column are according to a specific condition.
How to Add:
ALTER TABLE PRODUCTS
   MODIFY QTY INT NOT NULL CHECK (QTY >= 2);


INDEX − Basically Indexes are used to retreive data from a table quickly.
How to Create Index:
CREATE INDEX idx_price
   ON PRODUCTS (PRICE);


Constraints can also be added while creating a table with CREATE TABLE Statement otherwise you can set later with ALTER TABLE statement.

Dropping Constraints:
We can also remove a constraint by using below query:
For example, to drop the primary key constraint in the PRODUCTS table, you can use the following command.
ALTER TABLE PRODUCTS DROP CONSTRAINT PK_PRODTID;

Comments and Suggestions are always Welcome!

Tuesday, April 18, 2017

Tracing in asp .net Application for Beginners

Today we will learn how to use Tracing in Asp.Net to check the performance of Web Application.
In Web Development the most concerned part is Performance. so how we can check which part of our application is slower either its Asp.Net code or our Database queries. you can check your SQL queries performance by using SQL Profiler, look the execution plan which part of query is taking more time than normal and then you can easily find alternative or some good way to resolve query slowness.
But if query is performing fast in database then it means there is something in our application which is making causing slowness. In production environment its not easy to check which line of code is making problem so by using Tracing we can easily check where is the problem actually. We can turn on Tracing by setting page directive Trace="true". once its set on page then we can check at the end of page or in trace.axd file. from trace log in the file we can easily check which piece of code is making problem.
Let's have look on code:
First in page directive you need to set:
<%@ Page Language="C#" AutoEventWireup="true" Trace="true" CodeFile="WebPage.aspx.cs" Inherits="WebPage" %>
Now we will create three Gridviews to check each gridview data load performance on Page load.
<div>
            <b>All Orders</b>
            <asp:GridView ID="GridView1" autogeneratecolumns="True" runat="server"></asp:GridView>    
            <br />
            <b>Delivered Order</b>
            <asp:GridView ID="GridView2" autogeneratecolumns="True" runat="server"></asp:GridView>    
            <br />
            <b>Cancelled Order</b>
            <asp:GridView ID="GridView3" autogeneratecolumns="True" runat="server"></asp:GridView>    
        </div>


And In code behind we will call our Stored Procedure on Page load, here i am not going to write full code for calling stored procedures, we will just understand how Tracing will work:
protected void Page_Load(object sender, EventArgs e)
    {
        Trace.Warn("GetAllOrders() Stored procedure started");
        GetAllOrder();
        Trace.Warn("GetAllOrders() Stored procedure End");

        Trace.Warn("GetDeliveredOrder() Stored procedure started");
        GetDeliveredOrder();
        Trace.Warn("GetDeliveredOrder() Stored procedure End");

        Trace.Warn("GetCancelledOrder() Stored procedure started");
        GetCancelledOrder();
        Trace.Warn("GetCancelledOrder() Stored procedure End");

    }


Above we discussed it was page level Tracing, We can also set Tracing on application level by using below web.config code. it save trace data for up to 40 requests.
<configuration>
  <system.web>
    <trace enabled="true" requestLimit="40" localOnly="false" />
  </system.web>
</configuration>


Comments and Suggestions are always Welcome!

Sunday, April 16, 2017

Insert Data from one Database Table to another Database Table on Different Server

Today we are going to learn how to insert data from one database server table to another database server table.
So let’s start writing the query.

Insert into [Server/Machine Name].[Database Name].[Schema].[Table Name]
Select * from [Server/Machine Name]. [Database Name].[Schema].[Table Name]

If you want to pick specific columns then you will write this query like this

Insert into [Server/Machine Name]. [Database Name].[Schema].[Table Name](Column1,Column2)
Select Column1, Column2 from [Server/Machine Name]. [Database Name].[Schema].[Table Name]

Comments and Suggestions are Always Welcome!

Insert Data From one Database Table to another Database Table on Same Server

Today we are going to learn how to insert data from one database table to another database table. I am going to write a separate post in coming days to insert records from different database servers.
So without wasting time let’s have a look at the query to insert records from one DB table to another DB table on a same server.

Insert into [Database Name].[Schema].[Table Name]
Select * from [Database Name].[Schema].[Table Name]

If you want to pick specific columns then you will write this query like this

Insert into [Database Name].[Schema].[Table Name](Column1,Column2)
Select Column1, Column2 from [Database Name].[Schema].[Table Name]

For example you are moving customer table’s data from Northwind database to AdventureWorks database on the same server/machine/computer then your query will be

Insert into [AdventureWorks].[dbo].[Customer]
Select * from [Northwind].[dbo].[Customer]

Comments and Suggestions are Always Welcome!

Format currency without jQuery plugin

In this tutorial you will learn how to format currency without using any jQuery plugin.
Let’s have a look how to accomplish this

Javascript Function:-
function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

Call of the function will be like this:
formatCurrency(8000000000);
formatCurrency(0.700);
formatCurrency(100);

Output will be
$8,000,000,000.00
$0.70
$100.00

Tuesday, April 11, 2017

Retrieving Selected Item Text, Value and Index of Dropdown

Today we will check in Asp.Net, how to get a value from dropdown, its item text and index also. so i think without discussing more on theory let's go to code and create a dropdown with some sample data.

<asp:DropDownList ID="ddlSampleData" runat="server">
    <asp:ListItem Text="Select Name" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Pakistan" Value="1"></asp:ListItem>
    <asp:ListItem Text="England" Value="2"></asp:ListItem>
    <asp:ListItem Text="Ireland" Value="3"></asp:ListItem>
</asp:DropDownList>

<asp:Button ID="btnGetValddl" runat="server" Text="Button" onclick="btnGetValddl_Click" /> 

You can create a dropdown by using Asp.net toolbox, just drag and drop the dropdown control after that add some listitem to dropdown from proprty or by code. We created a asp button also to perform the operations.
On this button click event we will get the value, text and index of selected item with a very simple way and then we will write this to our page by using HttpResponse's Write method. here is the code for that button click event.
protected void btnGetValddl_Click(object sender, EventArgs e)
    {
        if (ddlSampleData.SelectedValue != "-1")
        {
            Response.Write("Selected Item's Text = " + ddlSampleData.SelectedItem.Text + "<br/>");
            Response.Write("Selected Item's Value = " + ddlSampleData.SelectedItem.Value + "<br/>");
            Response.Write("Selected Item's Index = " + ddlSampleData.SelectedIndex.ToString());
        }
        else
        {
            Response.Write("Select Countrt First!");
        }
    }


As on the first item of dropdown we set the value as -1, this value will tell us either a country is selected from the dropdown or not and if no country is selected then we will show message "select country first".
To get the select item Text we used:
ddlSampleData.SelectedItem.Text

To get the Select Item's Value we can:
ddlSampleData.SelectedItem.Value

or
ddlSampleData.SelectedValue
To get the index of Select Item's, we can do:
ddlSampleData.SelectedIndex

we can perform many other operation like if we want to set a value by default it should be select like if we want in our dropdown pakistan should come selected by default then we can set on page load event like:
 ddlSampleData.SelectedValue = "1";

or we can achieve this by using selectedIndex:
 ddlSampleData.SelectedIndex = 1;

if we want to bind our dropwdown directly data from data then we can do something like below, for example we have to bind a city dropdown:
<asp:DropDownList ID="slctCity" runat="server"></asp:DropDownList>


we are going to create a function so we can call this from different pages:
public void ddlbind(DropDownList ddl, string query, string text, string val)
    {
        DataSet ds = new DataSet();
        da = new SqlDataAdapter(query, con);
        da.Fill(ds);
        ddl.DataSource = ds.Tables[0];
        ddl.DataTextField = text;
        ddl.DataValueField = val;
        ddl.DataBind();
    }

in this you need to set con with your SQL Connection and after that pass just query and dropdown id.
we will call like this:
ddlbind(slctCity, "select ct_name,ct_charges from tbl_city", "ct_name", "ct_charges"); 

Comments and Suggestions are Always Welcome!

Sunday, April 9, 2017

Import Data in SQL Server Table From Excel

How to import data in sql server table from excel spreadsheet
In this tutorial you will learn how to import data into sql server table from an excel spreadsheet using SQL Import and Export Wizard with easy steps. Let start doing it step by step.
Step 1: Pick your Excel source


Step 2: Pick your SQL Server target database


Step 3: Pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!


Step 4: Check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:


Step 5: If you want to use it later on, save your SSIS package to SQL Server:


Step 6: Success! This is on a 64-bit machine, works like a charm - just do it!!

Comments and Suggestions are always Welcome!

Saturday, April 8, 2017

Web Application Life Cycle Event ASP.NET

Events in the life cycle of a web application:
Today we will discuss the events in the life cycle of a web application. As the name shows Application events are used across the application. these events are used to initialize some data which will be available to all current user of application. As we know Session are also used to initialize the data but that data will be available for individual session not for whole application. First let's have a look on Web application events available in Global.asax file:
void Application_Start(object sender, EventArgs e)
{
    //This Code will run on application start
}
void Application_End(object sender, EventArgs e)
{
    //This Code will run on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
    //This Code will run when some unhandled error occured
}
void Session_Start(object sender, EventArgs e)
{
        //This Code will run when a new session starts
}
void Session_End(object sender, EventArgs e)
{
    //This Code will run on when a session ends
} 


1. Application_Start: This event runs when an application starts running first time if it was not running before. mostly this even is used to initialize data that needs to be available across all the application. we can set an application state variable to keep records that when an application starts and we can also count of application start event fired.
void Application_Start(object sender, EventArgs e)
{
    // Create Application state variables
    Application["AppStartDateTime"] = DateTime.Now;
}

This will available across the application if required on some pages.

2. Application_End: This event will be fired when application shutdown. we can use this event to keep records and also, we can generate some alert so we could be aware of application is running or shutdown. this event will be fired when IIS is restarted basically it is a once per application event.
void Application_End(object sender, EventArgs e) 
{
    //Code
}


3. Application_Error: This event is mostly used than above mentioned events because when ever and error occurred then this event will be fired and we can set redirect according to error status code so our used should be face some terrible error page and we present some user-friendly message to use and mention the reason why user come to this page.
void Application_Error(object sender, EventArgs e) 
    { 
        // Code runs when an unhandled error occurs
    Exception ex = Server.GetLastError();
    if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
    {
        Response.Redirect("~/404.aspx");
        //Server.Transfer("~/Error.aspx");
    }
    else
    {
        // your global error handling here!
    }
}


4. Session_Start: This event will be fired every time when a new user/browser visits the application with different session id. by using this Event we can keep record how many user visits our application and we can check how many users currently on our application.
void Session_Start(object sender, EventArgs e)
{
    //Application["TotalUser"],Application["CurrentUser"] will be initialize in application_start
    // Increment TotalUserSessions by 1
    Application["TotalUser"] = (int)Application["TotalUser"] + 1;
    Application["CurrentUser"] = (int)Application["CurrentUser"] + 1;
}


5. Session_End: This event is fired when a single user's session ends or timed out.
void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends.  
    Application["CurrentUser"] = (int)Application["CurrentUser"] - 1;   
    }
Note: Session End event is fired only when we have set session state mode to "InProc". In other state mode, it will not fire Session End event.

Comments and Suggestions are Always Welcome!

Stored Procedures Best Practices

Stored Procedures Best Practices:
Today we will check which performance parameters and other point we should keep in mind while creating a stored procedure.
There are many benefits of using Stored procedures. basically a stored procedure is a set of SQL statements which are stored in database in compiled form with a specific name and most important benefit is, we can use this stored procedure in number of programs, with this feature we are not required to write query again and again.
we can also perform many operations at database level so it will not load our application and application will perform well. we can use many programming concept like IF-ELSE, WHILE loop and other constructs also.
Here i am going to share some good approaches while creating a stored procedure which, a developer should use to enhance the performance of stored procedure. there are some standard rules and signature to create stored procedure but we can add other things as per our requirements. i will not go to details of each benefit, will give a short description. so let’s have a look:
1. SET NOCOUNT ON: we should always use SET NOCOUNT ON statement at the start of your stored procedure code to minimize the unnecessary network round trips.
2. PARAMETER SNIFFING: This is a very good concept to study, we should never use our stored procedure parameters directly in SQL statement because it will cause Parameter Sniffing. first, we should assign the parameter to local variable and then we should pass to SQL statements.
3. Use table variables: Table Variables are very good for small data instead of temp table. it will give your stored procedure a good rise in performance.
4. Use of Temp Tables: Temp tables are not always recommended but if it is required and no other option then always create indexes on temp table. it is for big data like millions of records in this case do not use table variables.
5. Avoid using CURSORS: CURSORS are used to manipulate the data row-by-row but it will make your Stored procedure very slow, always try to avoid CURSORS and check for other SET based approaches.
6. Use TRY-CATCH block: This is a very good approach to use TRY-CATCH in SQL statement so if there is any error you can handle at Database and return a proper flag to application. it will also never let your application do any operation and check data for exception handling.
7. Using Transactions: BEGIB TRANSACTION, COMMIT/ROLLBACK these are good to use when you are going to perform some action on your database but always try to use short transaction with them otherwise it will create blocking in database and deadlocks. but by using Transactions we can keep track of successful/unsuccessful of your transaction.
8. Aliasing objects: although database will allow you to use SQL reserve keyword but try to avoid use reserved keywords otherwise it will affect your statement performance and its good approach to use meaningful naming conventions.
9. Avoid GOTO Statement: Like all other programming language its bad practice to use GOTO statement. it good to use and filter you statements with IF-ELSE without using GOTO.
10. Avoid 'sp_' prefix: your Stored procedure should not start with 'sp_' because in this case compiler will go first to master database and then it will come back to current database so it will slow down your Stored procedure.
11. Use fully qualified objects name: In SQL queries, it will help the compiler to find cached and compiled object quickly.
12. Use WITH ENCRYPTION: if it is required you can use this to hide the Stored Procedure statement.
13. Add Comments: always add comments in your procedure like a good programmer.
14. Use BEGIN-END code block: Whole Stored procedure should be in BEGIN-END block.
Below is the standard template for creating stored procedure which is generated by SQL Management studio.

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName> 
    -- Add the parameters for the stored procedure here
    <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>, 
    <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
END
GO


Comments and Suggestions are Always Welcome!

Monday, April 3, 2017

Highlight Duplicate Records in GridView

How to highlight Duplicate Records in GridView.
Hi, today I will share my experience with you which I face long time ago. problem was how to identify if there is any duplicate record. so, after spending too much time on search and finding solution I reached to a solution. below is given a function which finds the duplicate rows in a Gridview without much effort, just we need to pass our Gridview ID and it will find and highlight the duplicate rows. we can find duplicate row depending upon a cell value within a row or for multiple cells also.
Here is the function:

public void HighlightDuplicate(GridView gridview)
    {
        for(int currentRow = 0; currentRow < gridview.Rows.Count - 1; currentRow++)
        {
            GridViewRow rowToCompare = gridview.Rows[currentRow];
            for (int otherRow = currentRow + 1; otherRow < gridview.Rows.Count; otherRow++)
            {
                GridViewRow row = gridview.Rows[otherRow];
                bool duplicateRow = true;
                //check Duplicate on Name Coloumn
                if ((rowToCompare.Cells[2].Text) != (row.Cells[2].Text))
                {
                    duplicateRow = false;
                }
                else if (duplicateRow)
                {
                    rowToCompare.BackColor =System.Drawing.Color.Yellow;
                    row.BackColor = System.Drawing.Color.Yellow;
                }
            }
        }
    }


we will call this function after DataBind() is done to the Gridview.
Call function
HighlightDuplicate(GridView1);

In current function i am checking value of Cell[2] you can set as per your requirements.
This function can also be used for some other operations on the Gridview because you have full control on rows and cell of Gridview even you can find a specific value or control in the Gridview row and do whatever you want.
Comments and Suggestions are Always Welcome!

Sunday, April 2, 2017

Difference in ExecuteNonQuery ExecuterReader ExecuteScalar

ExecuteNonQuery() Vs ExecuterReader() Vs ExecuteScalar()
Today we will check the difference between ExecuteNonQuery, ExecuterReader and ExecuteScalar and we will try to understand which one should be used for which type of Database operations:
1. ExecuteNonQuery():
ExecuteNonQuery is always recommended for such operation in which you are not required to return anything from the query. it's used for INSERT,UPDATE and DELETE operations or other Action Queries like Alter, Drop,Create. it's function is same either we use direct SQL Query or Stored Procedure. so becarefull and do not use with SELECT Statements because it will always return total count of affected rows by query or stored procedure. we can not do much with its return because it is only returning int and its assigned to integer variable only.
Example:
        ExecuteNonQuery("DELETE FROM MYTABLE");
    ExecuteNonQuery("UPDATE TABLE SET COLUMNAL = 'Code'");

If we use ExecuteNonQuery with a Select Statement then it will do nothing. it will execute the Query but it's row affected will be negative -1 you can throw any error also.

2. ExecuterReader():
ExecuteReader is used to Read the Data from SQL Statement and its recommended to use with SELECT Operations. ExecuteReader returns IDataReader object when fetch the records from Database and we can perform other operation on this object as per our requirements like we can bind GridView etc. we use .Read() method of SqlDataReader which read the data one by one. it will also work for Action Queries but best to use for SELECT non action queries. it will return a collection of all data on which we can perform operation row by row or column by column also.

       IDataReader dr = ExecuteReader("SELECT * FROM MYTABLE"); 
     while(dr.Read())
     {
             Response.Write("Name: " + dr["ColumnName"]);
    } 


3. ExecuteScalar():
ExecuteScalar is always used for a single column value. it will return first column of first row of Query. it is used when we are required one column or a single value like we want to get SUM of a column,Average of Column or Count and also it's usable when we want to know ID of employee from employees table against a single employee. it will be usefull for Non Action quries. it will return the an object type.

       Int32 Value = Convert.ToInt32(ExecuteScalar("SELECT SUM(SALARY) FROM EMPLOYEES")); 
 Int32 Value = Convert.ToInt32(ExecuteScalar("SELECT AVG(INCENTIVE) FROM EMPLOYEES")); 


it's always used for single value but if we used with multiple column statement then it's behavior will also remain same it will return first row first column value.
Comments and Suggestions are Always Welcome!