Showing posts with label Console Appliation. Show all posts
Showing posts with label Console Appliation. Show all posts

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

Tuesday, 7 June 2016

How to replace single quote with double quote

In C#

                strComment = ""Manoj tyagi's photo;
                strComment = strComment.Replace("'", "''");


In Sql :

EX 1


DECLARE @sql varchar(max)
SET @sql = ' INSERT INTO ' + @tempTablea + 
       ' SELECT 0 as TypeA, 0 as TypeB, ' + ''''+
         replace( @name ,'''','''''')+''''+' as Name
       FROM #tempTableb tt2'

Ex 2

UPDATE myTable1
SET myField1 = REPLACE(myField1, '''', '"');

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

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

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

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

Thursday, 9 October 2014

Datatypes in C#

There are three types of data types in c#.
  1. Value Type
  2. Reference Type
  3. Pointer Type
Value Type:

The value types directly contain data. eg. int, char, float, which stores numbers, alphabets, floating point numbers, respectively. When you declare an type, the system allocates memory to store the value.

 int i=10;

Reference Type:

Object Type

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. So object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.
object obj;
obj = 100; // this is boxing

Dynamic Type

You can have any type of value in the dynamic data type. Type checking place at run-time for these type of variables.
Syntax :
dynamic <variable_name> = value;
For example,
dynamic d1 = 200;
 
In object type type checking take place at compile time and in dynamic type checking
take place at runtime. 

String Type

The String Type you can have any string value. The string type is an alias for the System.String class.
For example,
string str="Test String";


Pointer Type: 

Pointer type variables store the memory address of another type. These are like C or C++.
pointer type is:
type* identifier;
For example,
char* cptr1;
int* iptr1;



Introduction to C# Classes

A class is a group a related methods or you can say a class is a blue print. An 
object is a instance of that class. you can make as many objects of a class
and access methods and variables of that class. 

Here in this example Bike is a class and Describe and color are the methods of 
that class. We have create a object of Bike class in Main Method and call the 
functions here.
 
 
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Bike bike;
            bike= new Bike ("Red");
            Console.WriteLine(bike.Describe());
            bike= new Bike ("Green");
            Console.WriteLine(bike.Describe());
            Console.ReadLine();

        }
    }

    class Bike
    {
        private string color;
        public Bike(string color)
        {
            this.color = color;
        }
        public string Describe()
        {
            return "This Bike is " + Color;
        }
        public string Color
        {
            get { return color; }
            set { color = value; }
        }
    }
}

Monday, 22 September 2014

Read Connection settings from XML file C# and VB.Net

Using C#


public static string xxx = string.Empty;
    static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    public static string Connection()
    {
        DataSet _ds = new DataSet("MyDataSet");
        _ds.ReadXml(executableLocation + "\\ServerInfo.xml");
        if (_ds.Tables[0].Rows.Count > 0)
        {
            xxx = "Data Source=" + _ds.Tables[0].Rows[0]["DataSource"] + ";Database=" + _ds.Tables[0].Rows[0]["DatabaseName"] + ";uid=" + _ds.Tables[0].Rows[0]["UserName"] + ";pwd=" + _ds.Tables[0].Rows[0]["Password"];
            return xxx;
        }
        return xxx;
    }



Using VB.Net


Public Shared xxx As String = String.Empty
Shared executableLocation As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Public Shared Function Connection() As String
 Dim _ds As New DataSet("MyDataSet")
 _ds.ReadXml(executableLocation & "\ServerInfo.xml")
 If _ds.Tables(0).Rows.Count > 0 Then
  xxx = ((("Data Source=" + _ds.Tables(0).Rows(0)("DataSource") & ";Database=") + _ds.Tables(0).Rows(0)("DatabaseName") & ";uid=") + _ds.Tables(0).Rows(0)("UserName") & ";pwd=") + _ds.Tables(0).Rows(0)("Password")
  Return xxx
 End If
 Return xxx
End Function

Connection string in app.config file in c#

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="test" connectionString="Data Source=local;Initial Catalog=test;User ID=sa;Password=test;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="test" value="server=local;Initial Catalog=test;User ID=sa;Password=test"/>
  </appSettings>
  <system.net>
    <mailSettings>
      <smtp from="test@gmail.com">
        <network host="smtp.gmail.com" password="test" port="25" userName="test@gmail.com"/>
      </smtp>
    </mailSettings>
  </system.net>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

Read Pdf Files data Using coordinates with ITextSharp and C# and VB.Net

Using C#


public string[] ReadPdfFiles(string filepath, int pageno, int cordinate1, int coordinate2, int coordinate3, int coordinate4)
        {
            PdfReader reader = new PdfReader(filepath);
            string text = string.Empty;
            string[] words = null;
            try
            {

                iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(cordinate1, coordinate2, coordinate3, coordinate4);
                RenderFilter[] renderFilter = new RenderFilter[1];
                renderFilter[0] = new RegionTextRenderFilter(rect);
                ITextExtractionStrategy textExtractionStrategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
                text = PdfTextExtractor.GetTextFromPage(reader, pageno, textExtractionStrategy);
                words = text.Split('\n');
                return words;

            }
            catch (Exception Ex)
            {
                reader.Close();
                return words;
            }
            finally
            {
                reader.Close();
            }


        }


Using VB.Net


Public Function ReadPdfFiles(filepath As String, pageno As Integer, cordinate1 As Integer, coordinate2 As Integer, coordinate3 As Integer, coordinate4 As Integer) As String()


	Dim reader As New PdfReader(filepath)

	Dim text As String = String.Empty

	Dim words As String() = Nothing

	Try



		Dim rect As New iTextSharp.text.Rectangle(cordinate1, coordinate2, coordinate3, coordinate4)

		Dim renderFilter As RenderFilter() = New RenderFilter(0) {}

		renderFilter(0) = New RegionTextRenderFilter(rect)

		Dim textExtractionStrategy As ITextExtractionStrategy = New FilteredTextRenderListener(New LocationTextExtractionStrategy(), renderFilter)

		text = PdfTextExtractor.GetTextFromPage(reader, pageno, textExtractionStrategy)

		words = text.Split(ControlChars.Lf)



		Return words

	Catch Ex As Exception


		reader.Close()


		Return words
	Finally




		reader.Close()
	End Try



End Function

C# Console application to Exit from application

static void Main(string[] args)
        {
            Program prg = new Program();
            prg.ImportData();
            Environment.Exit(0);
        }