Asp.net blogs

Tuesday 16 July 2013

How to Set Default Page in Asp.net

 Set Default Page in Asp.net :

Go to web.config file and then write the following below code inside <System.WebServer></System.WebServer>

For Example : 

<System.webserver>
<defaultdocument>
<files>
<clear/>
<add value="Hello.aspx">
</files>

</defaultdocument>
</System.webserver>

Saturday 13 July 2013

Godaddy 500 Internal Server Errors


 Godaddy 500 Internal Server Error-: When your Website code working properly in your local system and when i'll upload the same website code over the server hosting then some times it gives 500 Internal Server Error.
So you will do that as paste and replace the following your code in your web.confing that exists on your live server :

<?xml version="1.0" encoding="UTF8"?>
<configuration>
  <system.web>
    <customErrors mode="Off" />
  </system.web>
  <connectionStrings>
    <remove name="LocalSqlServer" />
    <remove name="LocalMySqlServer" />


  </connectionStrings>
</configuration>

Monday 8 July 2013

Sunday 7 July 2013

State Management

State Management : It is used to manage the state of stateless pages.

Types of State Management : There are two types of State Management are as shown below :

1. Client Side State Management.
2. Server Side State Management.

1. Client Side State Management : a) To use the Client resources means that information is stored on client hard-disk and client memory.

b) Secure : It is not secure means anyone can modify on client hard disk.

Types of Client Side State Management :

a. Cookies.
b. Query String.
c. View State.
d. Hidden State.
e Control State.

a) Cookies : Data stored in different types and this information stores and go to the next page, for this action we will used cookies.

=> To stored data in text file and that text file resides or store on client machine.
=> We can stores only string values but not object i.e Data Set not store.
=> Scope : Multiple pages means Make cookie in one page and access in any other pages.
=> By default Cookies are temporary and temporary cookies store on the browser memory.
                                    If we can off the browser then the cookie will destroy.
=> But we can also create Permanent Cookies and we can specify Expiry time for cookie. If System off then there is no effect on cookie.


b) Query String : It is also used for data storage.

=> Data concatenated with URL in query string.
=> Not stored in Text file.
=> We can store string value but didn't store objects.
=> Scope : Its scope is to the next page means one page to another page but cookie scope is more.
=> Maximum length of URL is  2086 characters.
=> Client side not secure means we can manipulate data in URL.


c) View State : Information is stored in view state in Hashed(#), Compressed, Encoded form.
                            Hash key generated for data retrieve and it is fast.

=> We can stores string value as well as objects like data set store.
=> We can store only serialisable object but we can't store Non-Serializable objects.
=> Scope :  To manage the state of current page.

For example : Information stored and goes to server and information retrieve when page comes from server.
 If we go to the next page and then come back to the previous page then Information is lost.

=> We can specify Encryption Mode for a View State like Always, Never , On Request.
=> We can specify  maximum page size for a view state. By default -1 means unlimited, but we can also apply limitation over there.

Drawbacks :

=> In large volume of data, Pagr slow and information or performance also slow down.


d) Hidden : Data display in URL but with the help of hidden we can hide the data.

=> We can also store string values but not objects.

=> Scope of hidden value is to the next page.

=> It is not display in URL.

e) Control State : Control State is used to manage the state of Custom Controls we used Control State.


2.  Server Side State Management : Server Side State Management is used to used the Server Resources.

=> No login on Server if they donot know the Username and password.
=> It is Secure.
=> It is slower as compared to Client side because Information comes from Server to Client then it takes time.

Types of Server Side State Management :

a) Application.
b) Sessions.
c) Profile.
d) Cache.

a) Application : It is a Global variable when run on server ( Ms Server, Framework, IIS).

When firstly user opens the site the Application_Start() Event fired and then Run and if other user opens, then Http Application class creates their instances and if all users log-out including last one and then App_End() event fired and then all instances closed or removed.

Application Variable : In the application variable we can store String value as well as objects.

=>Scope : Throughout the application means we used in whole project.

=> Hit Counter : Number of Viewer visit in our personal website with the help of an application variable.

b) Session: Session generates Unique ID for all users provides like 50 people opens and generates 50 unique Ids. It creates two session copies i.e One is stored on Server Memory and other is stored on Client Memory.
And it is stored in special type cookie i.e Session Cookie.

=> Size of Session Id is 128 bit.

In ASP.Net we can create cookieless application means if session cookie is disabled and then it pass from querystring.

=> Session Variable : In session variable we can store String value as well as Objects.

=> Scope: Throughout the session.

=> Session Expired Forcefully by using Session.Abondoned() Method in c#.

=> Expiry Time : Session Expiry Time is by default 20 minutes but we can Increase or Decrease Session Expiry time.

Types of sessions:

a) In-Process.
b) Out-Process.

a) In-Process: To store session on same process where the application is running.

Drawback :

=> If you reset the webserver i.e  IIS then Session destroy. We have single Mode in IN-PROCESS i.e INPROC and it is by default.

b) OUT-PROCESS : To store session on different  process means application is on one server and session is on other server.

Different process may be on different server. Different process may be Sql Server Database. If application close then Session not close for example, ATM Transaction Rectify.

Two types of modes :

a) State Server.
b) Sql Server.

a) State Server : To store session on different server. First you must start the ASP.NET STATE SERVICES to implement the STATE SERVER TECHNIQUE.

Drawback: If you Reset the ASP.NET State Services then session will be destroy.

b) Sql Server : We can store Session in Sql Server Database.

Two types of Database :

(A) Temporary Database.
(B) ASP State.

(A) Temporary Database: We can store Session Temporary and it is inbuilt Sql Server.

Drawback : If we Reset the Sql Server Service then Data loss from temporary database.

(B) ASP State: Session stores permanently in ASP State. If either application close or session close then there is no effect.

** SESSION_END() EVENT NOT FIRE IN OUT-PROCESS means SESSION EXPIRE BUT EVENT DIDNOT FIRE.

Saturday 6 July 2013

Sql Data Reader

Sql Data Reader :

1. It is used to display data.
2. Read only but not manipulate.
3. It is a FORWARD only means go to only one direction i.e going to to the NEXT STEP means ONE by ONE go to 5th record and not directly jump from 1 t0 5th record and not vice-versa.
4. It is pne and only fastest way to retrieve data from database is called Data Reader.

Introduction to DotNet

DotNet : .Net was introduced by Microsoft. Ms.net is a software component that runs on the windows operating system.
It provides tools and libraries that enable developers to create windows software much faster and easier. The .net must be installed on a Users System to run .Net applications.

.Net Framework : It is a collection of all tools and utilities required to execute the .net applications on a particular platform like Web and Mobile Development.

The Microsoft.Net includes the standard compilers i.e c#, Vb.net,J# etc., runtime environment,Garbage Collector, Security Manager, Thread Manager, Assembly Loader, Just In Time Compilers and the standard framework or Base Class Libraries.

The .Net is made up of two parts as shown below :

1. Common Language Runtime.
2. Base Class Libraries.

1. Common Language Runtime: It is the execution engine for .Net applications and serves as the interface between .Net applications and the operating System.

or

It is an environment which manages the execution of coding.

Forexample : Memory Management, Garbage Collection,To support multiple Language.

The CLR provides many services such as :

a. Loads and Executes Code.
b. Convert Intermediate Language to Native Machine Language.
c. Separate Processes and Memory.
4. Handle Exceptions.

Code that is compiled and targeted to the CLR is known as Managed Code.

Managed Code provides metadata that is needed for the CLR to provide the services of multilanguage support, code security, object lifetime management and memory management.

2. Base Class Library -: It is a standard library available to all languages using .Net framework.Dotnet  includes the BCL to encapsulate a large number of common funstions such as file reading and writing, graphic rendering, database interaction and XML document manipulation which makes the programmer job easier.

The BCL is sometimes incorrectly referred to as the Framework Class Library which is a superset including the Microsoft.* namespace.


Friday 5 July 2013

Checked All checkbox during Grid View Load while Page Load using Javascript Code

Checked All checkbox during Grid View Load while Page Load using Javascript Code with the following code :

<HeaderTemplate>
<input id="chkAll" onclick="javascript:SelectAllChkboxes(this);" runat="server" type="checkbox" />
</HeaderTemplate>
   <script type="text/javascript">

function SelectAllChkboxes(spanChks) {

var oItem = spanChks.children;
var theBox = (spanChks.type == "checkbox") ? spanChks : spanChks.children.item[0];
xState = theBox.checked;
elme = theBox.form.elements;
for (i = 0; i < elme.length; i++)
if (elme[i].type == "checkbox" && elme[i].id != theBox.id) {
if (elme[i].checked != xState)
elme[i].click();
}

}
</script>

Upload Image File according to Dimensions choice i.e. Height and Width :

Upload Image File according to Dimensions choice i.e. Height and Width : In which whenever you will upload a image then you can set it with any dimensions with the following C# code as shown below :

 protected void btnSave_Click(object sender, EventArgs e)
        {
            if (imageUpload.HasFile)
            {
                string extension = Path.GetExtension(imageUpload.PostedFile.FileName);
                Boolean flag = checkext(extension);
                if (flag == true)
                {
                    String imagepath = uploadImagess(imageUpload.PostedFile, Convert.ToInt32(356), Convert.ToInt32(1600));
                    Initialize();
                    obj.InsertBannerLinks(imagepath, "True");
                   lblmsz.Text = "Image Saved Successfully.";
                }
                else
                {

                    lblmsz.Text = "Invalid file extension.";
                }
            }
            else
            {
                lblmsz.Text = "Please Upload Image";
            }
        }


 public Boolean checkext(String ext)
        {
            String[] exts = {".bmp", ".jpg", ".jpeg", ".gif", ".tif", ".png"};
            if (exts.Contains(ext.ToLower()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 private String uploadImagess(HttpPostedFile fil, int height, int width)
        {
            string now = DateTime.Now.ToString("MM-dd-yyyy");
            string DateFormat = now.Replace('-', '_');
            string now2 = DateTime.Now.ToString("HH:mm");
            string DateFormat2 = now2.Replace(':', '_');
            String fulldate = DateFormat + DateFormat2;
         
            String Name = fulldate + fil.FileName;
            Byte[] fileBinary = GetPictureBitss(fil.InputStream, fil.ContentLength);
            MemoryStream stream = new MemoryStream(fileBinary);
            Bitmap b = new Bitmap(stream);
            Bitmap s = new Bitmap(stream);
            Size newsize = new Size();
            newsize.Height = height;
            newsize.Width = width;
            Bitmap newBitMap = new Bitmap(newsize.Width, newsize.Height);
            Graphics g = Graphics.FromImage(newBitMap);
            g.DrawImage(b, 0, 0, newsize.Width, newsize.Height);
            newBitMap.Save(Server.MapPath("~/BannerImage/") + Name, ImageFormat.Jpeg);
            newsize.Height = 56;
            newsize.Width = 56;
            newBitMap.Dispose();
            s.Dispose();
            b.Dispose();
            return Name;
        }

 private Byte[] GetPictureBitss(Stream fs, int size)
        {
            Byte[] img = new Byte[size];
            fs.Read(img, 0, size);
            return img;
        }

Set focus of textbox while loading of Page using Javascript code as shown below :

Set focus of textbox while loading of Page using Javascript code as shown below : When someone open Login Page then first focus is set to Username textbox i.e txtUserName

<script type="text/javascript">
$(function() {
setTimeout(function() {
$("[id*=txUserName]").focus();
}, 10);
});
</script>

Thursday 4 July 2013

Port Number with description

Port Number with description -: 

Port Number Description

1 TCP Port Service Multiplexer (TCPMUX)
5 Remote Job Entry (RJE)
7 ECHO
18 Message Send Protocol (MSP)
20 FTP -- Data
21 FTP -- Control
22 SSH Remote Login Protocol
23 Telnet
25 Simple Mail Transfer Protocol (SMTP)
29 MSG ICP
37 Time
42 Host Name Server (Nameserv)
43 WhoIs
49 Login Host Protocol (Login)
53 Domain Name System (DNS)
69 Trivial File Transfer Protocol (TFTP)
70 Gopher Services
79 Finger
80 HTTP
103 X.400 Standard
108 SNA Gateway Access Server
109 POP2
110 POP3
115 Simple File Transfer Protocol (SFTP)
118 SQL Services
119 Newsgroup (NNTP)
137 NetBIOS Name Service
139 NetBIOS Datagram Service
143 Interim Mail Access Protocol (IMAP)
150 NetBIOS Session Service
156 SQL Server
161 SNMP
179 Border Gateway Protocol (BGP)
190 Gateway Access Control Protocol (GACP)
194 Internet Relay Chat (IRC)
197 Directory Location Service (DLS)
389 Lightweight Directory Access Protocol (LDAP)
396 Novell Netware over IP
443 HTTPS
444 Simple Network Paging Protocol (SNPP)
445 Microsoft-DS
458 Apple QuickTime
546 DHCP Client
547 DHCP Server
563 SNEWS
569 MSN
1080 Socks

Find IP address of web site visitor

To find IP address of web site visitor -:


            string VisitorIPAddress = Request.UserHostAddress.ToString();
            string VisitorIPAddress = Request.ServerVariables["REMOTE_ADDR"];

Forgot Password Recovery via email

Forgot Password Recovery via email -:

 MailMessage mes = new MailMessage();
       
        mes.To.Add(username.text+"@gmail.com");
        mes.From = new MailAddress("admin email id");

        mes.Body = "Your Password is: " + Label2.Text;
       
        SmtpClient client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = 587;

        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        NetworkCredential credentials = new NetworkCredential("admin email id","admin email password");
        client.Credentials = credentials;
        client.EnableSsl = true;

        client.Send(mes);
        Label1.Text = "EMail Sent Successful:";

Encrypt and Decrypt Password during Login Authentication in Asp.net

Encryption Method For Password :-

static String KeyEncryption = "PU$y*P*@$";
        public static string Encrypt(string stringToEncrypt)
        {

            String sEncryptionKey = KeyEncryption;
            byte[] key = { };
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
            byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)
            try
            {
                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = System.Text.Encoding.UTF8.GetBytes(stringToEncrypt);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

        }


Decryption Method For Password :-

        public static  string Decrypt(string stringToEncrypt)
        {
            String sEncryptionKey = KeyEncryption;
            byte[] key = { };
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
            byte[] inputByteArray;//= Convert.ToByte(Convert.ToDouble((stringToEncrypt.Length));
            try
            {

                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(stringToEncrypt);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                String retval = encoding.GetString(ms.ToArray());
                return retval;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

Login form with c# in asp.net

Create two textboxes with following name and Login Button i.e

User Name : txtusername
Password :txtpassword
Login Button :btnlogin

Paste below code in your ASP page

<table style="width:100%" >
            <tr>
                <td align="center" colspan="3">
                    <asp:Label ID="lblMsg" runat="server" FontBold="True" ForeColor="#FF3300"></asp:Label>
                </td>
            </tr>
            <tr>
                <td align="left" colspan="3" style="fontweight: 700">
                   <h3> 
                       <asp:Label ID="Label1" runat="server" ForeColor="White" 
                           Text="Admin Login Panel"></asp:Label>
                    </h3><hr /></td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;<asp:Label ID="Label2" runat="server" FontBold="True" ForeColor="White" 
                        Text="User Name :"></asp:Label>
                </td>
                <td class="style1">
                    <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="requsername" runat="server" 
                        ControlToValidate="txtusername" ErrorMessage="*"></asp:RequiredFieldValidator>
                </td>
                <td class="style1">
                    </td>
            </tr>
            <tr>
                <td>
                    &nbsp;<asp:Label ID="Label3" runat="server" FontBold="True" ForeColor="White" 
                        Text="Password :"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtpassword" runat="server" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="reqpassowrd" runat="server" 
                        ControlToValidate="txtpassword" ErrorMessage="*"></asp:RequiredFieldValidator>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnlogin" runat="server" Text="Admin Login" Width="93px" 
                        onclick="btnlogin_Click" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>


On Button Click, Paste the following c# code in aspx.cs code file

 int AdminStatus =  obj.AdminAuthenticate(txtusername.Text, txtpassword.Text);
            if (AdminStatus != 1)
            {
                lblMsg.Text = "Invalid Login";
            }
            else
            {

                Response.Redirect("Admin.aspx");


            }


Create a class file with the following below code:

  public int AdminAuthenticate(string username, string passowrd)
        {
            
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
                SqlCommand cmd = new SqlCommand("sp_AdminAuthenticate", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", passowrd);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                int retValue = Convert.ToInt32(cmd.ExecuteScalar());
                return retValue;

           
        }

Also create a stored procedure


CreatePROCEDURE [dbo].[sp_AdminAuthenticate] 
(
@username nvarchar(20),
@password nvarchar(20)
)
AS
BEGIN
IF EXISTS (select * from tbllogin where username=@username AND password = @password AND status=1 )
BEGIN
select 1 as retValue

END
ELSE
BEGIN
select 1 as retValue
END
END

Show Tweets of Twitter in Twitter Widget in your Website

Firstly create a Twitter Account and then after successful login , go to the following Url i.e https://twitter.com/settings/widgets

And then create a New Widget by click on Create New button as shown below :


After click on Create new the following window will appear :


Then click on Create widget and then Copy the code as shown in below box then paste it your website in aspx page as shown below :





Delete All Stored Procedure's and Tables from Database at a time instead of one by one in Sql Server

Query to delete all Stored Procedure at a time from database in Sql Server Query Execution Window :

declare @procName sysname
declare someCursor cursor for
select name from sysobjects where type = 'P' and objectproperty(id, 'IsMSShipped') = 0
open someCursor
fetch next from someCursor into @procName
while @@FETCH_STATUS = 0
begin
exec('drop proc ' + @procName)
fetch next from someCursor into @procName
end
close someCursor
deallocate someCursor
go

Query to delete all Tables at a time from database in Sql Server Query Execution Window :

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'





Wednesday 3 July 2013

Upload Video on Youtube using Asp.Net (c#) and play the url within your website.




First you need to download the following dlls from Internet via Google Search Engine :

1. Google.GData.Client.DLL
2. Google.GData.Extensions.dll
3. Google.GData.YouTube.dll
4. Newtonsoft.Json.dll


 Following c# code is usable to upload video on You Tube and play it in on your website :

C# Code :

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Google.YouTube;
using Google.GData.YouTube;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;
using System.IO;
using Google.GData.Extensions.Location;
using System.Threading;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    string developerKey = "AI39si7ETkiMUFrMQtfkuYcOoaxs1H8QMso8R0YTzApg-alwA9XebuWKUCm4e_tbUHWvU9Of5Iwr6gXPQOwFwTa5D7gn3oecRg";
    string username = "abc@gmail.com"; // Gmail username
    string password = "123456"; // Gmail Password
    public string youtubeurl;
    
protected void Button3_Click(object sender, EventArgs e)
    {
        string FileName = FileUpload1.FileName;
        string fillPath = FileUpload1.PostedFile.FileName;
        var newp = Server.MapPath("download/" + FileName);
        FileUpload1.SaveAs(Server.MapPath("download/" + FileName));
        YouTubeRequestSettings settings = new YouTubeRequestSettings("applicationName", developerKey, username, password);

        settings.Timeout = int.MaxValue;
        YouTubeRequest request = new YouTubeRequest(settings);
        Video newVideo = new Video();
        newVideo.Title = "Test";
        newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema));
        newVideo.Description = "Testing Testing Testing";
        newVideo.YouTubeEntry.Private = false;
        newVideo.YouTubeEntry.MediaSource = new MediaFileSource(newp, "video/mpeg");
        Video A = request.Upload(newVideo);
        youtubeurl = "http://www.youtube.com/v/" + A.VideoId + "&hl=en_US&fs=1&rel=0";
        System.IO.File.Delete(Request.PhysicalApplicationPath + "download/" + FileName);


    }
}

Output Shown as below :