Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, March 29, 2015

c#.net with Mongodb tutorial

Follow this below link :

http://www.codeproject.com/Articles/273145/Using-MongoDB-with-the-Official-Csharp-Driver

About MongoDB :

It's a Document Oriented Database. The data structure stored here is in similar to JSON. It is also classified as one of the popular NoSQL Database.



Thursday, December 5, 2013

Generate PDF from a html string using ItextSharp in asp.net (c#)

In this post i will show how to create a pdf file from a html string using itextsharp in asp.net.

Below is the code to do this (There may be redundant code in the given sample below. So you can edit the below code as per your needs)

//creating html:

        public void ViewReportPDF(Int32 EmpID)
        {
            SqlCommand cmd = new SqlCommand("USP_GET_EMP_DATA");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@empid", EMPID);
            DataSet ds = GetDataSet(cmd);

            int count = 0;
            string s1 = " <table border='1' width='100%'>";

            string s2 = "";

            for (int j = 0; j <= ds.Tables.Count - 1; j++)
            {
                for (int i = 0; i <= ds.Tables[j].Rows.Count - 1; i++)
                {
                    for (int k = 0; k <= ds.Tables[j].Columns.Count - 1; k++)
                    {
                        if (count == 2)
                        {
                            count = 0;
                        }

                        if (count == 0)
                        {
                            s2 = s2 + "<tr>";
                        }

                        s2 = s2 +
                        "<td>" + ds.Tables[j].Columns[k].ColumnName + "</td>" +
                        "<td>" + ds.Tables[j].Rows[i][k] + "</td>";

                        count++;

                        if (count == 2)
                        {
                            s2 = s2 + "</tr>";
                        }
                    }
                }
            }

            string s3 = "</table>";

            string htmlText1 = s1 + s2 + s3;
            HTMLToPdf(htmlText1);
        }

//creating pdf using itextsharp and saving it in the application folder:

        public void HTMLToPdf(string HTML)
        {
            Document document = new Document(PageSize.A4);
            PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\EMP.pdf", FileMode.Create));
            document.Open();
            iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
            iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
            hw.Parse(new StringReader(HTML));
            document.Close();
            string ss = Request.PhysicalApplicationPath.ToString() + "\\EMP.pdf";
            ShowPdf(ss);
        }

//showing pdf from folder where it was saved.

        private void ShowPdf(string s)
        {
            string fileName = Path.GetFileNameWithoutExtension(s);
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + "EMP" + ".pdf");
            Response.TransmitFile(Request.PhysicalApplicationPath.ToString() + "\\" + fileName + ".pdf");
            HttpContext.Current.ApplicationInstance.CompleteRequest();

        }

Output:

The output of pdf would be in below structure as given below:


Wednesday, December 4, 2013

Applying join on two datatable in asp.net (c#) using LINQ | using join, where clause in LINQ

Applying join on two datatable in asp.net (c#) using LINQ.

Below is the Query :

1.LINQ Join Query:

DataTable result = (from t1 in SomeDatatable1.AsEnumerable()
                    join t2 in SomeDatatable2.AsEnumerable() on t1.Field<string>("EmpId") equals                                                                                       t2.Field<string>("EmpId")
                    select t1).CopyToDataTable();


2.LINQ Join with Where clause Query:

DataTable result = (from t1 in SomeDatatable1.AsEnumerable()
                    join t2 in SomeDatatable2.AsEnumerable() on t1.Field<string>("EmpId") equals                                                                                       t2.Field<string>("EmpId")
                    where t2.Field<string>("EmpId") == "100"
                    select t1).CopyToDataTable();

Friday, September 13, 2013

calculating days,months,years difference between two dates in asp.net,C# | calculating date difference using timespan to calculate days,months,years

hi in this post i will show how to calculate days,months and years between two date in asp.net,c#(code-behind):

Below is the code for this:

public void calcDayMonthYear()
{

        DateTime dayStart;
        DateTime dateEnd;

        dayStart = Convert.ToDateTime(frmdate.Text);
        dateEnd = Convert.ToDateTime(todate.Text);
        TimeSpan ts = dateEnd - dayStart;

        double Years = Convert.ToDouble(ts.TotalDays) / 365;
        double Months = Years * 12;
        double Days = Convert.ToDouble(ts.TotalDays); 


}

example to call a javascript function from code-behind or server-code using ScriptManager in asp.net,c#

hi in this post i will show how to call a javascript function from codebehind in asp.net :

Example:

aspx.cs page(codebehind):

 protected void testMethod()
    {
 ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage1", "ShowalertMessage();", true);
    }

aspx page:
 <script type="text/javascript" language="javascript">
  function ShowalertMessage() {
            alert('hello world!');
        }
    </script>

Monday, August 26, 2013

Implementing Factory design pattern in asp.net using c# | Design Patterns | Example Factory design pattern

hi in this post i will show how to implement the Factory design pattern in asp.net

In Factory design pattern we cannot directly create the object of the class we need to send our requirement to the factory class. This factory class will provide us the required object.

it helps us to create object without exposing the instantiation logic to client.

Example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ConsoleApplication1
{
    interface color
    {
        string GetCarColor();
    }

    class myFactory
    {
        public color GetObj(int type)
        {
            color interfaceObj = null;
            switch (type)
            {
                case 1:
                    interfaceObj = new car1();
                    break;
                case 2:
                    interfaceObj = new car2();
                    break;
                case 3:
                    interfaceObj = new car3();
                    break;
            }
            return interfaceObj;
        }
    }

    class car1 : color
    {
        public string GetCarColor()
        {
            return "Red color car";
        }

    }
    class car2 : color
    {
        public string GetCarColor()
        {
            return "Blue color car";
        }
    }
    class car3 : color
    {
        public string GetCarColor()
        {
            return "White color car";
        }
    }
}

/////Main Class

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            myFactory obj = new myFactory();
            color c = obj.GetObj(2);
            string s = c.GetCarColor();
            Console.WriteLine(s);
            Console.ReadLine();

        }
    }
}

Thursday, August 8, 2013

using singleton pattern in .net | example of using the singleton patter in .net c# | Design Patterns

Design Pattern : Singleton

Singleton pattern assures that only a single object will be created for any class and the same object will be used in the application.

Example (Adding Numbers ) :

Solution Explorer


Class file (here we will be writing the code for implementing singleton pattern)

public class CommonClass
{
    private static CommonClass _instance;
    protected CommonClass()
    {
    }
    public static CommonClass Instance()
    {
        if (_instance == null) _instance = new CommonClass();
        return _instance;
    }

    public int addNumber(int x, int y)
    {
        return (x + y);
    }

}


ASPX :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowAddNumber.aspx.cs" Inherits="ShowAddNumber" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter Numbers to Add :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <br />

          Result 1: <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
          Result 2: <asp:Label ID="Label2" runat="server" Text=""></asp:Label>

        <br />

        <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>


Codebehind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ShowAddNumber : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void Button1_Click(object sender, EventArgs e)
    {
        CommonClass s1 = CommonClass.Instance();
        Label1.Text = s1.addNumber(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text)).ToString();

        CommonClass s2 = CommonClass.Instance();
        Label2.Text = s2.addNumber(int.Parse(TextBox1.Text) + 5, int.Parse(TextBox2.Text) + 5).ToString();

        if (s1 == s2)
        {
            lblMsg.Text = "Same Object Used";
        }
    }

}


Output :



Thursday, July 11, 2013

WCF Method Overloading Example in c#.net | Implementing method overloading in WCF

hi in post i will show how to implement method overloading in WCF using c#.net.

Example :

Take a new WCF Service Application Project.

1. IService1.cs --> Interface code

 [ServiceContract]
    public interface IService1
    {
        [OperationContract(Name="GetDataValue1")] //Method overloading
        string GetData(int value);

        [OperationContract(Name = "GetDataValue2")] //Method overloading
        string GetData(string value);
    }

2. Service.svc.cs 

    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public string GetData(string value)
        {
            return string.Format("You entered: {0}", value);
        }
       
    }

3. Result :




Tuesday, July 2, 2013

Logic to reverse a word string in c# | reverse a string in c#.net

hi a basic code on how to reverse a word(string) in c#.net.

Logic :

string reverseStr()
        {
            string s = "programming";
            char[] c = s.ToCharArray();
            string strReverse = "";
            for (int i = c.Length - 1; i > -1; i--)
            {
                strReverse += c[i];
            }

            return strReverse;
        }

Example:



find duplicate records in a datatable using LINQ | Example to find duplicate values from datatable or dataset using Linq Query

hi in this post i will show to find duplicate records in a datatable or dataset using LINQ.

Example:

Below is the sample employee table which i will take it into a datatable and then will search for duplicate employee names present inside the table using a LINQ query.

1. EMP Table

Code :

 public void checkDuplicate()
    {
        string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
        StringBuilder s = new StringBuilder();
        SqlConnection s1 = new SqlConnection(conStr);
        s1.Open();

        string queryString = "SELECT * FROM employee";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, s1);

        DataSet employee = new DataSet();
        adapter.Fill(employee, "employee");

        var duplicateRecords = employee.Tables[0].AsEnumerable()
                 .GroupBy(r => r["EmpName"]) //coloumn name which has the duplicate values
                 .Where(gr => gr.Count() > 1)
                 .Select(g => g.Key);


        foreach (var d in duplicateRecords)
        {
           s.Append("," + d.ToString());
        }

         Response.Write("<script language='javascript'>alert('Duplicates Names: "+ s.ToString() +"');</script>");
         s1.Close();
        
    }

Output :

Output


Thursday, June 20, 2013

asp.net(C#) adding columns and rows for datatable in Codebehind | Example for adding rows, column manually in datatable from codebehind

hi in this post i will show how to manually add columns and rows in datatable from a codebehind page in asp.net (c#).

Below is the sample code for this :

public void createDatatable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Salary");

        DataRow firstRow = dt.NewRow();
        firstRow["Name"] = "Chandan";
        firstRow["Salary"] = "1000";

        dt.Rows.Add(firstRow);

        DataRow SecondRow = dt.NewRow();
        SecondRow["Name"] = "Subodh";
        SecondRow["Salary"] = "2000";

        dt.Rows.Add(SecondRow);

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Monday, June 17, 2013

Logic Fibonacci series | Fibonacci series in c#.net | Interview Questions Fibonacci sequence

hi below is the logic to get the Fibonacci sequence :

Logic:

 fibo(int n)
        {
            int a = 0;
            int b = 1;

            for (int i = 0; i <= n; i++)
            {
                int temp = a;
                a = b;
                b = temp + b;
                print(a);
            }
        }


C# Implementation :





Sunday, June 16, 2013

Struct and Class Example | Difference Between Struct and Class

Structs and Class:

struct class
1 It is value type It is Reference Type
2 Default access specifier is Public Default access specifier is Private
3 It only has Constructor It has both Constructor and Destructor
4 Struct has values residing on Stack  Class have Object values residing on Heap and it has references to the objects on stack
5 do not support Inheritance It Supports Inheritance

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    struct emp
    {
        public int empid;
        public string empname;
    }

    class dept
    {
        public int deptid;
        public string deptname;
    }

    class Program
    {
        static void Main(string[] args)
        {
            emp e = new emp();
            emp e2 = e;

            e.empid = 1;
            e.empname = "chandan";

            e2.empid = 2;
            e2.empname = "Rahul";

            Console.WriteLine("ID:{0} and Name:{1}", e.empid, e.empname);
            Console.WriteLine("ID2:{0} and Name2:{1}", e2.empid, e2.empname);

            dept d = new dept();
            dept d2 = d;

            d.deptid = 100;
            d.deptname = "Accounts";

            d2.deptid = 101;
            d2.deptname = "IT";

            Console.WriteLine("ID:{0} and Name:{1}", d.deptid, d.deptname);
            Console.WriteLine("ID2:{0} and Name2:{1}", d2.deptid, d2.deptname);

            Console.ReadLine();
        }
    }
}

Result :

class object referring to the same values whereas struct has new values assigned