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 6 July 2015

SQL Server Database Queries Part 1

Select Statement:

select * from Subjects;

Aliasing Column Name:
you can rename column according to your need using AS keyword.
select subjectname as subject from subjects;


Eliminating duplicate records:(Distinct Clause)
you can eliminate duplicate records using DISTINCT Keyword from resultset.
Select distinct subjectname from subjects;

Filtering Data(Where Clause):

you can filter data using WHERE clause with some condition,
Select subject;name from subjects where subjectid=3;
Select subject;name from subjects where subjectid>3;



The 'Not' Clause:

you can use NOT keyword condition
Select subjectname from subjects where subjectname IS NOT NULL;
SELECT SUBJECTNAME FROM SUBJECTS WHERE SUBJECTID NOT IN (2,3);

Filtering String:
you can filter string using LIKE keyword and %.
'H%' will return all the records start with 'H'.
'%H' will return all the records end with 'H'.
'%H%'  will return all the records start and end with 'H'.

Select subjectname from subject where name like('H%')  ;
  
The In and Between Keywords:

you can use IN clause when you have multiple ids you can get all records which are IN();
select * from subjects where subjectid in (2,3);

you can user BETWEEN clause when you want to get records between some range.

select * from subjects where subjectid BETWEEN 2 and 3;

Sorting Data(Order By Clause):
you can sort resultset using ORDER BY clause.
select * from subjects ORDER BY subjectname;

Limiting Records(Top Clause):

you can limit records by using TOP clause in your query.
select TOP 2 * from subjects ORDERBY subjectname;

OFFSET FETCH:

you can use OFFSET to keep and skip records. It is useful in paging concept.
SELECT * FROM SUBJECTS OFFSET 10 ROWS FETCH NEXT 25 ROWS ONLY;

AGGREGATING DATA; GROUP BY AND HAVING CLAUSE
you can use GROUP BY clause to get record set in Group.
SELECT COUNT(*) FROM SUBJECTS GROUP BY SUBJECTNAME;

Select from multiple tables (Using Joins)

Joins are very useful when you want to get data from multiple tables.
select * from subjects , books;

select a.subjectname,b.bookname from subjects a, books b where a.SubjectID=b.Subject;

There are different type of joins in sql.

Cross Join:

It will return Carthesian Product. 

select * from books CROSS JOIN subjects;

Inner Join:

It is the most useful join. It is optional to use Inner Keyword. It is used in place of where and is a
proper way of join. it will return all the matching rows based on conditon.

select * from subjects INNER JOIN BOOKS ON SUBJECTS.SUBJECTID=BOOKS.SUBJECT;

Outer Join:

Outer joins are used when we want to matching and unmatching data from tables. it is of two types.

Left Outer Join:

It returns all matching of left and all of right records.


SELECT * FROM SUBJECTS LEFT OUTER JOIN BOOKS ON SUBJECTS.SUBJECTID=BOOKS.SUBJECT;

Right Outer Join:

It return all record of left and matching of right.

SELECT * FROM SUBJECTS Right OUTER JOIN BOOKS ON SUBJECTS.SUBJECTID=BOOKS.SUBJECT; 

Ranking Functions:
 
 There are four ranking functions in sql server.
  1. ROW_NUMBER
  2. RANK
  3. DENSE_RANK
  4. NTILE
ROW_NUMBER simply select the no of current row.
RANK and DENSE_RANK assisgn unique number to each row.
RANK return total no of rows of same rank plus 1.
DENSE_RANK return rank plus 1.


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

Abstraction in OOPS C#

Abstraction: Abstraction is to hiding the complexity of object and showing the essential features of that object. It focus on what object can do instead of how it can do.
"Abstraction is to hiding the working style of an object and showing the information of an object as understandable manner"

Real world example of Abstraction:

Suppose we take example of Mobile phones.

Nokia 2710 (Features: Calling, SMS)
Nokia 3110 (Features: Calling, SMS, FM Radio, MP3, Camera)


Abstract information(All mobile phones makes a call to any number and can send SMS)

for that you have to make a abstract class:

abstract class MobilePhone
    {
        public void Calling();
        public void SendSMS();
    }

public class Nokia2710 : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
    }

    public class Nokia3110 : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
        public void Recording();
        public void ReadAndSendEmails();
    }

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);

Tuesday 26 May 2015

What is Xaml?

XAML stands for extensible Application markup language, is variant of xml describing GUI. In winforms GUI framework was created in same language that you would use for interacting with the GUI like vb.net or c#.net.

Sunday 10 May 2015

Hello World in WPF- WPF Tutorial

In xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="60">Hello World</TextBlock>
    </Grid>
</Window>

After run program





For more info visit:
http://webxperts.co.in/


Loop throuth all textboxes in Winforms

For iterating through all textboxes in winforms:

foreach (TextBox TextBox in this.Controls.OfType<TextBox>())
            {
                if (TextBox.BackColor == Brushes.Green)
                {
                    //your code
                }
            }

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