Showing posts with label c# snippets. Show all posts
Showing posts with label c# snippets. Show all posts

Fibonacci Numbers

Fibonacci Series:


Fibonacci examples:

The Fibonacci sequence is named after Leonardo of Pisa, who was known as Fibonacci (a contraction of filius Bonacci, "son of Bonaccio").
Fibonacci's 1202 book Liber Abaci introduced the sequence to Western European mathematics, although the sequence was independently
described in Indian mathematics and it is disputed which came first.



The sequence of number 1, 1, 2, 3, 5, 8, 13, 21, 34 . . . . each of which sum is the sum of the two previous numbers.
These numbers are also called Fibonacci numbers. The ratio of one Fibonacci to the preceding one is a Convergent of the
 continued fraction.The sum of the Fibonacci Sequence can be directly obtained from Pascal's triangle.Fibonacci numbers are
 named after Leonardo of Pisa, known as Fibonacci. The Fibonacci numbers are also a Lucas sequence.Fibonacci numbers can be given by,

Fn = Fn-1 + Fn-2

where, F1 = F2 = 1
F0= 0 F1= 1 F2= 1 F3= 2 F4= 3
F5= 5 F6= 8 F7= 13 F8= 21 F9= 34
F10= 55 F11= 89 F12= 144 F13= 233 F14= 377

source : wikipedia


csharp / c# program for Fibonacci series recursive example :


class Program
    {
        static void Main(string[] args)
        {
          Program p=new Program();
          
            Console.Write(p.Fib(14));
            Console.ReadLine();
        }

        public int Fib(int num)
        {
            int res;
            if (num == 1 || num == 0)
                return num;
            res = Fib(num - 1) + Fib(num - 2);
            return res;
        }
    }


Output : 377


how to insert the multipe records in sql server with xml data

while inserting multiple records at a same time in a single transaction without failure (eg: bulk booking cinema tickets) means how to do this. for that inserting datas in sql server via xml is better.By using this we can also stop the transaction failure.................

The following example shows how to insert the multiple records using xml data

CREATE TABLE [dbo].[empinfo](
    [eno] [int] NULL,
    [ename] [varchar](50)
)
Stored procedure:

Create  Procedure sp_InsertEmp

@in_XML Text
AS
Begin

DECLARE @XMLHandle AS INTEGER  

Declare  @temp table
(empno int,
 empname varchar(20)
)
----------------------------------------------------------------
-- Initialize the XML for Processing
----------------------------------------------------------------
EXECUTE sp_xml_preparedocument
        @XMLHandle      OUTPUT
      , @in_XML

INSERT @Temp
(
      empno,
        empname      
)
SELECT
    XMLInput.eno,
    XMLInput.ename  
FROM OPENXML(@XMLHandle,'NewDataset/employee',2)
WITH
(
      eno int,
        ename varchar(20)
)as XMLInput

----------------------------------------------------------------
-- Close the XML
----------------------------------------------------------------
EXECUTE sp_xml_removedocument @XmlHandle


insert into empinfo(eno,ename)

select empno,empname from @temp

End



--execute stored procedure

exec sp_InsertEmp

'<NewDataset>
<employee>
<eno>101</eno>
<ename>sidhu</ename>
</employee>
</NewDataset>'

kick it on DotNetKicks.com

Related Question :

1) how to insert the multiple records using c# and sqlserver
2) how to To Send Multiple Rows At Once Into A Stored Procedure
3) Work with XML Data Type in SQL Server 2005 from ADO.NET 2.0

Programmatically Download File from Remote Location to User Through Server

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//base.OnLoad(e);
string url = string.Empty;// Request.QueryString["DownloadUrl"];
if (url == null || url.Length == 0)
{
url = "http://img444.imageshack.us/img444/6228/initialgridsq7.jpg";
}

//Initialize the input stream
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int bufferSize = 1;

//Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg");
Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
Response.ContentType = "application/download";

//Populate the output stream
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);
Stream rs = req.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}

//Cleanup
Response.End();
ms.Close();
ms.Dispose();
rs.Dispose();
ByteBuffer = null;
}
}

Get the index of the SelectedRow in a DataGridView

The below codes show how to do that

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{

if (dataGridView1.SelectedRows.Count == 1)
{
txtCustcode.Text = dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].Cells["CustomerCode"].Value.ToString();
}
}

Data grid view multiple checkbox selection

this shows how to use datagrid view and check boxes , and find which check box was checked


for (int i = 0; i < dgGrid.Rows.Count; i++) { GridViewRow row = dgGrid.Rows[i]; bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked; if (isChecked) { xSideID = dgGrid.Rows[i].Cells[1].Text; } }













How to read the comma seperated values from a string asp.net C#?

string myString = "A, B, C, D";
string delimStr = " ,";
char[] delimiter = delimStr.ToCharArray();
foreach (string s in myString.Split(delimiter))
{
Response.Write (s.ToString ()+ "
");
}

How do I prevent a user from moving a form at run time?

The following code snippet shows how you can prevent a user from moving a form at run time:

[C#]
protected override void WndProc(ref Message m)
{
const int WM_NCLBUTTONDOWN = 161;
const int WM_SYSCOMMAND = 274;
const int HTCAPTION = 2;
const int SC_MOVE = 61456;

if((m.Msg == WM_SYSCOMMAND) && (m.WParam.ToInt32() == SC_MOVE))
{
return;
}

if((m.Msg == WM_NCLBUTTONDOWN) && (m.WParam.ToInt32() == HTCAPTION))
{
return;
}

base.WndProc (ref m);
}

[VB.NET]
Protected Overrides Sub WndProc(ByRef m As Message)
const Integer WM_NCLBUTTONDOWN = 161
const Integer WM_SYSCOMMAND = 274
const Integer HTCAPTION = 2
const Integer SC_MOVE = 61456

If (m.Msg = WM_SYSCOMMAND) &&(m.WParam.ToInt32() = SC_MOVE) Then
Return
End If

If (m.Msg = WM_NCLBUTTONDOWN) &&(m.WParam.ToInt32() = HTCAPTION) Then
Return
End If

MyBase.WndProc( m)
End Sub

How do I make my child Form fill the entire mdi client without being maximized?

Here is how it can be done. This takes into account all docked controls (including menus) in the mdi parent form.

[C#]
private void FillActiveChildFormToClient()
{
Form child = this.ActiveMdiChild;
Rectangle mdiClientArea = Rectangle.Empty;
foreach(Control c in this.Controls)
{
if(c is MdiClient)
mdiClientArea = c.ClientRectangle;
}
child.Bounds = mdiClientArea;
}



[VB.Net]
Private Sub FillActiveChildFormToClient()
Dim child As Form = Me.ActiveMdiChild
Dim mdiClientArea As Rectangle = Rectangle.Empty
Dim c As Control
For Each c In Me.Controls
If TypeOf c Is MdiClient Then
mdiClientArea = c.ClientRectangle
End If
Next
child.Bounds = mdiClientArea
End Sub

Avoid duplicate child form in MDI

How do I check to see if a child form is already displayed so I don't have two instances showing?

// MyChildForm is the one I'm looking for

MyChildForm childForm = null;
foreach(Form f in this.MdiChildren)
{
if(f is MyChildForm)
{
// found it
childForm = (MyChildForm) f;
break;
}
}

if( childForm != null)
{
childForm.Show();
childForm.Focus();
}
else
{
childForm = new MyChildForm();
childForm.MdiParent = this;
childForm.Show();
childForm.Focus();
}

Read Pdf file using c#

So you’ll have to download the PDFBox package. In this package you’ll find a bin directory. To read your PDF file, you’ll need the following files:

* IKVM.GNU.Classpath.dll
* PDFBox-0.7.3.dll
* FontBox-0.1.0-dev.dll
* IKVM.Runtime.dll

PDF Box Package is free distribution tool







You’ll have to add a reference to the first two in your project. You’ll also have to copy the last two on your project’s bin directory.


The program will look something like this (if you’re working with a Console application):



using System;
using org.pdfbox.pdmodel;
using org.pdfbox.util;
namespace PDFReader

{
class Program
{
static void Main(string[] args)
{
PDDocument doc = PDDocument.load("lopreacamasa.pdf");

PDFTextStripper pdfStripper = new PDFTextStripper();

Console.Write(pdfStripper.getText(doc));
}

}

}

read Excel file using c#

How to read an Excel file with OleDb and a simple SQL query?

This approach is extremely useful when you need to read the
data from an Excel file fast and store the data in a DataTable
for further usage.

using System.Data;
using System.Data.OleDb;

...

String sConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + [Your Excel File Name Here] + ";" +
"Extended Properties=Excel 8.0;";


OleDbConnection objConn = new OleDbConnection(sConnectionString);

objConn.Open();

OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);

OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

objAdapter1.SelectCommand = objCmdSelect;

DataSet objDataset1 = new DataSet();

objAdapter1.Fill(objDataset1);

objConn.Close();

Bind countries from CultureInfo class in C#

Some people have asked me how BlogEngine.NET displays a dropdown list of countries when no source XML file is present. The simple answer is that you don’t need any external list to bind to from C#, you can instead use the CultureInfo class.

Consider that you have the following dropdown list declared in an ASP.NET page:



Then from code-behind, call this method which binds the countries alphabetically to the dropdown:

public void BindCountries()
{
System.Collections.Specialized.StringDictionary dic = new System.Collections.Specialized.StringDictionary();
System.Collections.Generic.List col = new System.Collections.Generic.List();

foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
{
RegionInfo ri = new RegionInfo(ci.LCID);
if (!dic.ContainsKey(ri.EnglishName))
dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());

if (!col.Contains(ri.EnglishName))
col.Add(ri.EnglishName);
}

col.Sort();

ddlCountry.Items.Add(new ListItem("[Not specified]", ""));
foreach (string key in col)
{
ddlCountry.Items.Add(new ListItem(key, dic[key]));
}

if (ddlCountry.SelectedIndex == 0 && Request.UserLanguages != null && Request.UserLanguages[0].Length == 5)
{
ddlCountry.SelectedValue = Request.UserLanguages[0].Substring(3);
}
}

The method first adds all the countries from the CultureInfo class to a dictionary and then sorts it alphabetically. Last, it tries to retrieve the country of the browser so it can auto-select the visitors country. There might be a prettier way to sort a dictionary, but this one works.

Difference between two dates

This snippet calculates the difference between two dates.

DateTime d1 = new DateTime( 2000, 7, 13 );
DateTime d2 = new DateTime( 2003, 12, 5 );
TimeSpan s = d2 - d1;
int numberofdays = s.TotalDays