Retrieving SQL Server Extended Properties From C# - c#

We document our SQL Server database by creating table and column level Description extended properties. We usually enter these via SSMS.
My question is this. I'm creating a C# application where I'd like to read the extended properties for a particular table and its associated columns.
Can someone show me how I might go about doing this?
Thanks - Randy

You simply ask for them using the built-in fn_listextendedproperty. The result of this function is an ordinary table result set that you read in C# using your data access tool of choice (SqlCommand/SqlDataReader, linq, datasets etc).

Read this: Extract SQL Column Extended Properties From LINQ in C# and see if that's something you could do in your situation.

A full example for a simple property:
In SQL Server :
Code:
String strVersion;
string cmd = "SELECT value from sys.extended_properties where name = 'MinimumClientVersion'";
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand(cmd, connection))
{
connection.Open();
strVersion = (string)comm.ExecuteScalar();
connection.Close();
}
Version MinimumVersion = new Version(strVersion);

Related

Moving processed sql data into new table using c#

I have a lot of data in several tables that I am pulling from and combining into one view. I need to have a daily job using c# to pull all of this data then insert it into a separate database/table running on a different server. The data consists of some 150+ columns once combined and I don't want to use reader.read() reader.getstring() reader.etc for every column then combine it all into a string to insert again. Is there a way to just pass the results of an sql query to an insert in a simple and compact way?
private static void GetPrimaryData(string query)
{
using (MySqlConnection connection = new MySqlConnection(_awsOptionsDBConnectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(query, connection))
{
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetInt32("tsid"));
}
}
}
connection.Close();
}
}
Ideally I'd just replace the Console.WriteLine(reader... part of code with some sort of insert where I pass the reader or the entire result of the reader query in.
Whether the data comes directly from a database, or from a user, one still needs to send the data to a database in the structure the database defines.
Your question is asking for a magical converter which would work with any type of data and send it to any database. There is no such tool or library in C#/.Net.
One should look into a cloud solution that has already been developed such as Azure Data Factory or Informatica, etc.
Otherwise write the mappings/translations as needed in C# and use an ORM to send it the data to the database.

Getting somewhat confused at this point folks

Am currently looking to use this code to display vehicle information in a data grid view in visual studio 2022 using c# :-
connStr = #"Data Source = .\sqlexpress; Initial Catalog = TDsSalesnService; Integrated Security = true";
// Setting up data adapter for datagridview display
sqlVehicleDetails = #"SELECT M.MakeName AS Make, ML.ModelName AS Model, V.Registration AS Reg, V.VINNum, V.PriceCost, V.PriceSell, V.Colour, VT.VehicleTypeDesc AS Type, V.Transmission, V.EngineSize, V.FuelType, V.Mileage, V.Condition, V.VehicleYear AS Year, V.Availableness AS Availability
FROM Vehicle V
JOIN VehicleType VT ON V.VehicleTypeID = VT.VehicleTypeID
JOIN Model ML on V.ModelID = ML.ModelID
JOIN Make M on ML.MakeID = M.MakeID
ORDER BY M.MakeName, ML.ModelName, VT.VehicleTypeDesc, V.VehicleYear ASC";
conn = new SqlConnection(connStr);
cmdVehicleDetails = new SqlCommand(sqlVehicleDetails, conn);
daVehicleDetails = new SqlDataAdapter(sqlVehicleDetails, conn);
cmdBVehicleDetails = new SqlCommandBuilder(daVehicleDetails);
daVehicleDetails.FillSchema(dsTDsSalesnService, SchemaType.Source, "Vehicle");
daVehicleDetails.Fill(dsTDsSalesnService, "Vehicle");
This works fine.
The issue comes when I go to write records to the database and it's saying it doesn't accept null values for the first field m.makename.
I was hoping to use and call the vehicle table using this code so i can write new records in the correct format :-
sqlVehicle = #"SELECT * from Vehicle";
daVehicle = new SqlDataAdapter(sqlVehicle, connStr);
cmdBVehicle = new SqlCommandBuilder(daVehicle);
daVehicle.FillSchema(dsTDsSalesnService, SchemaType.Source, "Vehicle");
daVehicle.Fill(dsTDsSalesnService, "Vehicle");
But keeps throwing error about the tables used not being unique.
I truth I would need each line explained as to what is going on so i can map in my head how the process is functioning as I don't think an just understanding it tbh.
Any help would be appreciated.
So the error reads System.ArgumentException:
'These columns don't currently have unique values.'
and it points to the daVehicle.FillSchema(dsTDsSalesnService, SchemaType.Source, "Vehicle"); line.
What am basically trying to do is have the datadgrid view display the vehicle details formatted using the first block of code to make it more legible to the user, but when I go to add records to the database I want to use it's raw format using the second block of code without utilizing the extra naming conventions and there's a extra field there that cause additional problems writing to the db even if i don't use the 2nd block of code.
I can use the second block of code as it for display and writing to the db but it's now useful to the user, looks awful and very hard to reads as it's codes in place of the fields instead of proper names.
datagridview using 1st block of code only
datagridview using 2nd block of code only

Creating a chart with network use in asp.net

I'm looking to create a chart with the history of network usage in my company. The DBA already guaranteed that the data exists and will create a query to get the data from the DB and then I can manipulate that info.
I never created a chart before in Asp.Net, so I really don´t know how to begin, and the samples that I found on the internet, using Microsoft Chart Control where really not clear to a beginner and they were well outdated.
I´m looking for a way to create that chart and populate it with my variables.
I don´t have the query yet and the Microsoft Chart Control Add On can´t be installed in Visual Studio 2013, so I have nothing yet.
Can anybody help me?
You may read the database from your query into array variables, then use those variables to plot the chart. The following is based on a charting library called ChartDirector.
//Open the connection to your database (using MS SQL as an example)
SqlConnection connection = new SqlConnection(connectionString)
//Issue the SQL query to read the data
string queryString = "SELECT MyTimeStamp, MyNetworkUsage FROM XXX;";
SqlCommand cmd = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
//Convert to arrays
ChartDirector.DBTable table = new ChartDirector.DBTable(reader);
DateTime[] timeStamps = table.getColAsDateTime(0); //1st column is timestamp
double[] data = table.getCol(1); //2nd column is data
Now you can simply use those arrays in any charting example that accepts arrays as data. Some examples are:
A simple .NET line chart
A .NET line chart with tracking cursor

Accessing Local Database [duplicate]

I'm coming over from PHP and am having a hard time with storing information into my newly created local database. I'm using Microsoft Visual C# 2010 to help me learn and develop.
I'm reading that many people do not like datasets and would opt to ignore them all together. That is fine if I am able to hard-wire into my local database. (I did not use the server database option provided because I'll turn my completed product into a commercial solution and this will require the users to store their information into a local database that stores their project data.
I've made a video showing my windows form and my database, and the extent of my knowledge so far. Maybe you guys can help? http://screencast.com/t/x9Qt1NtOgo6X
There are many ways to access a database from your application. These range from low-level ado.net commands (SqlDataReader, etc..) to using an Object Relational Mapper (ORM) such as Entity Framework.
All of them will require that you learn the technologies, but you can start here:
http://windowsclient.net/learn/videos.aspx
Here's some code that uses SQLServer to do a direct insert, although you'll need a connection string to your database.
Include the SQL server database includes.
using System.Data.SqlClient;
using System.Data.SqlTypes;
.
.
.
using (SqlConnection cn = new SqlConnection("XXXXX")) // must put a connection string to your database here
{
cn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Session(field1, field2) VALUES(#Value1, #Value2)"))
{
cmd.Parameters.AddWithValue("#Value1", 4);
cmd.Parameters.AddWithValue("#Value2", "test");
cmd.ExecuteNonQuery();
}
}
Well, if you want a quick, almost close to the wire code like the way you used to have with PHP, the following code should work.
var conn = new SqlConnection("Your Connection String");
var command = conn.CreateCommand();
command.CommandText = "insert into sessions (id, name) values (#id, #name)";
command.Parameters.AddWithValue("#id", "");
command.Parameters.AddWithValue("#name", "test");
conn.Open();
command.ExecuteNonQuery();
command.Dispose();
conn.Close();
In the long run, it would be better if you get accustomed to one of the data-related / ORM frameworks such as Entity Framework, NHibernate and the likes. That would really help a lot in data manipulation and make your life a whole lot easier.
It depends on your requirments, but for most situations, I would highly recommend you use Entity Framework or Linq to Sql data classes. You'd be much better off... go with the latter as a start... hope it helps.
[Edited]
If you want to see how easy an ORM can be:
right-click on your project
select Add New Item
Choose Linq to Sql Data Classes
When you've added it, you'll have a blank .dbml file
Go to server explorer and add a connection to the sql db
Drag and drop the tables wherever you like
Start using the entities like this:
using (DataClasses1DataContext db = new DataClasses1DataContext("Data Source=localhost\sqlexpress; Initial Catalog=myDBName; Integrated Security=true"))
{
IEnumerable citiesForUSA = db.Cities.Where(x => x.Country.Name == "United States");
City city = new City();
city.Name = "Metropolis";
//etc
db.Cities.InsertOnSubmit(city);
db.SubmitChanges(); // <-- INSERT INTO completed
//etc
}
Good luck!
:-)

How to create a piece of C#.NET script to let MySql server execute a MySql Script?

Suppose I have a myTest.sql scripts, which contains thousands of "create table blahblah" statements.
myTest.sql :
CREATE TABLE A;
CREATE TABLE A1;
....
CREATE TABLE A1000;
What Im trying to achieve is that make an C# script to force MySql server EXECUTE the myTest.sql file, instead of doing
using (MySqlConnection cn = new MySqlConnection(ConectionString))
{
MySqlCommand newCmd = new MySqlCommand("create statement here 1", cn);
cn.Open();
newCmd.ExecuteNonQuery();
cn.Close();
}
I dont want to repeat 1000 times or a for loop something like that. Thanks for all helps and please forgive my grammar problems.
Could you load the myTest.sql file into a string and pass it to the MySqlCommand.
string myTestSql = IO.File.ReadAllText("myTest.sql");
...
MySqlCommand newCmd = new MySqlCommand(myTestSql, cn);
Should work as long as MySQL accepts commands separated by semicolons.
You certainly don't have to open and close the connection every single time, but it would be the cleanest if you ran each of these one at a time and look at the result to ensure that the statement completed successfully. Unfortunately if you run a giant statement with 1000 statements and it fails, you don't have an easy way of determining which step(s) were successful and which have to be repeated.
Use this
You can do it using mysql command-line and shell with System.Process static methods if you want to use .net / c#.

Categories

Resources