i'm building GPS application where GPS devices send location by tcp port
i'm building a service to read these messages and save it to database
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8889);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
// Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
// Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
// Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
static void WriteLog(string message, EventLogEntryType type)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(message, type, 101, 1);
}
}
static int InsideDangerArea(double Lat, double Lng)
{
string point = "POINT(" + Lng + " " + Lat + ")";
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_Geofncies", conn))
{
DataTable dt = new DataTable();
dt.Load(comm.ExecuteReader());
foreach (DataRow dr in dt.Rows)
{
string Query = " DECLARE #g geometry; DECLARE #h geometry; SET #g = (select(points) from T_Geofncies where id=" + dr["id"].ToString() + " );";
Query += " SET #h = geometry::STGeomFromText('" + point + "', 4326); SELECT #g.STContains(#h);";
comm.CommandText = Query;
int Val = Convert.ToInt32(comm.ExecuteScalar());
if (Val == 1)
{
conn.Close();
conn.Dispose();
return Convert.ToInt32(dr["id"]);
}
}
}
conn.Close();
conn.Dispose();
}
return 0;
}
static int OutsideSafeArea(double Lat, double Lng)
{
string point = "POINT(" + Lng + " " + Lat + ")";
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_SafeArea", conn))
{
DataTable dt = new DataTable();
dt.Load(comm.ExecuteReader());
foreach (DataRow dr in dt.Rows)
{
string Query = " DECLARE #g geometry; DECLARE #h geometry; SET #g = (select(points) from T_SafeArea where id=" + dr["id"].ToString() + " );";
Query += " SET #h = geometry::STGeomFromText('" + point + "', 4326); SELECT #g.STContains(#h);";
comm.CommandText = Query;
int Val = Convert.ToInt32(comm.ExecuteScalar());
if (Val == 1)
{
conn.Close();
conn.Dispose();
return Convert.ToInt32(dr["id"]);
}
}
}
conn.Close();
conn.Dispose();
}
return 0;
}
static SqlGeography GetGeographyFromText(String pText)
{
SqlString ss = new SqlString(pText);
SqlChars sc = new SqlChars(ss);
try
{
return SqlGeography.STPointFromText(sc, 4326);
}
catch (Exception ex)
{
throw ex;
}
}
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
int requestCount = 0;
// byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
int i;
int size = (int)clientSocket.ReceiveBufferSize;
// Loop to receive all the data sent by the client.
Byte[] bytes = new Byte[size];
string data = "";
string IMEI;
while ((i = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
try
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
string[] tokens = data.Split(new[] { "GPRMC" }, StringSplitOptions.None);
var longest = Regex.Matches(data, #"\d+").Cast<Match>().OrderByDescending(m => m.Length).First();
IMEI = longest.ToString();
if (IMEI.Length > 15)
IMEI = IMEI.Substring(1);
foreach (string item in tokens)
{
try
{
string[] Values = item.Split(','); // Console.WriteLine("Received: {0}", data);
string time = Values[1];
// Console.WriteLine("Time= " + time);
string lat;
string lng;
string speed;
string date;
lat = Values[3];
lng = Values[5];
speed = Values[7];
date = Values[9];
string NewDString = date.Substring(2, 2) + date.Substring(0, 2) + date.Substring(4, 2);
// Console.WriteLine("IMEI= " + IMEI);
// Alternate choice: If the string has been input by an end user, you might
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
string myDate = (NewDString + time).Insert(2, "-").Insert(5, "-").Insert(8, " ").Insert(11, ":").Insert(14, ":");
double latDeg = Convert.ToDouble(Convert.ToDouble(lat).ToString().Substring(0, 2));
double latMin = Convert.ToDouble(Convert.ToDouble(lat).ToString().Substring(2));
double lngDeg = Convert.ToDouble(Convert.ToDouble(lng).ToString().Substring(0, 2));
double lngmin = Convert.ToDouble(Convert.ToDouble(lng).ToString().Substring(2));
double latmap = latDeg + (latMin / 60);
// OldLat=
double lngmap = lngDeg + (lngmin / 60);
//if ((Math.Round(latmap, 3) != Math.Round(OldLat, 3) && Math.Round(lngmap, 3) != Math.Round(OldLng, 3)) || idleRecord > 30)
//{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
// DbCommand also implements IDisposable
// create command with placeholders
cmd.CommandText =
"INSERT INTO T_Tracking " +
"([IMEI], [TrackTime], [Longitude], [Lattitude], [speed],[MapPoint],[SafeAreaID],[GeoFenceID]) " +
"VALUES(#IMEI, #TrackTime, #Longitude, #Lattitude, #speed,#MapPoint,#SafeAreaID,#GeoFenceID)";
SqlParameter p_IMEI = new SqlParameter("#IMEI", IMEI);
cmd.Parameters.Add(p_IMEI);
SqlParameter p_TrackTime = new SqlParameter("#TrackTime", myDate);
cmd.Parameters.Add(p_TrackTime);
SqlParameter p_Longitude = new SqlParameter("#Longitude", lngmap);
cmd.Parameters.Add(p_Longitude);
SqlParameter p_Lattitude = new SqlParameter("#Lattitude", latmap);
cmd.Parameters.Add(p_Lattitude);
SqlParameter p_Speed = new SqlParameter("#speed", speed);
cmd.Parameters.Add(p_Speed);
SqlParameter p_Points = new SqlParameter("#MapPoint", System.Data.SqlDbType.Udt);
p_Points.UdtTypeName = "geometry";
p_Points.Value = GetGeographyFromText("Point(" + lngmap + " " + latmap + ") ");
cmd.Parameters.Add(p_Points);
SqlParameter P_Safe = new SqlParameter("#SafeAreaID", OutsideSafeArea(latmap, lngmap));
cmd.Parameters.Add(P_Safe);
SqlParameter P_GeoFence = new SqlParameter("#GeoFenceID", InsideDangerArea(latmap, lngmap));
cmd.Parameters.Add(P_GeoFence);
// execute
cmd.ExecuteNonQuery();
}
//}
//else
// idleRecord = idleRecord + 1;
}
}
catch (Exception exp) { WriteLog(exp.ToString(), EventLogEntryType.Error); }
}
}
catch { }
}
}
catch (Exception ex)
{
// Console.WriteLine(" >> " + ex.ToString());
}
}
}
}
}
it is working fine but the problem is performance
it is test system with 5 devices
it consume 95% memory on server on 10 minutes
what can be done to optimize that code
Thank You
The problem here is that every time a new socket connection comes in you are creating a new thread that never ends even when the underlying connection is closed. The thread procedure is wrapped with a catch-all exception handler inside a while (true) loop, and so when the socket connection is closed and a SocketException thrown this is caught and ignored and the thread procedure loops again. This will also prevent garbage collection of the socket objects and is probably highly CPU intensive as well. Also the cleanup code at the end of main will never be called because of the while(true) there, and indeed would only close the last client connection.
Your thread procedure should correctly handle exceptions and stop looping when the underlying socket connection is closed.
Related
Im trying to write "Increasing Numbers/Price" in a While with incrementing in my Database, but still didnt work...
Without a while /incrementing my other code works very well, and i get writed data in my database but with the "while code" not... can anyone help me out? thx you
namespace Testing
{
class Program
{
static void Main(string[] args)
{
SqlConnection con;
string str;
string Buyable;
Buyable = "0";
int count = 10;
double Add = 0.00000000;
for (int i = 0; i < count; i++)
{
Add = Add + 0.00000005;
try
{
str = #"..........";
con = new SqlConnection(str);
con.Open();
Console.WriteLine("Database connected");
string query = "INSERT INTO[dbo].[Table]([Price], [Buyable]) VALUES('" + Add + "'," + Buyable + ")";
SqlCommand ins = new SqlCommand(query, con);
ins.ExecuteNonQuery();
Console.WriteLine("Stored");
Console.ReadKey();
}
catch (SqlException)
{
}
}
}
}
}
Try this:
static void Main(string[] args)
{
double Add = 0D; //You really should use a **decimal** for anything to do with money!
int Buyable = 0;
int count = 10;
string str = #"..........";
string sql = "INSERT INTO[dbo].[Table]([Price], [Buyable]) VALUES(#Add, #Buyable);"; // + Add + "'," + Buyable + ")";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand ins = new SqlCommand(sql, con))
{
ins.Parameters.Add("#Add", SqlDbType.Float);
ins.Parameters.Add("#Buyable", SqlDbType.Int); //guessing at parameter type here
con.Open();
Console.WriteLine("Database connected");
for (int i = 0; i < count; i++)
{
Add += 0.00000005D;
try
{
ins.Parameters["#Add"].Value = Add;
ins.Parameters["#Buyable"].Value = Buyable;
ins.ExecuteNonQuery();
Console.WriteLine("Stored");
Console.ReadKey();
}
catch (SqlException ex)
{
//Do *something* with the exception here!
Console.WriteLine("Error using the database. The message is:\n{0}", ex.Message);
}
}
}
}
Don't leave the connection open and try to use using with all disposable objects in your C# life.
str = #"..........";
using(con = new SqlConnection(str))
{
con.Open();
Console.WriteLine("Database connected");
string query = "INSERT INTO[dbo].[Table]([Price], [Buyable]) VALUES('" + Add + "'," + Buyable + ")";
SqlCommand ins = new SqlCommand(query, con);
ins.ExecuteNonQuery();
Console.WriteLine("Stored");
Console.ReadKey();
}
Here you are writing con.Open(); in loop without closing previous connection con.Close(); which cause to throw error , write con.Close(); after ins.ExecuteNonQuery(); and try.
Another solution is Open your connection before loop and close after for loop ends .. I think this may help you
I have this simple code C# and SQL Server database:
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
// here like cursor stop
cm2.ExecuteNonQuery();
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
I have run it but nothing happens on query execution I used MessageBox like that to identify the line that has the problem
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
MessageBox.Show("1");
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
MessageBox.Show("2");
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
MessageBox.Show("3");
// here cursor stops
cm2.ExecuteNonQuery();
// that messagebox isn't shown
MessageBox.Show("4");
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
Any help will be appreciated
You haven't opened your Connection. See below.
You should also use the using syntax to make use of IDisposable
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
var sqlCmdText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
try
{
using (var sqlConnection = new SqlConnection([YOUR CONNECTION STRING HERE]))
{
using (var sqlCommand = new SqlCommand(sqlCmdText, sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new DataException(ex.Message);
}
i got one thread reading on the database. When i click on the menustrip it shows an error "Database is locked." and it only happen sometimes. Any way to prevent the database lock? I have try WAL but its not working.
Reading:
private void checkPort(string ipIN, char[] input, string output)
{
try
{
bool building = false;
Thread beep = new Thread(Beep);
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string query = "select * from ALL_IO(nolock)";
using (SQLiteCommand cmd = new SQLiteCommand(query, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
int Contact;
while (dr.Read())
{
string _IP = dr.GetString(0);
string _IO_I = dr.GetString(1);
string _BuildingName = dr.GetString(4);
int IO_I = Convert.ToInt32(dr.GetString(1).Replace("DI ", ""));
if (dr.GetString(3) == "NC")
{
Contact = 1;
}
else
{
Contact = 0;
}
_tableName = dr.GetString(8);
string _name = dr.GetString(5);
var _active = dr.GetString(6);
var _status = dr.GetString(7);
if (_active == "Yes" && _status == "Enable")
{
//Some condition check here
}
}
catch { }
}
Writing:
void contexMenuuu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
data = "";
ToolStripItem item = e.ClickedItem;
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string sql = "select * from " + Properties.Settings.Default.TableName + "(nolock) where Name= '" + Properties.Settings.Default.LabelName.Replace(" DO", "") + "' ";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
_controllerIP = dr.GetString(0);
_IO = dr.GetString(1);
_IO_O = dr.GetString(2).Replace("DO ", "");
_Name = dr.GetString(4);
_Interval = Convert.ToInt32(dr.GetString(9));
}
}
}
}
if (item.Text == "Bypass Enable")
{
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
//c.DefaultTimeout = 2000;
c.Open();
string sql = "update ALL_IO SET Active='Yes', Status='Bypass' where ControllerIP='" + _controllerIP + "' and DI='" + _IO + "';";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
lock (lockobj)
{
//SQLiteConnection.ClearAllPools();
cmd.ExecuteNonQuery(); //Error occur here
}
}
}
}
Once the functionality is finished you must close the Database connect for avoid database lock issue. For executing the query you opened the database connection after that you didn't close it. so you need to close.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
This is my code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.Common;
public class General_function
{
internal System.Windows.Forms.DataGridView DG_ItemShow;
public static object Get_Single_Value(string SQLQuery)
{
try
{
object SingleValue = null;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = SQLQuery;
SingleValue = cmd.ExecuteScalar;
return SingleValue;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Get_Single_Value : " + ex.Message);
}
}
public static long get_Max_value(string tablename, string fieldname)
{
try
{
long maxvalue = 0;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = "select max(" + fieldname + ") From " + tablename;
string res = null;
res = cmd.ExecuteScalar.ToString;
if (string.IsNullOrEmpty(res))
{
maxvalue = 0;
}
else
{
maxvalue = long.Parse(res);
}
return maxvalue;
}
catch (Exception ex)
{
Interaction.MsgBox("Error in get_Max_value" + ex.Message);
}
}
public static int Save_Record(ArrayList Al, string TableName)
{
try
{
int Retval = 0;
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = ds.Tables(TableName);
ArrayList tal = new ArrayList();
foreach (DataColumn cl in dt.Columns)
{
tal.Add(cl.ColumnName);
}
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string n = null;
for (int i = 0; i <= tal.Count - 1; i++)
{
n = "#" + tal(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = n;
pa.Value = Al(i);
cmd1.Parameters.Add(pa);
}
n = "";
string v = "";
string sqlstr = "insert into " + TableName + " (";
for (int i = 0; i <= tal.Count - 1; i++)
{
n = n + "," + tal(i).ToString;
v = v + ",#" + tal(i).ToString;
}
n = Strings.Right(n, Strings.Len(n) - 1);
v = Strings.Right(v, Strings.Len(v) - 1);
sqlstr = sqlstr + n + ") values (" + v + ")";
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Save_Record : " + ex.Message);
}
}
public static int Delete_Record(ArrayList AlName, ArrayList AlValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "delete from " + TableName + " where ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + " And " + AlName(i).ToString + "=#" + AlName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 4);
sqlstr = sqlstr + v;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Delete_Record : " + ex.Message);
}
}
public static int Modify_Record(ArrayList AlName, ArrayList AlValue, ArrayList
AlPKName, ArrayList AlPKValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
//values parameters
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
//primary key column parameters
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
m = "#" + AlPKName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlPKValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "update " + TableName + " set ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + "," + AlName(i).ToString + "=#" + AlName(i).ToString;
}
string w = "";
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
w = w + " And " + AlPKName(i).ToString + "=#" + AlPKName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 1);
w = Strings.Right(w, Strings.Len(w) - 4);
sqlstr = sqlstr + v + " Where " + w;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Modify_Record : " + ex.Message);
}
}
public static DataTable RecordSearch(string SqlString, string TableName)
{
try
{
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = default(DataTable);
DbDataAdapter da = database_Object.GetAdapter(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
cmd.Connection = cnn;
cmd.CommandText = SqlString;
da.SelectCommand = cmd;
da.Fill(ds, TableName);
dt = ds.Tables(TableName);
cnn.Close();
cmd.Dispose();
da.Dispose();
cnn.Dispose();
return dt;
}
catch (Exception ex)
{
Interaction.MsgBox("error in RecordSearch : " + ex.Message);
}
}
}
How can I call the this class method from another page?
Using your static methods, you just call them by referencing the namespace:
object result = General_function.Get_Single_Value("select * from table");
as shown in code, you defined method as static so in order to invoke that method u can use,
var o = General_function.Get_Single_Value("your_parameter");
and
long lobj = General_function.get_Max_value("table_name","field_name");
and so on...
Is it possible to generate the database creation scripts for a SQL server database from .NET?
I am using C# and I would like to create some sort of an installer project for my application
on which I can select an existing database, generate the creation scripts and run them on another SQL server instance.
Yes, it is possible.
It's easy to do this with SMO, see Transfer class for scripting operations and Database class for database operations (create, drop, etc). Usage looks like this:
private StringCollection GetTransferScript(Database database)
{
var transfer = new Transfer(database);
transfer.CopyAllObjects = true;
transfer.CopyAllSynonyms = true;
transfer.CopyData = false;
// additional options
transfer.Options.WithDependencies = true;
transfer.Options.DriAll = true;
transfer.Options.Triggers = true;
transfer.Options.Indexes = true;
transfer.Options.SchemaQualifyForeignKeysReferences = true;
transfer.Options.ExtendedProperties = true;
transfer.Options.IncludeDatabaseRoleMemberships = true;
transfer.Options.Permissions = true;
transfer.PreserveDbo = true;
// generates script
return transfer.ScriptTransfer();
}
if you want to create database dynamically with c# code then here is the code:
you can do it like this also:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text);
if (!resultdbexistencx)
{
// if not exists create it check the user name for sub-admin avialibe or not.
if (txt_DbName.Text.Trim() == string.Empty) return;
string strDbCreate;
strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " +
"(NAME = " + txt_DbName.Text + "_Data, " +
"FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " +
"SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " +
"LOG ON (NAME = " + txt_DbName.Text + "_Log, " +
"FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " +
"SIZE = 4MB, " +
"MAXSIZE = 10GB, " +
"FILEGROWTH = 100%)";
SqlConnection sqlconn = new SqlConnection(Connectionstring);
SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
try
{
sqlconn.Open();
sqlconn.ChangeDatabase("master");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult));
if (dbRollbackResult == 1)
{
Response.Write(ex.Message);
lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible.");
}
}
Here is the code of "RollBackTheWholetransaction" method :
private Int32 RollBackTheWholetransaction(String DbName, Int32 HospitalId)
{
Int32 result = 0;
try
{
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
String sqlCommandText = "ALTER DATABASE [" + DbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
String sqlCommandText1 = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
ClsHospitals objHospiitals = new ClsHospitals();
String resultDbdelete = objHospiitals.DeleteHospital(HospitalId, Session["devSuperAdmin"].ToString());
if (resultDbdelete == "1")
{
result = 1;
}
else
{
result = 2;
}
}
else
{
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
}
And here is the code to check existence of db in Database :
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
// tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
if (tmpConn.State == System.Data.ConnectionState.Open)
{
tmpConn.Close();
tmpConn.Dispose();
}
tmpConn.Open();
tmpConn.ChangeDatabase("master");
int databaseID = (int)sqlCmd.ExecuteScalar();
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
its the working code, hope it will work for you too....
You have to create your own installer by coding it all yourself. there are frameworks out there that make it much easyier.
like Windows Installer XML (WiX)
Windows installer
and more...
I would suggest you to have a look at WiX, worked with it and its quite easy and you can do much. Can be integrated in Visual Studio