Two types of configuration files supported by ASP.Net.
Configuration files are used to control and manage the behavior of a web application.
i) Machine.config
ii)Web.config
Difference between Machine.Config and Web.Config
Machine.Config:
i) This is automatically installed when you install Visual Studio. Net.
ii) This is also called machine level configuration file.
iii)Only one machine.config file exists on a server.
iv) This file is at the highest level in the configuration hierarchy.
Web.Config:
i) This is automatically created when you create an ASP.Net web application project.
ii) This is also called application level configuration file.
iii)This file inherits setting from the machine.config
ASP.NET MVC, C#, MS SQL Server, EF, MySql Server, Linq, Jquery, Java Script, Interview Questions. If you are looking for updates than kindly subscribe with this blog.
Sunday, September 25, 2011
Friday, September 9, 2011
Restricting access to page or directory in ASP.NET
You have to use Forms Authentication.
http://support.microsoft.com/kb/301240
How to subtract 1 from a orginal count in an ASP.NET gridview
I have a gridview that contains a count (whic is Quantity) were i have a button that adds a row under the orginal row and i need the sub row's count (Quantity) to subtract one from the orgianl row Quantity.
EX: Before button click
Orgianl row = 3
After click
Orginal row = 2
Subrow = 1
Code:
ASP.NET
// FUNCTION : Adds a new subrow
protected void gvParent_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("btn_AddRow", StringComparison.OrdinalIgnoreCase))
{
// Get the row that was clicked (index 0. Meaning that 0 is 1, 1 is 2 and so on)
// Objects can be null, Int32s cannot not.
// Int16 = 2 bytes long (short)
// Int32 = 4 bytes long (int)
// Int64 = 8 bytes long (long)
int i = Convert.ToInt32(e.CommandArgument);
// create a DataTable based off the view state
DataTable dataTable = (DataTable)ViewState["gvParent"];
for (int part = 0; part < dataTable.Rows.Count; part++) { int oldQuantity = Convert.ToInt32(dataTable.Rows[i]["Quantity"]); string partNumber = dataTable.Rows[i]["ProductDescription"].ToString(); string description = dataTable.Rows[i]["Description"].ToString(); string dateOrdered = dataTable.Rows[i]["GTRI_DateSubmittedtoPurchasing"].ToString(); string estShipDate = dataTable.Rows[i]["Gtri_EstShipDate"].ToString(); string actualShipDate = dataTable.Rows[i]["Gtri_ActualShipDate"].ToString(); string trackingNumb = dataTable.Rows[i]["GTRI_TrackingNumbers"].ToString(); string serialNumb = dataTable.Rows[i]["Gtri_SerialNumber"].ToString(); int oldQuantitySubtract = Convert.ToInt32(dataTable.Rows[part]["Quantity"]); string curentPartNumbers = dataTable.Rows[part]["ProductDescription"].ToString(); string currentDescription = dataTable.Rows[part]["Description"].ToString(); string currentDateOrdered = dataTable.Rows[part]["GTRI_DateSubmittedtoPurchasing"].ToString(); string currentEstShipDate = dataTable.Rows[part]["Gtri_EstShipDate"].ToString(); string currentActualShipDate = dataTable.Rows[part]["Gtri_ActualShipDate"].ToString(); string currentTrackingNumb = dataTable.Rows[part]["GTRI_TrackingNumbers"].ToString(); string currentSerialNumb = dataTable.Rows[part]["Gtri_SerialNumber"].ToString(); if (partNumber.Equals(curentPartNumbers, StringComparison.OrdinalIgnoreCase) && oldQuantitySubtract > 1)
{
dataTable.Rows[part]["Quantity"] = oldQuantitySubtract - 1;
// Instert a new row at a specific index
DataRow dtAdd = dataTable.NewRow();
for (int k = 0; k < dataTable.Columns.Count; k++)
dtAdd[k] = dataTable.Rows[part][k];
dataTable.Rows.InsertAt(dtAdd, i + 1);
break;
//dataTable.Rows.Add(dtAdd);
}
}
// Rebind the data
gvParent.DataSource = dataTable;
gvParent.DataBind();
}
}
EX: Before button click
Orgianl row = 3
After click
Orginal row = 2
Subrow = 1
Code:
ASP.NET
// FUNCTION : Adds a new subrow
protected void gvParent_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("btn_AddRow", StringComparison.OrdinalIgnoreCase))
{
// Get the row that was clicked (index 0. Meaning that 0 is 1, 1 is 2 and so on)
// Objects can be null, Int32s cannot not.
// Int16 = 2 bytes long (short)
// Int32 = 4 bytes long (int)
// Int64 = 8 bytes long (long)
int i = Convert.ToInt32(e.CommandArgument);
// create a DataTable based off the view state
DataTable dataTable = (DataTable)ViewState["gvParent"];
for (int part = 0; part < dataTable.Rows.Count; part++) { int oldQuantity = Convert.ToInt32(dataTable.Rows[i]["Quantity"]); string partNumber = dataTable.Rows[i]["ProductDescription"].ToString(); string description = dataTable.Rows[i]["Description"].ToString(); string dateOrdered = dataTable.Rows[i]["GTRI_DateSubmittedtoPurchasing"].ToString(); string estShipDate = dataTable.Rows[i]["Gtri_EstShipDate"].ToString(); string actualShipDate = dataTable.Rows[i]["Gtri_ActualShipDate"].ToString(); string trackingNumb = dataTable.Rows[i]["GTRI_TrackingNumbers"].ToString(); string serialNumb = dataTable.Rows[i]["Gtri_SerialNumber"].ToString(); int oldQuantitySubtract = Convert.ToInt32(dataTable.Rows[part]["Quantity"]); string curentPartNumbers = dataTable.Rows[part]["ProductDescription"].ToString(); string currentDescription = dataTable.Rows[part]["Description"].ToString(); string currentDateOrdered = dataTable.Rows[part]["GTRI_DateSubmittedtoPurchasing"].ToString(); string currentEstShipDate = dataTable.Rows[part]["Gtri_EstShipDate"].ToString(); string currentActualShipDate = dataTable.Rows[part]["Gtri_ActualShipDate"].ToString(); string currentTrackingNumb = dataTable.Rows[part]["GTRI_TrackingNumbers"].ToString(); string currentSerialNumb = dataTable.Rows[part]["Gtri_SerialNumber"].ToString(); if (partNumber.Equals(curentPartNumbers, StringComparison.OrdinalIgnoreCase) && oldQuantitySubtract > 1)
{
dataTable.Rows[part]["Quantity"] = oldQuantitySubtract - 1;
// Instert a new row at a specific index
DataRow dtAdd = dataTable.NewRow();
for (int k = 0; k < dataTable.Columns.Count; k++)
dtAdd[k] = dataTable.Rows[part][k];
dataTable.Rows.InsertAt(dtAdd, i + 1);
break;
//dataTable.Rows.Add(dtAdd);
}
}
// Rebind the data
gvParent.DataSource = dataTable;
gvParent.DataBind();
}
}
What are "Expression Trees" in C# ?
URL explains Expression Trees with examples in C# and VB.
http://msdn.microsoft.com/en-us/library/bb397951.aspx
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications
http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx
As per above article I follow the steps to integrate WebApp with MVC application. I am successfully integrated MVC project into WebApp(C#) and also VB.NET MVC and VB.NET WebApp also I am able to successfully integrated.
The problem is If I choose WebApp as VB.NET project, and integrated with C# MVC project. In this case the request is not routing to corresponding MVC files.
What could be the reason not routing to MVC. Do we need to plug some extra dlls?
As per above article I follow the steps to integrate WebApp with MVC application. I am successfully integrated MVC project into WebApp(C#) and also VB.NET MVC and VB.NET WebApp also I am able to successfully integrated.
The problem is If I choose WebApp as VB.NET project, and integrated with C# MVC project. In this case the request is not routing to corresponding MVC files.
What could be the reason not routing to MVC. Do we need to plug some extra dlls?
How to access values of dynamically created TextBoxes
If one adds controls dynamically to a page and wants to get their information after PostBack, one needs to recreate these elements after the PostBack. Let's consider the following idea: First you create some controls:
for(int i=0;i<10;i++) {
TextBox objBox = new TextBox();
objBox.ID = "objBox" + i.ToString();
this.Page.Controls.Add(objBox);
}
After PostBack, you want to retrieve the text entered in the third TextBox. If you try this:
String strText = objBox2.Text;
you'll receive an exception. Why? Because the boxes have not been created again and the local variable objBox2 simply not exists.
How to retrieve the Box?
You'll need to recreate the box by using the code above. Then, you may try to get its value by using the following code:
TextBox objBox2;
objBox2 = this.Page.FindControl("objBox2") as TextBox;
if(objBox2 != null)
Response.Write(objBox2.Text);
for(int i=0;i<10;i++) {
TextBox objBox = new TextBox();
objBox.ID = "objBox" + i.ToString();
this.Page.Controls.Add(objBox);
}
After PostBack, you want to retrieve the text entered in the third TextBox. If you try this:
String strText = objBox2.Text;
you'll receive an exception. Why? Because the boxes have not been created again and the local variable objBox2 simply not exists.
How to retrieve the Box?
You'll need to recreate the box by using the code above. Then, you may try to get its value by using the following code:
TextBox objBox2;
objBox2 = this.Page.FindControl("objBox2") as TextBox;
if(objBox2 != null)
Response.Write(objBox2.Text);
Sunday, July 10, 2011
SQL Server 2008 Designer Behavior Change: Saving Changes Not Permitted
Warning Message:
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
This is by design and can be quickly fixed in Management Studio by unchecking a property. To fix this in Management Studio, go to Tools -> Options then go to the Designer Page and uncheck "Prevent saving changes that require table re-creation"
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
This is by design and can be quickly fixed in Management Studio by unchecking a property. To fix this in Management Studio, go to Tools -> Options then go to the Designer Page and uncheck "Prevent saving changes that require table re-creation"
Sunday, June 19, 2011
C# - How to detect all IP addresses from a LAN?
string strHostName = string.Empty;
cmbIPAddress.Items.Clear();
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] iparrAddr = ipEntry.AddressList;
if (iparrAddr.Length > 0)
{
for (int intLoop = 0; intLoop < iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());
}
cmbIPAddress.Items.Clear();
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] iparrAddr = ipEntry.AddressList;
if (iparrAddr.Length > 0)
{
for (int intLoop = 0; intLoop < iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());
}
Tuesday, May 24, 2011
Difference between Detach/Attach and Restore/BackUp a DB
Transact-SQL BACKUP/RESTORE is the normal method for database backup and
recovery. Databases can be backed up while online. The backup file size is
usually smaller than the database files since only used pages are backed up.
Also, in the FULL or BULK_LOGGED recovery model, you can reduce potential
data loss by performing transaction log backups.
Detaching a database removes the database from SQL Server while leaving the
physical database files intact. This allows you to rename or move the
physical files and then re-attach. Although one could perform cold backups
using this technique, detach/attach isn't really intended to be used as a
backup/recovery process.
Commonly it is recommended that you use BACKUP/RESTORE for disaster recovery (DR) scenario and copying data from one location to another. But this is not absolute, sometimes for a very large database, if you want to move it from one location to another, backup/restore process may spend a lot of time which you do not like, in this case, detaching/attaching a database is a better way since you can attach a workable database very fast. But you need to aware that detaching a database will bring it offline for a short time and detaching/attaching does not provide DR function.
For more information about detaching and attaching databases, you can refer to:
Detaching and Attaching Databases
http://technet.microsoft.com/en-us/library/ms190794.aspx
recovery. Databases can be backed up while online. The backup file size is
usually smaller than the database files since only used pages are backed up.
Also, in the FULL or BULK_LOGGED recovery model, you can reduce potential
data loss by performing transaction log backups.
Detaching a database removes the database from SQL Server while leaving the
physical database files intact. This allows you to rename or move the
physical files and then re-attach. Although one could perform cold backups
using this technique, detach/attach isn't really intended to be used as a
backup/recovery process.
Commonly it is recommended that you use BACKUP/RESTORE for disaster recovery (DR) scenario and copying data from one location to another. But this is not absolute, sometimes for a very large database, if you want to move it from one location to another, backup/restore process may spend a lot of time which you do not like, in this case, detaching/attaching a database is a better way since you can attach a workable database very fast. But you need to aware that detaching a database will bring it offline for a short time and detaching/attaching does not provide DR function.
For more information about detaching and attaching databases, you can refer to:
Detaching and Attaching Databases
http://technet.microsoft.com/en-us/library/ms190794.aspx
Wednesday, May 18, 2011
How To Get Web Site Thumbnail Image In ASP.NET
Overview
One very common requirement of many web applications is to display a thumbnail image of a web site. A typical example is to provide a link to a dynamic website displaying its current thumbnail image, or displaying images of websites with their links as a result of search (I love to see it on Google). Microsoft .NET Framework 2.0 makes it quite easier to do it in a ASP.NET application.
Background
In order to generate image of a web page, first we need to load the web page to get their html code, and then this html needs to be rendered in a web browser. After that, a screen shot can be taken easily. I think there is no easier way to do this. Before .NET framework 2.0 it was quite difficult to use a web browser in C# or VB.NET because we either have to use COM+ interoperability or third party controls which becomes headache later.
WebBrowser control in .NET framework 2.0
In .NET framework 2.0 we have a new Windows Forms WebBrowser control which is a wrapper around old shwdoc.dll. All you really need to do is to drop a WebBrowser control from your Toolbox on your form in .NET framework 2.0.
If you have not used WebBrowser control yet, it's quite easy to use and very consistent with other Windows Forms controls. Some important methods of WebBrowser control are.
public bool GoBack();
public bool GoForward();
public void GoHome();
public void GoSearch();
public void Navigate(Uri url);
public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);
These methods are self explanatory with their names like Navigate function which redirects browser to provided URL. It also has a number of useful overloads. The DrawToBitmap (inherited from Control) draws the current image of WebBrowser to the provided bitmap.
Using WebBrowser control in ASP.NET 2.0
The Solution
Let's start to implement the solution which we discussed above. First we will define a static method to get the web site thumbnail image.
public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
return thumbnailGenerator.GenerateWebSiteThumbnailImage();
}
The WebsiteThumbnailImage class will have a public method named GenerateWebSiteThumbnailImage which will generate the website thumbnail image in a separate STA thread and wait for the thread to exit. In this case, I decided to Join method of Thread class to block the initial calling thread until the bitmap is actually available, and then return the generated web site thumbnail.
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
The _GenerateWebSiteThumbnailImage will create a WebBrowser control object and navigate to the provided Url. We also register for the DocumentCompleted event of the web browser control to take screen shot of the web page. To pass the flow to the other controls we need to perform a method call to Application.DoEvents(); and wait for the completion of the navigation until the browser state changes to Complete in a loop.
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocument
CompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
The DocumentCompleted event will be fired when the navigation is completed and the browser is ready for screen shot. We will get screen shot using DrawToBitmap method as described previously which will return the bitmap of the web browser. Then the thumbnail image is generated using GetThumbnailImage method of Bitmap class passing it the required thumbnail image width and height.
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
One more example here : http://www.codeproject.com/KB/aspnet/Website_URL_Screenshot.aspx
One very common requirement of many web applications is to display a thumbnail image of a web site. A typical example is to provide a link to a dynamic website displaying its current thumbnail image, or displaying images of websites with their links as a result of search (I love to see it on Google). Microsoft .NET Framework 2.0 makes it quite easier to do it in a ASP.NET application.
Background
In order to generate image of a web page, first we need to load the web page to get their html code, and then this html needs to be rendered in a web browser. After that, a screen shot can be taken easily. I think there is no easier way to do this. Before .NET framework 2.0 it was quite difficult to use a web browser in C# or VB.NET because we either have to use COM+ interoperability or third party controls which becomes headache later.
WebBrowser control in .NET framework 2.0
In .NET framework 2.0 we have a new Windows Forms WebBrowser control which is a wrapper around old shwdoc.dll. All you really need to do is to drop a WebBrowser control from your Toolbox on your form in .NET framework 2.0.
If you have not used WebBrowser control yet, it's quite easy to use and very consistent with other Windows Forms controls. Some important methods of WebBrowser control are.
public bool GoBack();
public bool GoForward();
public void GoHome();
public void GoSearch();
public void Navigate(Uri url);
public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);
These methods are self explanatory with their names like Navigate function which redirects browser to provided URL. It also has a number of useful overloads. The DrawToBitmap (inherited from Control) draws the current image of WebBrowser to the provided bitmap.
Using WebBrowser control in ASP.NET 2.0
The Solution
Let's start to implement the solution which we discussed above. First we will define a static method to get the web site thumbnail image.
public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
return thumbnailGenerator.GenerateWebSiteThumbnailImage();
}
The WebsiteThumbnailImage class will have a public method named GenerateWebSiteThumbnailImage which will generate the website thumbnail image in a separate STA thread and wait for the thread to exit. In this case, I decided to Join method of Thread class to block the initial calling thread until the bitmap is actually available, and then return the generated web site thumbnail.
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
The _GenerateWebSiteThumbnailImage will create a WebBrowser control object and navigate to the provided Url. We also register for the DocumentCompleted event of the web browser control to take screen shot of the web page. To pass the flow to the other controls we need to perform a method call to Application.DoEvents(); and wait for the completion of the navigation until the browser state changes to Complete in a loop.
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocument
CompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
The DocumentCompleted event will be fired when the navigation is completed and the browser is ready for screen shot. We will get screen shot using DrawToBitmap method as described previously which will return the bitmap of the web browser. Then the thumbnail image is generated using GetThumbnailImage method of Bitmap class passing it the required thumbnail image width and height.
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
One more example here : http://www.codeproject.com/KB/aspnet/Website_URL_Screenshot.aspx
Tuesday, May 3, 2011
Edit in desktop application with DataGridView
private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
string s = DataGridView.Rows[e.RowIndex].Cells[1].FormattedValue.ToString();
srno = Convert.ToInt16(s);
FormName objFrm = new FormName(s);
objFrm.MdiParent = this.MdiParent;
objFrm.Show();
}
}
//Into the New Form
public FormName(string id)
{
uid = id;
i = Convert.ToInt16(id);
InitializeComponent();
}
//Get Detail As per id
public void GetDetail()
{
string detail = "SELECT fieldname1,fieldname2 FROM TableName where PrimaryKeyField = "+id+"";
DataSet ds = new DataSet();
ds = (DataSet)prm.RetriveData(detail);
}
//RetriveData Function
public object RetriveData(string query)
{
// If you have sql connection use SqlConnection
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter drap = new OleDbDataAdapter(query, con);
con.Open();
DataSet ds = new DataSet();
drap.Fill(ds);
con.Close();
return ds;
}
{
if (e.ColumnIndex == 0)
{
string s = DataGridView.Rows[e.RowIndex].Cells[1].FormattedValue.ToString();
srno = Convert.ToInt16(s);
FormName objFrm = new FormName(s);
objFrm.MdiParent = this.MdiParent;
objFrm.Show();
}
}
//Into the New Form
public FormName(string id)
{
uid = id;
i = Convert.ToInt16(id);
InitializeComponent();
}
//Get Detail As per id
public void GetDetail()
{
string detail = "SELECT fieldname1,fieldname2 FROM TableName where PrimaryKeyField = "+id+"";
DataSet ds = new DataSet();
ds = (DataSet)prm.RetriveData(detail);
}
//RetriveData Function
public object RetriveData(string query)
{
// If you have sql connection use SqlConnection
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter drap = new OleDbDataAdapter(query, con);
con.Open();
DataSet ds = new DataSet();
drap.Fill(ds);
con.Close();
return ds;
}
Thursday, March 17, 2011
Run a .sql script file in C#
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
Tuesday, March 15, 2011
.Net to Oracle Connectivity using ODBC .NET
You can use the new ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher. You need to have MDAC 2.6 or later installed and then download ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?url=/code/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml&frame=true. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver. Insta ...You can use the new ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher. You need to have MDAC 2.6 or later installed and then download ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?url=/code/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml&frame=true. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver. Install ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/msdn-files/027/001/943/msdncompositedoc.xml Create a DSN, using either Microsoft ODBC for Oracle or Oracle supplied Driver if the Oracle client software is loaded. here for eq. TrailDSN. While creating DSN give user name along with passward for eq. scott/tiger.
using Microsoft
.Data.Odbc;
private void Form1_Load(object sender, System.EventArgs e)
{
try
{
OdbcConnection myconnection= new OdbcConnection ("DSN=TrialDSN");
OdbcDataAdapter myda = new OdbcDataAdapter ("Select * from EMP", myconnection);
DataSet ds= new DataSet ();
myda.Fill(ds, "Table");
dataGrid1.DataSource = ds ;
}
catch(Exception ex)
{
MessageBox.Show (ex.Message );
}
}
using Microsoft
.Data.Odbc;
private void Form1_Load(object sender, System.EventArgs e)
{
try
{
OdbcConnection myconnection= new OdbcConnection ("DSN=TrialDSN");
OdbcDataAdapter myda = new OdbcDataAdapter ("Select * from EMP", myconnection);
DataSet ds= new DataSet ();
myda.Fill(ds, "Table");
dataGrid1.DataSource = ds ;
}
catch(Exception ex)
{
MessageBox.Show (ex.Message );
}
}
Thursday, February 17, 2011
Storing Binary Data to Database using ASP.NET 2.0
http://www.beansoftware.com/ASP.NET-Tutorials/Binary-Files-To-Database.aspx
Friday, January 28, 2011
Login - check database if user exists... (c#)
I have managed to do the following...
string connectionString = "datasource=localhost;username=xxx;password=xxx;database=xxx";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
string selectString =
"SELECT username, password " +
"FROM forum_members " +
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";
MySqlCommand mySqlCommand = new MySqlCommand(selectString, mySqlConnection);
mySqlConnection.Open();
String strResult = String.Empty;
strResult = (String)mySqlCommand.ExecuteScalar();
mySqlConnection.Close();
if (strResult.Length == 0)
{
Label1.Text = "INCORRECT USER/PASS!"
//could redirect to register page
} else {
Label1.Text = "YOU ARE LOGGED IN!";
//set loggin in sessions variables
}
string connectionString = "datasource=localhost;username=xxx;password=xxx;database=xxx";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
string selectString =
"SELECT username, password " +
"FROM forum_members " +
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";
MySqlCommand mySqlCommand = new MySqlCommand(selectString, mySqlConnection);
mySqlConnection.Open();
String strResult = String.Empty;
strResult = (String)mySqlCommand.ExecuteScalar();
mySqlConnection.Close();
if (strResult.Length == 0)
{
Label1.Text = "INCORRECT USER/PASS!"
//could redirect to register page
} else {
Label1.Text = "YOU ARE LOGGED IN!";
//set loggin in sessions variables
}
Tuesday, January 18, 2011
Getting input from keyboard
When you type on the keyboard the keystrokes go to a particular application, the active application.
The active application receives the input from the keyboard. This means the application has input focus.
There are two events for a key on a keyboard, when the key is pressed and when it is released. No it's not a single event as you might expect if you have no prior programming experience, in shooter games for example when you keep the forward key pressed (KeyDown) the player goes forward, and when it isn't pressed (KeyUp) the player stays put.
The event that occurs when the key is pressed is called KeyPress. It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.
Similar to the way we handle OnPaint and other events we also handle the OnKeyDown event (because we want the event to occur when the key is pressed and not when it is released) by overriding it.
Try the code below and test it. You will understand the role of each property.
protected override void OnKeyDown(KeyEventArgs keyEvent)
{
// Gets the key code
lblKeyCode.Text = "KeyCode: " + keyEvent.KeyCode.ToString();
// Gets the key data; recognizes combination of keys
lblKeyData.Text = "KeyData: " + keyEvent.KeyData.ToString();
// Integer representation of KeyData
lblKeyValue.Text = "KeyValue: " + keyEvent.KeyValue.ToString();
// Returns true if Alt is pressed
lblAlt.Text = "Alt: " + keyEvent.Alt.ToString();
// Returns true if Ctrl is pressed
lblCtrl.Text = "Ctrl: " + keyEvent.Control.ToString();
// Returns true if Shift is pressed
lblShift.Text = "Shift: " + keyEvent.Shift.ToString();
}
How do I find out when the user presses a specific key?
As you probably imagine, this will be easily accomplished using 'if'.
if (keyEvent.KeyCode == Keys.A)
{
MessageBox.Show("'A' was pressed.");
}
Probably most beginners would be tempted to do this:
if (keyEvent.KeyCode == "A")
....
which is definitely incorrect because we can't compare System.Windows.Forms.Keys to a string.
Also note that in the example we are using 'keyEvent.KeyCode', that means that even if we have other shift keys pressed (Alt, Ctrl, Shift, Windows...) simultaneous with A, the if condition returns true because it doesn't recognize key combinations.
If we want to ignore key combinations (Alt+A, Ctrl+Shift+A), etc. we need to use 'keyEvent.KeyData' of course:
if (keyEvent.KeyData == Keys.A)
{
MessageBox.Show("'A', and only A, was pressed.");
}
When you right click on a file in Windows Explorer and you have the Shift key pressed you get the additional 'Open with...' item in the menu. This and many others are cases when you need to use the mouse button together with the keyboard.
The following code will change the background color of the form only if the form is clicked while the Ctrl key on the keyboard is pressed. If the Ctrl key is unpressed and the form is clicked nothing happens.
private void Form1_Click(object sender, System.EventArgs e)
{
Keys modKey = Control.ModifierKeys;
if(modKey == Keys.Control)
{
this.BackColor = Color.Yellow;
}
}
If you have further questions feel free to ask them and also check the following pages at MSDN:
KeyUp Event
KeyPress Event
KeyDown Event
The active application receives the input from the keyboard. This means the application has input focus.
There are two events for a key on a keyboard, when the key is pressed and when it is released. No it's not a single event as you might expect if you have no prior programming experience, in shooter games for example when you keep the forward key pressed (KeyDown) the player goes forward, and when it isn't pressed (KeyUp) the player stays put.
The event that occurs when the key is pressed is called KeyPress. It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.
Similar to the way we handle OnPaint and other events we also handle the OnKeyDown event (because we want the event to occur when the key is pressed and not when it is released) by overriding it.
Try the code below and test it. You will understand the role of each property.
protected override void OnKeyDown(KeyEventArgs keyEvent)
{
// Gets the key code
lblKeyCode.Text = "KeyCode: " + keyEvent.KeyCode.ToString();
// Gets the key data; recognizes combination of keys
lblKeyData.Text = "KeyData: " + keyEvent.KeyData.ToString();
// Integer representation of KeyData
lblKeyValue.Text = "KeyValue: " + keyEvent.KeyValue.ToString();
// Returns true if Alt is pressed
lblAlt.Text = "Alt: " + keyEvent.Alt.ToString();
// Returns true if Ctrl is pressed
lblCtrl.Text = "Ctrl: " + keyEvent.Control.ToString();
// Returns true if Shift is pressed
lblShift.Text = "Shift: " + keyEvent.Shift.ToString();
}
How do I find out when the user presses a specific key?
As you probably imagine, this will be easily accomplished using 'if'.
if (keyEvent.KeyCode == Keys.A)
{
MessageBox.Show("'A' was pressed.");
}
Probably most beginners would be tempted to do this:
if (keyEvent.KeyCode == "A")
....
which is definitely incorrect because we can't compare System.Windows.Forms.Keys to a string.
Also note that in the example we are using 'keyEvent.KeyCode', that means that even if we have other shift keys pressed (Alt, Ctrl, Shift, Windows...) simultaneous with A, the if condition returns true because it doesn't recognize key combinations.
If we want to ignore key combinations (Alt+A, Ctrl+Shift+A), etc. we need to use 'keyEvent.KeyData' of course:
if (keyEvent.KeyData == Keys.A)
{
MessageBox.Show("'A', and only A, was pressed.");
}
When you right click on a file in Windows Explorer and you have the Shift key pressed you get the additional 'Open with...' item in the menu. This and many others are cases when you need to use the mouse button together with the keyboard.
The following code will change the background color of the form only if the form is clicked while the Ctrl key on the keyboard is pressed. If the Ctrl key is unpressed and the form is clicked nothing happens.
private void Form1_Click(object sender, System.EventArgs e)
{
Keys modKey = Control.ModifierKeys;
if(modKey == Keys.Control)
{
this.BackColor = Color.Yellow;
}
}
If you have further questions feel free to ask them and also check the following pages at MSDN:
KeyUp Event
KeyPress Event
KeyDown Event
Sunday, January 9, 2011
ASP.NET C# Session Variable
You can make changes in the web.config. You can give the location path i.e the pages to whom u want to apply the security. Ex.
1) In first case the page can be accessed by everyone.
// Allow ALL users to visit the CreatingUserAccounts.aspx //
location path="CreatingUserAccounts.aspx">
system.web>
authorization>
allow users="*" />
/authorization>
/system.web>
/location>
2) in this case only admin can access the page
// Allow ADMIN users to visit the hello.aspx
location path="hello.aspx">
system.web>
authorization>
allow roles="ADMIN' />
deny users="*" />
/authorization>
/system.web>
/location>
OR
On the every page you need to check the authorization according to the page logic
ex:
On every page call this
if (session[loggeduser] !=null)
{
DataSet dsUser=(DataSet)session[loggeduser];
if (dsUser !=null && dsUser.Tables.Count>0 && dsUser.Tables[0] !=null && dsUser.Tables[0].Rows.Count>0)
{
if (dsUser.Table[0].Rows[0]["UserType"]=="SuperAdmin")
{
//your page logic here
}
if (dsUser.Table[0].Rows[0]["UserType"]=="Admin")
{
//your page logic here
}
}
}
1) In first case the page can be accessed by everyone.
// Allow ALL users to visit the CreatingUserAccounts.aspx //
location path="CreatingUserAccounts.aspx">
system.web>
authorization>
allow users="*" />
/authorization>
/system.web>
/location>
2) in this case only admin can access the page
// Allow ADMIN users to visit the hello.aspx
location path="hello.aspx">
system.web>
authorization>
allow roles="ADMIN' />
deny users="*" />
/authorization>
/system.web>
/location>
OR
On the every page you need to check the authorization according to the page logic
ex:
On every page call this
if (session[loggeduser] !=null)
{
DataSet dsUser=(DataSet)session[loggeduser];
if (dsUser !=null && dsUser.Tables.Count>0 && dsUser.Tables[0] !=null && dsUser.Tables[0].Rows.Count>0)
{
if (dsUser.Table[0].Rows[0]["UserType"]=="SuperAdmin")
{
//your page logic here
}
if (dsUser.Table[0].Rows[0]["UserType"]=="Admin")
{
//your page logic here
}
}
}
Friday, December 31, 2010
What is the difference between String and string in C#
string :
------
The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.
'string' is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword ('string') is preferred over the full system type name (System.String, or String).
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:
String :
------
A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object
Difference between string & String :
---------- ------- ------ - ------
the string is usually used for declaration while String is used for accessing static string methods
we can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.
we can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.
we can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. I.e. - if I get data from elsewhere, I'd deserialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.
------
The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.
'string' is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword ('string') is preferred over the full system type name (System.String, or String).
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:
String :
------
A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object
Difference between string & String :
---------- ------- ------ - ------
the string is usually used for declaration while String is used for accessing static string methods
we can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.
we can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.
we can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. I.e. - if I get data from elsewhere, I'd deserialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.
Wednesday, December 29, 2010
Default text disappear from textbox with javascript
//form action="http://www.domain.com" method="post">
//input type="text" size="25" value="Enter Your Default Text Here" onFocus="if(this.value == 'Enter Your Default Text Here') {this.value = '';}" //onBlur="if (this.value == '') {this.value = 'Enter Your Default Text Here';}" />
//input type=submit value=Submit>
///FORM>
//input type="text" size="25" value="Enter Your Default Text Here" onFocus="if(this.value == 'Enter Your Default Text Here') {this.value = '';}" //onBlur="if (this.value == '') {this.value = 'Enter Your Default Text Here';}" />
//input type=submit value=Submit>
///FORM>
Monday, December 27, 2010
Javascript Open a Window Full Size (Mazimized)
function f_open_window_max( aURL, aWinName )
{
var wOpen;
var sOptions;
sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
wOpen = window.open( '', aWinName, sOptions );
wOpen.location = aURL;
wOpen.focus();
wOpen.moveTo( 0, 0 );
wOpen.resizeTo( screen.availWidth, screen.availHeight );
return wOpen;
}
{
var wOpen;
var sOptions;
sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
wOpen = window.open( '', aWinName, sOptions );
wOpen.location = aURL;
wOpen.focus();
wOpen.moveTo( 0, 0 );
wOpen.resizeTo( screen.availWidth, screen.availHeight );
return wOpen;
}
Subscribe to:
Posts (Atom)