EventmanagementDataContext db = new EventmanagementDataContext();
var v = from user in db.tblUsers select new {user.Name,user.UserID};
DropDownList1.DataSource = v;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "UserID";
DropDownList1.DataBind();
Tuesday, May 31, 2011
Linq - fetch data from database using linkq
create database "Eventmanagement" in SQL server.
Add table tblUser with fields "username","password","userid"
Add "Linq to SQL class" named "Eventmanagement"
Add table "tbluser" from database "Eventmanagement" to the layout in dbml file created
under app_code folder.
Add a GridView in default page.
Paste the following code in Page Load event
EventmanagementDataContext db = new EventmanagementDataContext();
var v = from user in db.tblUsers select new {user.username, user.password, user.userid};
GridView1.DataSource = v;
GridView1.DataBind();
Add table tblUser with fields "username","password","userid"
Add "Linq to SQL class" named "Eventmanagement"
Add table "tbluser" from database "Eventmanagement" to the layout in dbml file created
under app_code folder.
Add a GridView in default page.
Paste the following code in Page Load event
EventmanagementDataContext db = new EventmanagementDataContext();
var v = from user in db.tblUsers select new {user.username, user.password, user.userid};
GridView1.DataSource = v;
GridView1.DataBind();
Configure Visual Source Safe
1. Install VSS.
2. Configure vss database
3. Create project/website in visual studio.
4. Add to source control by selecting "Add to source control" in right click options.
5. It will create folders in vss database.
6. Check out and check in your files there.
7. If you have your default project folder in "my documents". remove the sln and other files to the project folder you set up.
8. open your sln file and enter with your username and password for vss.
To install the same for client -
1. Map drive the database "srcsafe.ini" file in your vss database folder.
2. Select the same database for your client mnachine.
3. Paste the project in the folder or you can "get latest" the folder from "Microsoft Visual Soursafe" in menu.
Add a new file in client's project and checkin the file.
Get latest your project and get the same file in your solution.
Once you check out the file to modify , client can't do the same at same time, untill you make it done.
2. Configure vss database
3. Create project/website in visual studio.
4. Add to source control by selecting "Add to source control" in right click options.
5. It will create folders in vss database.
6. Check out and check in your files there.
7. If you have your default project folder in "my documents". remove the sln and other files to the project folder you set up.
8. open your sln file and enter with your username and password for vss.
To install the same for client -
1. Map drive the database "srcsafe.ini" file in your vss database folder.
2. Select the same database for your client mnachine.
3. Paste the project in the folder or you can "get latest" the folder from "Microsoft Visual Soursafe" in menu.
Add a new file in client's project and checkin the file.
Get latest your project and get the same file in your solution.
Once you check out the file to modify , client can't do the same at same time, untill you make it done.
Upload File from desktop Application to ftp
My.Computer.Network.UploadFile(OpenFileDialog1.FileName, "ftp://yoursitename.com/www/yourfolder/" + s, "ftpUsername", "ftppassword", True, 4000)
Monday, May 30, 2011
Display video in listview, asp.net c#
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Panel p = new Panel();
p = (Panel)e.Item.FindControl("panv");
Label lbl = new Label();
string str = "";
HiddenField h = new HiddenField();
h = (HiddenField)e.Item.FindControl("hVideoid");
str = " ";
lbl.Text = str;
p.Controls.Clear();
p.Controls.Add(lbl);
}
{
Panel p = new Panel();
p = (Panel)e.Item.FindControl("panv");
Label lbl = new Label();
string str = "";
HiddenField h = new HiddenField();
h = (HiddenField)e.Item.FindControl("hVideoid");
str = " ";
lbl.Text = str;
p.Controls.Clear();
p.Controls.Add(lbl);
}
Upload video in asp.net , c#
private void UploadVideo()
{
if (FileUpload1.HasFile == true)
{
string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowedtypes = new string[] { ".flv" };
if (allowedtypes.Contains(ext))
{
string[] mimetypes = new string[] { "application/x-shockwave-flash", "application/octet-stream", "video/x-flv" };
string filetype = FileUpload1.PostedFile.ContentType;
if (mimetypes.Contains(filetype) == false)
{
// error = "Image is not in the correct format, Please ensure the image is either a JPEG, GIF or PNG";
return;
}
else
{
string filename = Session["StudentID"].ToString() +"_"+ DateTime.Now + ext.ToString();
filename = filename.Replace("/", "").Trim();
filename = filename.Replace(":", "");
filename = filename.Replace(" ", "");
string strpath = "Video/" + filename;
FileUpload1.SaveAs(Server.MapPath("~/forum/Video/") + filename);
}
}
else
{
lblMassage.Text = "Only .FLV format supported";
return;
}
}
else
{
lblMassage.Text = "No file selected.";
return;
}
}
{
if (FileUpload1.HasFile == true)
{
string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowedtypes = new string[] { ".flv" };
if (allowedtypes.Contains(ext))
{
string[] mimetypes = new string[] { "application/x-shockwave-flash", "application/octet-stream", "video/x-flv" };
string filetype = FileUpload1.PostedFile.ContentType;
if (mimetypes.Contains(filetype) == false)
{
// error = "Image is not in the correct format, Please ensure the image is either a JPEG, GIF or PNG";
return;
}
else
{
string filename = Session["StudentID"].ToString() +"_"+ DateTime.Now + ext.ToString();
filename = filename.Replace("/", "").Trim();
filename = filename.Replace(":", "");
filename = filename.Replace(" ", "");
string strpath = "Video/" + filename;
FileUpload1.SaveAs(Server.MapPath("~/forum/Video/") + filename);
}
}
else
{
lblMassage.Text = "Only .FLV format supported";
return;
}
}
else
{
lblMassage.Text = "No file selected.";
return;
}
}
Encrypt & Decrypt
Public Function Encrypt1(ByVal toEncrypt As String, ByVal key As String, ByVal useHashing As Boolean) As String
Dim keyArray As Byte()
Dim toEncryptArray As Byte() = UTF8Encoding.UTF8.GetBytes(toEncrypt)
If useHashing = True Then
Dim hashmd5 As New MD5CryptoServiceProvider()
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
Else
keyArray = UTF8Encoding.UTF8.GetBytes(key)
End If
Dim tdes As New TripleDESCryptoServiceProvider()
tdes.Key = keyArray
tdes.Mode = CipherMode.ECB
tdes.Padding = PaddingMode.PKCS7
Dim cTransform As ICryptoTransform = tdes.CreateEncryptor()
Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
Return (Convert.ToBase64String(resultArray, 0, resultArray.Length))
End Function
Public Function Decrypt1(ByVal toDecrypt As String, ByVal key As String, ByVal useHashing As Boolean) As String
Dim keyArray As Byte()
Dim toEncryptArray As Byte() = Convert.FromBase64String(toDecrypt)
If useHashing = True Then
Dim hashmd5 As New MD5CryptoServiceProvider()
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
Else
keyArray = UTF8Encoding.UTF8.GetBytes(key)
End If
Dim tdes As New TripleDESCryptoServiceProvider()
tdes.Key = keyArray
tdes.Mode = CipherMode.ECB
tdes.Padding = PaddingMode.PKCS7
Dim cTransform As ICryptoTransform = tdes.CreateDecryptor()
Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
Return UTF8Encoding.UTF8.GetString(resultArray)
End Function
Dim keyArray As Byte()
Dim toEncryptArray As Byte() = UTF8Encoding.UTF8.GetBytes(toEncrypt)
If useHashing = True Then
Dim hashmd5 As New MD5CryptoServiceProvider()
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
Else
keyArray = UTF8Encoding.UTF8.GetBytes(key)
End If
Dim tdes As New TripleDESCryptoServiceProvider()
tdes.Key = keyArray
tdes.Mode = CipherMode.ECB
tdes.Padding = PaddingMode.PKCS7
Dim cTransform As ICryptoTransform = tdes.CreateEncryptor()
Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
Return (Convert.ToBase64String(resultArray, 0, resultArray.Length))
End Function
Public Function Decrypt1(ByVal toDecrypt As String, ByVal key As String, ByVal useHashing As Boolean) As String
Dim keyArray As Byte()
Dim toEncryptArray As Byte() = Convert.FromBase64String(toDecrypt)
If useHashing = True Then
Dim hashmd5 As New MD5CryptoServiceProvider()
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key))
Else
keyArray = UTF8Encoding.UTF8.GetBytes(key)
End If
Dim tdes As New TripleDESCryptoServiceProvider()
tdes.Key = keyArray
tdes.Mode = CipherMode.ECB
tdes.Padding = PaddingMode.PKCS7
Dim cTransform As ICryptoTransform = tdes.CreateDecryptor()
Dim resultArray As Byte() = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
Return UTF8Encoding.UTF8.GetString(resultArray)
End Function
get system MAC Address
Imports System.Collections.Generic
Imports System.Text
Imports System.Security.Cryptography
Imports System.Configuration
Imports System.Management
Public Function GetMACAddress() As String
Dim mc As New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As ManagementObjectCollection = mc.GetInstances()
Dim MACAddress As String = [String].Empty
For Each mo As ManagementObject In moc
If MACAddress = [String].Empty Then
' only return MAC Address from first card
If CBool(mo("IPEnabled")) = True Then
MACAddress = mo("MacAddress").ToString()
End If
End If
mo.Dispose()
Next
MACAddress = MACAddress.Replace(":", "")
Return MACAddress
End Function
Imports System.Text
Imports System.Security.Cryptography
Imports System.Configuration
Imports System.Management
Public Function GetMACAddress() As String
Dim mc As New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As ManagementObjectCollection = mc.GetInstances()
Dim MACAddress As String = [String].Empty
For Each mo As ManagementObject In moc
If MACAddress = [String].Empty Then
' only return MAC Address from first card
If CBool(mo("IPEnabled")) = True Then
MACAddress = mo("MacAddress").ToString()
End If
End If
mo.Dispose()
Next
MACAddress = MACAddress.Replace(":", "")
Return MACAddress
End Function
Diffrence between two Date
Private Sub DetermineNumberofDays()
Dim dtStartDate As Date = Convert.ToDateTime(System.DateTime.Now.ToString("MM/dd/yyyy"))
Dim dtEndDate As Date = Convert.ToDateTime(strExpirydate)
Dim tsTimeSpan As TimeSpan
Dim iNumberOfDays As Integer
Dim strMsgText As String
tsTimeSpan = dtEndDate.Subtract(dtStartDate)
iNumberOfDays = tsTimeSpan.Days
strMsgText = "Your trial copy have" & iNumberOfDays.ToString() & "days left."
MsgBox(strMsgText)
End Sub
Dim dtStartDate As Date = Convert.ToDateTime(System.DateTime.Now.ToString("MM/dd/yyyy"))
Dim dtEndDate As Date = Convert.ToDateTime(strExpirydate)
Dim tsTimeSpan As TimeSpan
Dim iNumberOfDays As Integer
Dim strMsgText As String
tsTimeSpan = dtEndDate.Subtract(dtStartDate)
iNumberOfDays = tsTimeSpan.Days
strMsgText = "Your trial copy have" & iNumberOfDays.ToString() & "days left."
MsgBox(strMsgText)
End Sub
Create ,read registry key
Imports System.IO
Imports System.Management
Imports Microsoft.Win32
'==Creating registry sub key and assigned value into them.=====
Dim Activekey As Microsoft.Win32.RegistryKey
Activekey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\Mayabious\key")
Activekey.SetValue("Activated", 0)
'retrive value from specefic regystry key=============
ActivationKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\Mayabious\key")
strActivationKey = ActivationKey.GetValue("ActivationCode").ToString()
strActivationKey = mac.Decrypt1(strActivationKey, "", True)
Imports System.Management
Imports Microsoft.Win32
'==Creating registry sub key and assigned value into them.=====
Dim Activekey As Microsoft.Win32.RegistryKey
Activekey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\Mayabious\key")
Activekey.SetValue("Activated", 0)
'retrive value from specefic regystry key=============
ActivationKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\Mayabious\key")
strActivationKey = ActivationKey.GetValue("ActivationCode").ToString()
strActivationKey = mac.Decrypt1(strActivationKey, "", True)
Thursday, May 26, 2011
Add Row in datatable
din dt as new datatable
Dim dr = dt.NewRow
dr.Item("NAME1") = dt.Rows(i)("NAME").ToString()
dr.Item("DESIGNATION1") = dt.Rows(i)("DESIGNATION").ToString()
dr.Item("COMPANY1") = dt.Rows(i)("COMPANY").ToString()
dr.Item("ADDRESS_11") = dt.Rows(i)("ADDRESS_1").ToString()
dr.Item("CITY1") = dt.Rows(i)("CITY").ToString()
dr.Item("PINCODE1") = dt.Rows(i)("PINCODE").ToString()
dr.Item("PHONE1") = dt.Rows(i)("PHONE").ToString()
dr.Item("MOBILE1") = dt.Rows(i)("MOBILE").ToString()
dr.Item("EMAIL1") = dt.Rows(i)("EMAIL").ToString()
dt.Rows.Add(dr)
Dim dr = dt.NewRow
dr.Item("NAME1") = dt.Rows(i)("NAME").ToString()
dr.Item("DESIGNATION1") = dt.Rows(i)("DESIGNATION").ToString()
dr.Item("COMPANY1") = dt.Rows(i)("COMPANY").ToString()
dr.Item("ADDRESS_11") = dt.Rows(i)("ADDRESS_1").ToString()
dr.Item("CITY1") = dt.Rows(i)("CITY").ToString()
dr.Item("PINCODE1") = dt.Rows(i)("PINCODE").ToString()
dr.Item("PHONE1") = dt.Rows(i)("PHONE").ToString()
dr.Item("MOBILE1") = dt.Rows(i)("MOBILE").ToString()
dr.Item("EMAIL1") = dt.Rows(i)("EMAIL").ToString()
dt.Rows.Add(dr)
Add CheckBox Column to datagridview
Private Sub AddCheckBox(ByVal pos As Integer, ByRef grd As DataGridView)
'grd.Columns.Clear()
'grd.Rows.Clear()
Dim column As New DataGridViewCheckBoxColumn()
With column
.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
.FlatStyle = FlatStyle.Standard
.CellTemplate = New DataGridViewCheckBoxCell()
.CellTemplate.Style.BackColor = Color.Beige
.Name = "c_" + pos.ToString()
End With
grd.Columns.Insert(pos, column)
End Sub
'grd.Columns.Clear()
'grd.Rows.Clear()
Dim column As New DataGridViewCheckBoxColumn()
With column
.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
.FlatStyle = FlatStyle.Standard
.CellTemplate = New DataGridViewCheckBoxCell()
.CellTemplate.Style.BackColor = Color.Beige
.Name = "c_" + pos.ToString()
End With
grd.Columns.Insert(pos, column)
End Sub
Wednesday, May 25, 2011
Arrange Arraylist integer items ascending & descending.
For ascending order
arraylist.Sort()
For descending order
arrRowId.Sort()
arrRowId.Reverse()
arraylist.Sort()
For descending order
arrRowId.Sort()
arrRowId.Reverse()
Delete file by extention
For Each filename As String In IO.Directory.GetFiles(Path.GetTempPath.ToString(), "*.bin")
IO.File.Delete(filename)
Next
IO.File.Delete(filename)
Next
C#
string fileLoc = @"c:\sample1.txt";
VB.NET
Dim fileLoc As String = "c:\sample1.txt"
You would also need to reference the System.IO namespace in your project.
Create a Text File
C#
// Create a Text File
private void btnCreate_Click(object sender, EventArgs e)
{
FileStream fs = null;
if (!File.Exists(fileLoc))
{
using (fs = File.Create(fileLoc))
{
}
}
}
VB.NET
' Create a Text File
Private Sub btnCreate_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
fs = File.Create(fileLoc)
Using fs
End Using
End If
End Sub
Write to a Text File
C#
// Write to a Text File
private void btnWrite_Click(object sender, EventArgs e)
{
if (File.Exists(fileLoc))
{
using (StreamWriter sw = new StreamWriter(fileLoc))
{
sw.Write("Some sample text for the file");
}
}
}
VB.NET
' Write to a Text File
Private Sub btnWrite_Click(ByVal sender As Object, ByVal e As EventArgs)
If File.Exists(fileLoc) Then
Using sw As StreamWriter = New StreamWriter(fileLoc)
sw.Write("Some sample text for the file")
End Using
End If
End Sub
Read From a Text File
C#
// Read From a Text File
private void btnRead_Click(object sender, EventArgs e)
{
if (File.Exists(fileLoc))
{
using (TextReader tr = new StreamReader(fileLoc))
{
MessageBox.Show(tr.ReadLine());
}
}
}
VB.NET
' Read From a Text File
Private Sub btnRead_Click(ByVal sender As Object, ByVal e As EventArgs)
If File.Exists(fileLoc) Then
Using tr As TextReader = New StreamReader(fileLoc)
MessageBox.Show(tr.ReadLine())
End Using
End If
End Sub
Copy a Text File
C#
// Copy a Text File
private void btnCopy_Click(object sender, EventArgs e)
{
string fileLocCopy = @"d:\sample1.txt";
if (File.Exists(fileLoc))
{
// If file already exists in destination, delete it.
if (File.Exists(fileLocCopy))
File.Delete(fileLocCopy);
File.Copy(fileLoc, fileLocCopy);
}
}
VB.NET
' Copy a Text File
Private Sub btnCopy_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileLocCopy As String = "d:\sample1.txt"
If File.Exists(fileLoc) Then
' If file already exists in destination, delete it.
If File.Exists(fileLocCopy) Then
File.Delete(fileLocCopy)
End If
File.Copy(fileLoc, fileLocCopy)
End If
End Sub
Move a Text File
C#
// Move a Text file
private void btnMove_Click(object sender, EventArgs e)
{
// Create unique file name
string fileLocMove = @"d:\sample1" + System.DateTime.Now.Ticks + ".txt";
if (File.Exists(fileLoc))
{
File.Move(fileLoc, fileLocMove);
}
}
VB.NET
' Move a Text file
Private Sub btnMove_Click(ByVal sender As Object, ByVal e As EventArgs)
' Create unique file name
Dim fileLocMove As String = "d:\sample1" & System.DateTime.Now.Ticks & ".txt"
If File.Exists(fileLoc) Then
File.Move(fileLoc, fileLocMove)
End If
End Sub
Delete a Text File
C#
// Delete a text file
private void btnDelete_Click(object sender, EventArgs e)
{
if (File.Exists(fileLoc))
{
File.Delete(fileLoc);
}
}
VB.NET
' Delete a text file
Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
If File.Exists(fileLoc) Then
File.Delete(fileLoc)
End If
End Sub
We saw how to achieve some of the most common requirements while dealing with text files. Take a look at these reference links below to get a detailed understanding of the File and FileInfo class.
Tuesday, May 24, 2011
Connect Asp.net with mySQL and Execute Storeprocedure
1. Download MySQL Connector Net 5.1.7 from http://dev.mysql.com/downloads/connector/net/5.1.html
2.Install .
3. Add MySql.Data.dll into bin folder from C:\Program Files\MySQL\MySQL Connector Net 5.1.7\Binaries\.NET 2.0
4.================CLASS FOR EXECUTE STORE PROCEDURE==================
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports MySql.Data.MySqlClient
Imports MySql.Data
Imports System.Data.Odbc
Imports System.Configuration
Imports System.ComponentModel
Public Class Exec_SP_MSQL
Dim connectionstring As String = ConfigurationManager.ConnectionStrings("demo").ConnectionString.ToString()
Dim con As New MySqlConnection(connectionstring)
Public Sub OpenConnection()
con.Open()
End Sub
Public Sub CloseConnection()
con.Close()
End Sub
Public Function ExecuteSPWithReturnDataTable(ByVal spName As [String], ByVal ParamArray CommandParameter As MySqlClient.MySqlParameter()) As DataTable
Dim tmpDataTable As New DataTable()
'try
'{
Me.OpenConnection()
Dim OdbcCommand As New MySqlCommand()
Me.PrepareCommand(OdbcCommand, Nothing, spName, CommandParameter)
'this.PrepareCommand(OdbcCommand, null, spName, CommandParameter);
Dim OdbcDataAdapter As New MySqlDataAdapter(OdbcCommand)
OdbcDataAdapter.Fill(tmpDataTable).ToString()
Me.CloseConnection()
'}
'catch (Exception exception1)
'{
' //(exception1.Message);
'}
'Catch exception2 As Exception
' Throw New Exception(exception2.Message)
'End Try
Return tmpDataTable
End Function
Private Sub PrepareCommand(ByVal command As MySqlCommand, ByVal transaction As MySqlTransaction, ByVal commandText As String, ByVal commandParameters As MySqlParameter())
'this.PrepareCommand(command1, null, spName, commandParameters);
command.Connection = Me.con
command.CommandText = commandText
If transaction IsNot Nothing Then
command.Transaction = transaction
End If
command.CommandType = CommandType.StoredProcedure
If commandParameters IsNot Nothing Then
Me.AttachParameters(command, commandParameters)
End If
End Sub
Private Sub AttachParameters(ByVal command As MySqlCommand, ByVal commandParameters As MySqlParameter())
For Each parameter1 As MySqlParameter In commandParameters
If (parameter1.Direction = ParameterDirection.InputOutput) AndAlso (parameter1.Value Is Nothing) Then
parameter1.Value = DBNull.Value
End If
command.Parameters.Add(parameter1)
Next
End Sub
End Class
====================================================================
Add this class into App_Code Folder
5.Add class for each table in which you want to rur procedure
====================================================================
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Odbc
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class tblUse
Public Function Dotask(ByVal strFlag As String, ByVal iID As Integer, ByVal strUsername As String, ByVal strPassword As String) As DataTable
Dim _Exec_SP_MSQL As New Exec_SP_MSQL
Dim dt As New DataTable
Dim db As New DBManager.CDataAccess
Dim pFlag As New MySqlParameter("pFlag", MySqlDbType.VarChar)
Dim pID As New MySqlParameter("pID", MySqlDbType.Int32)
Dim pName As New MySqlParameter("pName", MySqlDbType.VarChar)
Dim pPassword As New MySqlParameter("pPassword", MySqlDbType.VarChar)
pFlag.Value = strFlag
pID.Value = iID
pName.Value = strUsername
pPassword.Value = strPassword
dt = _Exec_SP_MSQL.ExecuteSPWithReturnDataTable("spuser", pFlag, pID, pName, pPassword)
Return dt
End Function
End Class
====================================================================
6.How to write Store procedure with Flag in MySQL
Install MySQL 5.6.1
Install Navicat
====================================================================
begin
IF pFlag = "a" THEN
select * from tbluser where Name=pName and Password=pPassword ;
END IF;
IF pFlag = "" THEN
select * from tbluser ;
END IF;
END
===================================================================
2.Install .
3. Add MySql.Data.dll into bin folder from C:\Program Files\MySQL\MySQL Connector Net 5.1.7\Binaries\.NET 2.0
4.================CLASS FOR EXECUTE STORE PROCEDURE==================
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports MySql.Data.MySqlClient
Imports MySql.Data
Imports System.Data.Odbc
Imports System.Configuration
Imports System.ComponentModel
Public Class Exec_SP_MSQL
Dim connectionstring As String = ConfigurationManager.ConnectionStrings("demo").ConnectionString.ToString()
Dim con As New MySqlConnection(connectionstring)
Public Sub OpenConnection()
con.Open()
End Sub
Public Sub CloseConnection()
con.Close()
End Sub
Public Function ExecuteSPWithReturnDataTable(ByVal spName As [String], ByVal ParamArray CommandParameter As MySqlClient.MySqlParameter()) As DataTable
Dim tmpDataTable As New DataTable()
'try
'{
Me.OpenConnection()
Dim OdbcCommand As New MySqlCommand()
Me.PrepareCommand(OdbcCommand, Nothing, spName, CommandParameter)
'this.PrepareCommand(OdbcCommand, null, spName, CommandParameter);
Dim OdbcDataAdapter As New MySqlDataAdapter(OdbcCommand)
OdbcDataAdapter.Fill(tmpDataTable).ToString()
Me.CloseConnection()
'}
'catch (Exception exception1)
'{
' //(exception1.Message);
'}
'Catch exception2 As Exception
' Throw New Exception(exception2.Message)
'End Try
Return tmpDataTable
End Function
Private Sub PrepareCommand(ByVal command As MySqlCommand, ByVal transaction As MySqlTransaction, ByVal commandText As String, ByVal commandParameters As MySqlParameter())
'this.PrepareCommand(command1, null, spName, commandParameters);
command.Connection = Me.con
command.CommandText = commandText
If transaction IsNot Nothing Then
command.Transaction = transaction
End If
command.CommandType = CommandType.StoredProcedure
If commandParameters IsNot Nothing Then
Me.AttachParameters(command, commandParameters)
End If
End Sub
Private Sub AttachParameters(ByVal command As MySqlCommand, ByVal commandParameters As MySqlParameter())
For Each parameter1 As MySqlParameter In commandParameters
If (parameter1.Direction = ParameterDirection.InputOutput) AndAlso (parameter1.Value Is Nothing) Then
parameter1.Value = DBNull.Value
End If
command.Parameters.Add(parameter1)
Next
End Sub
End Class
====================================================================
Add this class into App_Code Folder
5.Add class for each table in which you want to rur procedure
====================================================================
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Odbc
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class tblUse
Public Function Dotask(ByVal strFlag As String, ByVal iID As Integer, ByVal strUsername As String, ByVal strPassword As String) As DataTable
Dim _Exec_SP_MSQL As New Exec_SP_MSQL
Dim dt As New DataTable
Dim db As New DBManager.CDataAccess
Dim pFlag As New MySqlParameter("pFlag", MySqlDbType.VarChar)
Dim pID As New MySqlParameter("pID", MySqlDbType.Int32)
Dim pName As New MySqlParameter("pName", MySqlDbType.VarChar)
Dim pPassword As New MySqlParameter("pPassword", MySqlDbType.VarChar)
pFlag.Value = strFlag
pID.Value = iID
pName.Value = strUsername
pPassword.Value = strPassword
dt = _Exec_SP_MSQL.ExecuteSPWithReturnDataTable("spuser", pFlag, pID, pName, pPassword)
Return dt
End Function
End Class
====================================================================
6.How to write Store procedure with Flag in MySQL
Install MySQL 5.6.1
Install Navicat
====================================================================
begin
IF pFlag = "a" THEN
select * from tbluser where Name=pName and Password=pPassword ;
END IF;
IF pFlag = "" THEN
select * from tbluser ;
END IF;
END
===================================================================
Check email in Vb.net desktop application
Imports System.Text.RegularExpressions
Public Function IsEmail(ByVal str As String) As Boolean
If (str = Nothing) Then
Return False
ElseIf (str = "") Then
Return False
Else
Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
Dim emailAddressMatch As Match = Regex.Match(str, pattern)
If emailAddressMatch.Success Then
Return True
Else
Return False
End If
End If
End Function
Public Function IsEmail(ByVal str As String) As Boolean
If (str = Nothing) Then
Return False
ElseIf (str = "") Then
Return False
Else
Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
Dim emailAddressMatch As Match = Regex.Match(str, pattern)
If emailAddressMatch.Success Then
Return True
Else
Return False
End If
End If
End Function
Exporting Text Into Excel
Imports Excel = Microsoft.Office.Interop.Excel
Public Sub ExportToExcel(ByVal objDT As DataTable)
Dim Excel As Object = CreateObject("Excel.Application")
Dim strFilename As String
Dim intCol, intRow As Integer
Dim strPath As String = "c:\"
If Excel Is Nothing Then
MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
Return
End If
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
'.cells(1, 1).value = "Heading" 'Heading of the excel file
.cells(1, 1).EntireRow.Font.Bold = True
Dim intI As Integer = 1
For intCol = 0 To objDT.Columns.Count - 1
.cells(2, intI).value = objDT.Columns(intCol).ColumnName
.cells(2, intI).EntireRow.Font.Bold = True
intI += 1
Next
intI = 3
Dim intK As Integer = 1
For intCol = 0 To objDT.Columns.Count - 1
intI = 3
For intRow = 0 To objDT.Rows.Count - 1
.Cells(intI, intK).Value = objDT.Rows(intRow).ItemArray(intCol)
intI += 1
Next
intK += 1
Next
If Mid$(strPath, strPath.Length, 1) <> "\" Then
strPath = strPath & "\"
End If
Dim filename As String = System.DateTime.Now.ToString("MM/dd/yyyy")
filename = filename.Replace("/", "_") & System.DateTime.Now.Millisecond.ToString()
strFilename = strPath & filename
.ActiveCell.Worksheet.SaveAs(strFilename)
End With
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Excel = Nothing
MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message)
End Try
' The excel is created and opened for insert value. We most close this excel using this system
Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each i As Process In pro
i.Kill()
Next
End Sub
Public Sub ExportToExcel(ByVal objDT As DataTable)
Dim Excel As Object = CreateObject("Excel.Application")
Dim strFilename As String
Dim intCol, intRow As Integer
Dim strPath As String = "c:\"
If Excel Is Nothing Then
MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
Return
End If
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
'.cells(1, 1).value = "Heading" 'Heading of the excel file
.cells(1, 1).EntireRow.Font.Bold = True
Dim intI As Integer = 1
For intCol = 0 To objDT.Columns.Count - 1
.cells(2, intI).value = objDT.Columns(intCol).ColumnName
.cells(2, intI).EntireRow.Font.Bold = True
intI += 1
Next
intI = 3
Dim intK As Integer = 1
For intCol = 0 To objDT.Columns.Count - 1
intI = 3
For intRow = 0 To objDT.Rows.Count - 1
.Cells(intI, intK).Value = objDT.Rows(intRow).ItemArray(intCol)
intI += 1
Next
intK += 1
Next
If Mid$(strPath, strPath.Length, 1) <> "\" Then
strPath = strPath & "\"
End If
Dim filename As String = System.DateTime.Now.ToString("MM/dd/yyyy")
filename = filename.Replace("/", "_") & System.DateTime.Now.Millisecond.ToString()
strFilename = strPath & filename
.ActiveCell.Worksheet.SaveAs(strFilename)
End With
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Excel = Nothing
MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message)
End Try
' The excel is created and opened for insert value. We most close this excel using this system
Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each i As Process In pro
i.Kill()
Next
End Sub
Union two diffrent Datatable In vb.net
Public Function mergeDTs(ByVal dt1 As DataTable, ByVal dt2 As DataTable) As DataTable
'dt1.Columns.Add("ContactID")
Dim dtResult As DataTable = dt1.Clone()
Dim ds As New DataSet
For Each dr As DataRow In dt1.Rows
dtResult.Rows.Add(dr.ItemArray)
Next
For Each dr As DataRow In dt2.Rows
dtResult.Rows.Add(dr.ItemArray)
'dtResult.Columns.Add("ContactID")
Next
Dim dtFinalResult As New DataTable
Return dtResult
End Function
'dt1.Columns.Add("ContactID")
Dim dtResult As DataTable = dt1.Clone()
Dim ds As New DataSet
For Each dr As DataRow In dt1.Rows
dtResult.Rows.Add(dr.ItemArray)
Next
For Each dr As DataRow In dt2.Rows
dtResult.Rows.Add(dr.ItemArray)
'dtResult.Columns.Add("ContactID")
Next
Dim dtFinalResult As New DataTable
Return dtResult
End Function
Grid Populate in vb.net
Private Sub GridDisplay()
Dim dt As New DataTable()
dt = db.GetDatatable(" select * from tblCandidate ")
grdCandidateList.Columns.Clear()
grdCandidateList.DataSource = dt
End Sub
Dim dt As New DataTable()
dt = db.GetDatatable(" select * from tblCandidate ")
grdCandidateList.Columns.Clear()
grdCandidateList.DataSource = dt
End Sub
Simple Combo populate , not from database in vb.net
Dim dt As New DataTable()
dt.Columns.Add("ID")
dt.Columns.Add("Val")
dt.Rows.Add("1", "Yes")
dt.Rows.Add("0", "No")
cmbpChallenged.DataSource = dt
cmbpChallenged.ValueMember = "ID"
cmbpChallenged.DisplayMember = "Val"
cmbpChallenged is my combo here .
dt.Columns.Add("ID")
dt.Columns.Add("Val")
dt.Rows.Add("1", "Yes")
dt.Rows.Add("0", "No")
cmbpChallenged.DataSource = dt
cmbpChallenged.ValueMember = "ID"
cmbpChallenged.DisplayMember = "Val"
cmbpChallenged is my combo here .
Read Content from notepad in vb.net
Place your text file under bin/debug for the following , otherwise you can place the text box any where and set the path.
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader
Dim EntireFile As String
oRead = IO.File.OpenText(Application.StartupPath() + "/test.txt")
EntireFile = oRead.ReadToEnd()
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader
Dim EntireFile As String
oRead = IO.File.OpenText(Application.StartupPath() + "/test.txt")
EntireFile = oRead.ReadToEnd()
Subscribe to:
Posts (Atom)