Showing posts with label ASP.net Examples. Show all posts
Showing posts with label ASP.net Examples. Show all posts

Wednesday, 12 October 2016

Serialize dataset to xml in webservice .net

Create a class for extension:

public static class Extensions
    {
        public static string ToXml(this DataSet ds)
        {
            using (var mStream = new MemoryStream())
            {
                using (TextWriter sWriter = new StreamWriter(mStream))
                {
                    var xmlSerializer = new XmlSerializer(typeof(DataSet));
                    xmlSerializer.Serialize(sWriter, ds);
                    return Encoding.UTF8.GetString(mStream.ToArray());
                }
            }
        }
    }

Tuesday, 28 June 2016

Fill dataset using stored procedure in .Net

 // Within the code body set your variable  
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            DataSet ds = new DataSet();
            try
            {
                string query = "exec GetData  '" + FromDate + "','" + ToDate + "'";
                using (SqlConnection connection = new SqlConnection(connectionString))
                using (SqlCommand command = new SqlCommand(query, connection))
                using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                {
                    adapter.Fill(ds);
                }
                return ds;
             
            }
            catch
            {
                return ds;
            }

Thursday, 16 July 2015

Code to send email from Gmail in .net

        private void SendEmail(string emailBody)
        {
            try
            {
                MailMessage message = new MailMessage();

                //SmtpClient smtp = new SmtpClient();

                message.From = new MailAddress(ConfigurationManager.AppSettings["FROMEMAIL"].ToString());

                message.To.Add(new MailAddress(emailTo));

                message.CC.Add(new MailAddress(emailCC));

                message.Subject = emailSubject;

                message.Body = emailBody.ToString();

                message.IsBodyHtml = true;

                var client = new SmtpClient("smtp.gmail.com", 587)
                {
                    Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"].ToString(), ConfigurationManager.AppSettings["FROMPWD"].ToString()),
                    EnableSsl = true
                };
                client.Send(message);
            }
            catch (Exception ex)
            {
                objLogWriter.LogWrite(ex.Message);
            }
        }

Execute Stored Procedure with parameters and Fill Dataset

Introcution: Here you can call and execute stored procedure from code behind and pass the parameters and fill dataset.

Implementation:
DataSet ds = new DataSet();

            DataTable dt;

            sb.Append("<table>");

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {

                    using (SqlCommand command = new SqlCommand("sp_DistwiseDetails1", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;

                        command.Parameters.Add("@RetriveType", SqlDbType.VarChar).Value = 2;

                        command.Parameters.Add("@FromDate", SqlDbType.VarChar).Value = DateTime.Now.AddYears(-2);

                        command.Parameters.Add("@ToDate", SqlDbType.VarChar).Value = DateTime.Now.ToShortDateString();

                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            adapter.Fill(ds);
                        }

                    }
                }
                dt = ds.Tables[0];
}
catch
{
}

Monday, 29 June 2015

Uploading files with Asp.net MVC

Uploading a single File:
Start with view having a form that will postback to the current action

<form action="" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file1" id="file1" />
  <input type="submit" />
</form>
 
In Controller
 
[HttpPost]
public ActionResult Index(HttpPostedFileBase file1) {

  if (file1.ContentLength > 0) {
    var fileName = Path.GetFileName(file1.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file1.SaveAs(path);
  }

  return RedirectToAction("Index");
} 


"~/App_Data/uploads" is a folder to upload files on server.
 
Uploading multiple files: 

In view 

<form action="" method="post" enctype="multipart/form-data">
  <label for="file1">File name:</label>
  <input type="file" name="files1" id="file1" />
  <label for="file2">File name:</label>
  <input type="file" name="files1" id="file2" />
  <input type="submit"  />
</form>
 
In Controller:
 
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file1 in files) {
    if (file1.ContentLength > 0) {
      var fileName = Path.GetFileName(file1.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file1.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
} 
Here we are getting list of files so we are using IEnumerable to list the files.
So you can upload multiples files on server.

Monday, 15 June 2015

Introduction to object oriented programing in C#

Class: A class is a blue print of an object that contains members and functions in it.

for ex:

class A
{
int a;
string s;
public void int sum(int a, int b
{
}
}

Object:An object is a instance of a class. You can create object of a class and access all the public variable and methods of that class.

for ex:

A objA=new Obj A();
int sum=a.sum(a,b);

Sunday, 22 March 2015

Design Patterns:Three layred or Tiered architechture

This article will provide you the basic knowledge of Layered architecture.

3 tier architecture
What is layer- A layer is a reusable code that can be used any where, in any project.
in .net a layer is setup as a project.
We can have multiple layers to segregate our project.
We are going to discuss three layered architecture here. in three layered architecture we have three layers:
1.Data Access Layer
2.Business Logic Layer
3.Presentation Logic Layer

1.Data Access Layer(DAL)- Data access layer is basically used to interact with database. We use ado.net to access database in this layer. BAL layer interact with DAL to interact with database. BAL call DAL function to send and receive data to database.

2.Business Access Layer(BAL)-BAL layer is basically used to define business logic, calculations, conversions and all the stuff that is required by Presentation Layer.

3.Presentation Logic Layer- This layer is basically used for user interface. Presentation layer always interact to BAL layer for any data required or to send any data to database.

Benifits of layered architecture:
1.Easy to maintain of code. Because all layers are seperated from other so we can change to any layer easyily.
2.Reusability of code: We can use the code anywhere in the same project or any other project using reference.
3.Provide a segregated architecutre.

Sunday, 15 February 2015

Ineterface with example in C#

Interface Definition: An interface is basically a contract or service which will implemented by other classes.
This implements the rules which will forced to use by derived classes.
Interface has only declarations of methods and properties. They do not have body in method they
have only the signatures.
Declaring Interfaces:

public interface IUser
{
void AddUser(User user);
void EditUser(int Id)
User GetUserByID(int Id);
}
Implementation:

public class User:IUser
{
public User GetUserByID(int Id)
{
 var context=...................;
var user=context.Users.find(Id);
return user;
}
public EditUser(int Id)
{
var context=...................;
var user=context.Users.find(Id);
context.Entry(user).State=EntityState.Modified;
context.SaveChanges();
}
public void AddUser(User user)
{
var context=...................;
context.Users.Add(user);
context.SaveChanges();
}
}

Thursday, 8 January 2015

How to add all the rows of a column to string with comma seperated

 Introduction: Here we have to add all the rows of a column to string with comma seperated.
Description:I am going to use coalesce function of sql server to achieve the result.
Query:

DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ',', '') + Name
FROM tbl_Names
print @Names

Monday, 29 December 2014

How to call javascript and jquery function from code behind in ASP.net and c#

Introduction: Here I will tell you how you can call javascript and jquery function 
from codebehind.
Descirption:
Here I will tell you how you can call javascript and jquery function from codebehind.
If you are using scriptmanager on page then you can call
ScriptManager instance.
If you are not using script manager then you can call 
Page.ClientScript instance

Implementation:
In Code Behind 
protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", 
 "MyFunction();", true);
} 

protected void MyButton_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.GetType(), "myScript", 
  "MyFunction();", true);
} 

Sunday, 28 December 2014

Abstract classes in C#.NET, VB.NET

Introduction: Abstract classes are those classes that can not be instantiated, but they can be inherited by 
other classes.
Description: Abstract classes are those classes that can not be instantiated, but they can be inherited by 
other classes. Abstract classes are base classes and inherited classes are called derived classes.
Abstract class can have both abstract and non abstract method in it. 
When to use: It is use to give common functionality to all inherited classes. it works like a base class.
Implementation:
abstract class MyShapes
{ 
abstract public int MyArea();
}
class Square : MyShapes
{
int side = 0;
 public Square(int n)
{ 
side = n; 
}
// Override Area method
public override int MyArea()
{ 
return side * side; 
}
}
class Rectangle : MyShapes
{
int length = 0, width=0;
public Rectangle (int length, int width)
{
this.length = length;
this.width = width;
// Override Area method 
public override int MyArea()
{ 
return length * width; 
}
}

Thursday, 4 December 2014

Call web method from page using jquery and ajax without postback

Introduction: In this article I will show you how to call webmethod from aspx page using jquery
and ajax without postback.

Description:  Call webmethod from aspx page using jquery and ajax without postback.



In Aspx Page:

<head runat="server">
    <title></title>
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetTime",
        data: '{name: "' + $("#<%=txtName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>
</head>

<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<div>
Your Name :
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
</form>
</body>


In Code Behind:

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}


Saturday, 8 November 2014

Bind Asp.net Dropdownlist from database in C#, VB.net

Introduction: Here I will explain how to bind dropdownlist from database.
Description: Today I will show you how to bind dropdownlist static and from database also I will
explain you how to find data in dropdownlist by text and by value.
Before implement this example we need database

Column NameDataTypeAllowNulls
UserId Int(set identity true) No
UserName VarChar(50) Yes
Location VarChar(50) Yes

Once table is designed write below code to your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>how to show data in dropdownlist from database in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Selected UserName:</b>
<asp:DropDownList ID="ddlUser" runat="server" />
</div>
</form>
</body>
</html


Now add the following namespace to code behind

C# code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

After add namespace write the following code to code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindUserdropdown();
}
}
/// <summary>
/// Bind Userdropdown
/// </summary>
protected voidBindUserdropdown ()
{
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlUser.DataSource = ds;
ddlUser.DataTextField = "UserName";
ddlUser.DataValueField = "UserId";
ddlUser.DataBind();
ddlUser.Items.Insert(0, new ListItem("--Select--", "0"));
con.Close();
}
}
VB.Net Code 
 
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class VBSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindUserdropdown()
End If
End Sub
''' <summary>
''' Bind UserDropdownlist
''' </summary>
Protected SubBindUserdropdown ()
'conenction path for database
Using con As New SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool")
con.Open()
Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
ddlUser.DataSource = ds
ddlUser.DataTextField = "UserName"
ddlUser.DataValueField = "UserId"
ddlUser.DataBind()
ddlUser.Items.Insert(0, New ListItem("--Select--", "0"))
con.Close()
End Using
End Sub
End Class
 

Wednesday, 5 November 2014

Compress and Extract files to zip in Asp.net C#

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplicationZip
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\source";
            string zipPath = @"c:\example\source\result.zip";
            string extractPath = @"c:\example\destination";

            ZipFile.CreateFromDirectory(startPath, zipPath);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}