Login Page in ASP.net

To make a login page which would acess the database and tell the user that he has been loged on we will require a database table in which username and password is stored. This work will be done in 3 parts
First make a connection string Secondly accessing the data and thirdly loging in.

First we have to make a connection string the connection string is made in Web.Config like this

<connectionStrings>

<add name=”ConnectDBString” connectionString=”server=localhost;Database=test;Integrated Security=SSPI;” />

</connectionStrings>

by this we have made a connection string a connection string has 3 basic parts 1. Server Name 2. Database Name and 3. Authentication Type.
After making the connection string we have to get data from the database to get the data we will use connection less approach and we will get data by calling a stored procedure from database
To get data from database we write these lines to read the connection string from web.config

public db_data()
{
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectDBString"].ConnectionString;

try
{
objcon = new SqlConnection(myConnectionString);
}

catch (Exception ex)
{

}
}

public DataTable Athuntication(string username, string password)
{
SqlCommand m_SqlCmd = new SqlCommand();
m_SqlCmd.CommandText = “dbo.[pr_select_login]“;
m_SqlCmd.CommandType = CommandType.StoredProcedure;
DataTable dtToReturn = new DataTable(“tbl_login”);
SqlDataAdapter m_SqlAdp = new SqlDataAdapter(m_SqlCmd);
m_SqlCmd.Connection = objcon;
try
{
m_SqlCmd.Parameters.Add(new SqlParameter(“@username”, SqlDbType.VarChar, 30, ParameterDirection.Input, false, 10, 0, “”, DataRowVersion.Proposed, username));
m_SqlCmd.Parameters.Add(new SqlParameter(“@password”, SqlDbType.VarChar, 50, ParameterDirection.Input, false, 10, 0, “”, DataRowVersion.Proposed, password));

m_SqlAdp.Fill(dtToReturn);
return dtToReturn;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}

}

}

Now we have a datatable full of required data we can use this for logging in.

GridView with Fixed Headers in ASP.Net using C# and SQL using CSS

We everyday use grid view for viewing data the problem with the data on the web is that when we scroll down the header of the gridview also go down which is not good and makes things difficult to read.

So I made a program which will stop this and the girdview will keep on scrolling without moving the headers this can be accomplished with both CSS and Jquery we will be using CSS for this.

First we will make a connection string and fetch the data.Then we assign the data to the Gridview

sda.Fill(dt);
     GridView1.DataSource = dt;
     GridView1.DataBind();
     GridView1.HeaderRow.Attributes["style"] = "display:none";
     GridView1.UseAccessibleHeader = true;
     GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

The magic starts with the line written in this the Style of Header row we have disabled the original headers and we will now make our own headers.

We make a html table and put data in it

ID Name

Then we change the gridview settings

And then apply the style sheet

  .grid
    {
        font-family:Arial;
        font-size:10pt;
        width:600px
    }
    .grid THEAD
    {
         background-color:Green;
         color:White;
    }

File Transfer Application

                                                                              Huda Ijaz

 Introduction

The article demonstrates how to write a c# application which can be used to transfers files from client computer to server computer over the LAN or WAN (internet) using TCP protocol classes available in C# .net .

Core Working

The program works in two sections, mean there would be two applications working in contact with each other simultaneously; one is Server and another is Client. At first, the server will open a port and will wait for a request from the client, and the client will try to connect to the server. After getting a connection request, the server will accept it and will make a successful connection. After a successful connection, the client will send data in byte array and the server will catch and hold it. Then, it will save these bytes. After successful data transfer, the server will save data and disconnect client. The file is selected from and stored in a given directory by using “OpenFileDialog” control in client app and by “folderBrowserDialog” control in server app.

Using the code

The code for Server and Client applications with some comments is as given below:

Server

server


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace FileTransfer
{
    public partial class Form1 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        string rd;
        byte[] b1;
        string v;
        int m;
        TcpListener list;
        Int32 port = 5050;
        Int32 port1 = 5055;
        IPAddress localAddr = IPAddress.Parse("192.168.1.20");
private void Browse_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog1.SelectedPath;
                TcpListener list = new TcpListener(localAddr,port1);
                list.Start();
                TcpClient client = list.AcceptTcpClient();
                Stream s = client.GetStream();
                b1 = new byte[m];
                s.Read(b1, 0, b1.Length);
                File.WriteAllBytes(textBox1.Text + "\\" +   rd.Substring(0,            rd.LastIndexOf('.')), b1);
                list.Stop();
                client.Close();
                label1.Text = "File Received......";
            }
         }        
        private void Form2_Load(object sender, EventArgs e)
        {
            TcpListener list = new TcpListener(localAddr, port);
            list.Start();
            TcpClient client = list.AcceptTcpClient();
            MessageBox.Show("Client trying to connect");
            StreamReader sr = new StreamReader(client.GetStream());
            rd = sr.ReadLine();
            v = rd.Substring(rd.LastIndexOf('.') + 1);
            m = int.Parse(v);
            list.Stop();
            client.Close();
        }
    }
} 

client


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
namespace FileTransfer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string n;
        byte[] b1;
        OpenFileDialog op;
        private void button1_Click(object sender, EventArgs e)
        {
            op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
            {
                string t = textBox1.Text;
                t = op.FileName;
                FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
                n = fi.Name + "." + fi.Length;
                TcpClient client = new TcpClient("SwtRascal", 5055);
                StreamWriter sw = new StreamWriter(client.GetStream());
                sw.WriteLine(n);
                sw.Flush();
                label1.Text = "File Transferred....";
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            TcpClient client = new TcpClient("Ravian", 5050);
            Stream s = client.GetStream();
            b1 = File.ReadAllBytes(op.FileName);
            s.Write(b1, 0, b1.Length);
            client.Close();
            label1.Text = "File Transferred....";
        }
    }
} 

How to store and Retrieve Images in Database using C#

We Programmers, daily use database for different work but the main thing is that we only save text and other stuff but we never post and save images in the databse
To save the images in the database we should have to first convert them to the bytes and when they would be retrived the method will be opposite first the bytes stored in the database will be coverted back to the bytes and then to image the sample code is as following

private void btnLoad_Click(object sender, EventArgs e)
{
try
{

FileDialog fldlg = new OpenFileDialog();

//specify your own initial directory

fldlg.InitialDirectory = @”:D\”;

//this will allow only those file extensions to be added

fldlg.Filter = “Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif”;

if (fldlg.ShowDialog() == DialogResult.OK)
{

imagename = fldlg.FileName;

Bitmap newimg = new Bitmap(imagename);

//pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

//pictureBox1.Image = (Image)newimg;
MessageBox.Show(“Image Loaded”);

}

fldlg = null;

}

catch (System.ArgumentException ae)
{

imagename = ” “;

MessageBox.Show(ae.Message.ToString());

}

catch (Exception ex)
{

MessageBox.Show(ex.Message.ToString());

}
}

private void retrive_Click(object sender, EventArgs e)
{
DataTable dataTable = dset.Tables[0];

//if there is an already an image in picturebox, then delete it

if (pictureBox2.Image != null)
{

pictureBox2.Image.Dispose();

}

//using filestream object write the column as bytes and store
//it as an image

FileStream FS1 = new FileStream(“image.jpg”, FileMode.Create);

foreach (DataRow dataRow in dataTable.Rows)
{

if (dataRow[0].ToString() == comboBox1.SelectedItem.ToString())
{

byte[] blob = (byte[])dataRow[1];

FS1.Write(blob, 0, blob.Length);

FS1.Close();

FS1 = null;

pictureBox2.Image = Image.FromFile(“image.jpg”);

pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;

pictureBox2.Refresh();

}

}
}
}
}

Govt. College University Lahore
Computer Science Dept.
Author Name : M Hashim Bajwa
Roll No: 063-bscs-2010
Section: A

Console Based Hangman game

Aatif Ishtiaq

119-BSCS-2010
Section B

Introduction

This is a console based game I developed in 2nd semester. The core language is c++. In this game user enters a word and ask another user to guess that word, for every wrong alphabet, A man will start to appear, and if all the lives run out then, eventually that man will be hanged.

Background

This game is a traditional one, More like Ludo etc. Many develepors have spent hours on its concept. My aim ehilr developomg this game was to practice my c++ skills.

In the code:

It is implemented in structred base programming rather then OOP.
It contains following methods.


void show_word();
void guess_word();
void head();
void arms();
void tummy();
void leg1();
void leg2();
void hang();
void set_position();


void head()
{
cout<<"  , ,  ";gotoxy(wherex()-7,wherey()+1);
cout<<"( o o )";gotoxy(wherex()-7,wherey()+1);
cout<<"!  ^  !";
}

void arms()
{
for(int i=0;i<8;i++)
cout<<"_";
}

void tummy()
{
for(int i=0;i<3;i++)
{
cout<<"|";
gotoxy(wherex()-1,wherey()-1);
}
}

void leg1()
{
for(int i=0;i<5;i++)
{
cout<<"|";
gotoxy(wherex()-2,wherey()+1);
}
}

void leg2()
{
for(int i=0;i<5;i++)
{
cout<<"|";
gotoxy(wherex(),wherey()+1);
}
}

void hang()
{
cout<<"-------";gotoxy(wherex()-7,wherey());
for(int i=0;i<6;i++)
{
gotoxy(wherex()-1,wherey()-1);
cout<<"|";
}
}

  1. Enter a word.
    Capture
    Capture1
  2. Guess the word.
    Capture3
  3. In case you choose a wrong word.
    Capture4

Summary

When the user submits a word, it is saved into an array of chars. Then when user guesses the word, each word is compared with the already submited word. If all the alphabets are correct user wins otherwise user is hanged.

Speech Recognition

Table of contents :

  • Introduction
  • Code

Introduction:

Speech recognition (SR) is the translation of spoken words into text. It is also known as “automatic speech recognition”, “ASR”, “computer speech recognition”, “speech to text”, or just “STT”. Some SR systems use “training” where an individual speaker reads sections of text into the SR system. These systems analyze the person’s specific voice and use it to fine tune the recognition of that person’s speech, resulting in more accurate transcription. Systems that do not use training are called “Speaker Independent” systems. Systems that use training are called “Speaker Dependent” systems.The term voice recognition refers to finding the identity of “who” is speaking, rather than what they are saying.

Code:

Untitleds

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Speech.Recognition;

namespace VoiceRecognition_Application
{

public partial class MainWindow : Window
{
private SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
public MainWindow()
{
InitializeComponent();
}

private void buttonRec_Click(object sender, RoutedEventArgs e)

{
_recognizer.SetInputToDefaultAudioDevice();

_recognizer.LoadGrammar(new DictationGrammar());
_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recognizer_SpeechRecognized);
_recognizer.RecognizeAsync(RecognizeMode.Multiple);

}

void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
foreach (RecognizedWordUnit word in e.Result.Words)
{
listBoxResults.Items.Add(word.Text);
}

}
}
}

Umer Butt(024-bscs-2010)

Task Schedular

How to make a Task schedular with custom colored progress bars and interchanging wallpaper according to time.

 

Using the timestruct, the timestruct method takes the time from the computer and uses it in the program.

tsk schdler

The main label Displaying the current system time and date

{
label4.Text = DateTime.Now.ToLongTimeString();
}

{
label5.Text = DateTime.Now.ToString(“ddd,d MMM,yyyy”);

}

The progress bar displaying the seconds time and integrating it with the progress bar, the rest can be edited the same way

{
label3.Text = DateTime.Now.ToString(“ss”);
}

{
progressBar1.BackColor = Color.PowderBlue; // seconds progress bar design
progressBar1.ForeColor = Color.Navy;
progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
string sec = DateTime.Now.ToString(“ss”);  // taking the system seconds, converting them to int and integrating it to the progress bar
int se = Convert.ToInt16(sec);
progressBar1.Value = se;
progressBar1.Update();
}

Opening the Dialog to select the file

dlg = new OpenFileDialog(); // on clicking the button opens the file dialog
dlg.DefaultExt = “.exe”; // file dialog default extension, i chose .exe
dlg.Filter = “All Files|”; // dialog box filter
dlg.FilterIndex = 0; // number of files that can be selected in the dialog box
dlg.Multiselect = false; // multi-select option not available
dlg.InitialDirectory = Directory.GetCurrentDirectory(); // the initial directory when file dialog is opened
if (dlg.ShowDialog(this) == DialogResult.OK) // gets the address of the selected file
{

if (dlg.FileName != string.Empty) // condition on the selected file, gets selected file name and address
{
textBox3.Text = dlg.FileName; // shows the selected file’s address and name
fn = textBox3.Text; // taking the file name string named ‘ fn’ for later use
}

After selecting the file,setting the time from the date-time dropdown box and comparing it with the current time, the set date and time is displayed in the header.

 

if (checkBox1.Checked == true) // condition if the checkBox is checked
{
if (fn != null) // if string ‘ fn ‘ is not empty
{
this.Text = “Task – Set: (” + dateTimePicker1.Value.ToShortDateString() + “)_(” + dateTimePicker2.Value.ToShortTimeString() + “)”; // the task is set and the scheduled time and date is displayed on the header

if
(DateTime.Now >= dateTimePicker1.Value) // condition to compare the scheduled and current time
{ f = 2; }
else
{ f = 0; };

if
(DateTime.Now >= dateTimePicker2.Value)// condition to compare the scheduled and current date
{ g = 2; }
else
{ g = 3; };

if (f == g)
{
checkBox1.Checked = false; // if the conditions have been fulfilled,the checkbox is unchecked so as to break loop
System.Diagnostics.Process.Start(@fn);// using system diagnostics, the selected file starts
MessageBox.Show(“Task Activated”);
textBox3.Clear(); // textbox is restarted
}
else { };
}
else
{
checkBox1.Checked = false;  // if no file is selected, shows this message
MessageBox.Show(“Please select an App to run”);

}
}
}

Changing the desktop walpaper and the progress bar colour, the pre-defined walpapers are stored in the resources folder and picked up from there.

{ string hour = DateTime.Now.ToString(“hh”);
int hr = Convert.ToInt16(hour);

int h = 1;
int i = 3;
int j = 6;
int k = 9;
int l = 12;
if (h<=2)
{
if (hr<=i)
{ this.BackgroundImage = Properties.Resources.tsk4; }
else
{
if ( hr <= j)
{ this.BackgroundImage = Properties.Resources.tsk1; }
else{
if ( hr <= k)
{ this.BackgroundImage = Properties.Resources.ts2; }
else{

if ( hr <= l)
{ this.BackgroundImage = Properties.Resources.tsk5; }

}}}
}

}

 

Hope this help’s. Thank you.

Client Server Application using C#

Download: Project Archive

In this simple article you will learn “How to program a client _server application in Console.

Requirements:

We need Following Namespaces

reference

*Threading will be used at server side to get multiple clients on stream.

How it works:

Client:
In main method we create a TcpClient through which it will connect  to Server.

static void Main(string[] args)
{
TcpClient client = new TcpClient("server IP",5000);
NetworkStream ns = client.GetStream();
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
ParameterizedThreadStart pts = new ParameterizedThreadStart(recieve);
Thread t = new Thread(pts);
t.Start(sr);
while (true)
{
String s = Console.ReadLine();
sw.WriteLine(s);
sw.Flush();

}
}

NetwrokStream class help us in making a connection between server and client. Stream Reader is used to read the message from server, Stream writer to write to stream or to transfer the message from client to server.

while (true)

{

String s = Console.ReadLine();

sw.WriteLine(s);

sw.Flush();

}

This piece of code will help us in sending messages to server.

How client receive message:

public static void recieve(Object obj)
{
    string s = "";
    StreamReader sr = (StreamReader)obj;

    while(true)
    {
       s= sr.ReadLine();
       Console.WriteLine(s);
    }
}

StreamReader at client side is used to read messages from Server. You read a message form server and write it on console.

Server:

At server side we need a arraylist to store multiple client and to forecast the message to each client. I am using three threads: Main thread, second thread to read and third one is to connect the client.

static ArrayList list = new ArrayList();

static void Main(string[] args)
{

Thread te= new Thread(run);

te.Start();

while (true)

{

String consread = Console.ReadLine();

for (int i = 0; i < list.Count; i++)

{

Socket soket = (Socket)list[i];

StreamWriter writer = new StreamWriter(new NetworkStream(soket));

writer.WriteLine(consread);

writer.Flush();

}

This piece of code is getting each client from the list and sending the message to it.

How server read:

public static  void read(Object obj)
{

String read = "";

StreamReader strread = (StreamReader)obj;

while(true)
{

read=strread.ReadLine();

Console.WriteLine(read);

}

}

Connecting a client:

public static void run ()
{

Program socket_store = new Program();

IPAddress ipadrs = IPAddress.Parse("IP of the server");

TcpListener tcplsnr = new TcpListener(ipadrs, 5000);

tcplsnr.Start();

while (true)
{
Socket sokt = tcplsnr.AcceptSocket();

Console.WriteLine("Client connected");

list.Add(sokt);

NetworkStream stre = new NetworkStream(sokt);

StreamReader stread = new StreamReader(stre);

StreamWriter strwr = new StreamWriter(stre);

ParameterizedThreadStart pts = new ParameterizedThreadStart(read);

Thread t1 = new Thread(pts);

t1.Start(stread);

}
}

Run function run in new thread. We define it to get the client connected to server. When a client is connected, it is stored in ArrayList, create a new thread fro reading from that client.

StreamReader stread = new StreamReader(stre);

Thread t1 = new Thread(pts);

t1.Start(stread);

—————————————————————————————-

that’s it !

About:

Danish Kamal khan

Computer Science Dept.

G-C-University Lahore Pakistan.

Reading Data from .csv File and Writing into SQL

Introduction

This is a simple programs written in C# which reads data of records from a .csv File, And write these records to a SQL Database accordingly. The CSV (“Comma Separated Value”) file format is often used to exchange data between disparate applications.

Tools: 

1. Visual Studio 2010
2. Microsoft SQL 2008
3. Language: C#

 Background

Sometimes we need to store records while we have to use very limited memory. In that case a .csv file is used to store records and information or in other words called Flat File Database. Its less size feature is very useful when we are transferring this database over network via streams. The record is stored in .csv files as One Record per line and is separated by a specific delimiter (which is “,” in .csv files) to differentiate between columns.

Using the Code

Let’s move through the code

Untitled1

This is a simple piece of code which fetch the records from .csv File separate them on the base of Delimiter(which is “,” in csv files) and the place them in the Data table object which is “dt” using Microsoft Jet OLEDB Adapter.

Now we have all the records of the .csv File into data table each at its respective column and row. It’s time to write these records to Microsoft SQL Server. We already have a Table there  with all the column names.

The attribute FMT =Delimited in the connection string defines the delimiter, the program will automatically identify that it is comma delimited or tab delimited and will separate the record accordingly.

File name from where we want records “Gan_Advertisers.csv”

Untitled2

 

Now we have to write the data which is present in our data table into the SQL Server database, and data is written into the SQL Database until all the rows successfully transferred to the SQL database.

Untitled3

After that data is written in SQL.

Now we have read data from a csv file and wrote it into SQL database.