Creating a chart with network use in asp.net - c#

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

Related

Save Changes in DataGridView C#

After calling the table from the database into the dataGridView and entering data into the empty cells of this DataGridView, I want to save this data to my database by clicking on the button, but I don’t know how to do this
This is how I access db:
public MySqlConnection mycon;
public MySqlCommand mycom;
public string connect = "Server=localhost;Database=base;Uid=root;password=pas;charset=utf8";
public SD.DataSet ds;
mycon = new MySqlConnection(connect);
mycon.Open();
MySqlDataAdapter ms_data = new MySqlDataAdapter(script, connect);
SD.DataTable table = new SD.DataTable();
ms_data.Fill(table);
dataGridView1.DataSource = table;
mycon.Close();
Pains me to write it, but this should be the minimum set of calls necessary:
MySqlDataAdapter ms_data = new MySqlDataAdapter(script, connect);
new MySqlCommandBuilder(ms_data);
ms_data.Update(dataGridView1.DataSource as DataTable);
You need an adapter, and then passing it to a command builder should make the CB read the select command loaded into the adapter and use it to populate the adapter's other commands (insert/update/delete), then you can call Update and pass a modified table and the rows in the table will be examined to see if they're new, modified or deleted and the appropriate command will be called to persist the changes
script needs to be an SQL that selects the primary key columns from the DB
Why "pains to say it" ? Because it's such a long winded, hard work way of doing database access compared to even the technology that replaced it, let alone something modern like EF. If you're liking working with datatables, consider:
Add a new DataSet type of file to the project
Open it, right click the surface, add a tableadapter
Configure the connection string
Configure a "select that returns rows" query like SELECT * FROM sometable WHERE id = #someId
A tableadapter and datatable pair appear, that mimick the table in the database
Switch to a form, open the data sources window (View Menu, Other Windows), drag the table to the form - a datagridview, dataset, tableadapter, navigator etc appear.
Everything is wired up to go.
Your tableadapter is a dataadapter on steroids, and will Fill/Update the datatable from/to database. The datatable has named columns and is generally much nicer to work with. All the code for loading and saving is already written into the FormX.cs so you can take a look, but it basically amounts to:
var x = new BlahBlahTableAdapter();
x.FillBy(this.BlahBlahDataSet, someIdTextBox.Text);
Filling the datatable that is binded to the grid will cause the data to appear in the grid automatically.
Saving is similarly simple:
var x = new BlahBlahTableAdapter();
x.Update(this.BlahBlahDataSet);
Footnote: I believe you need MySQL Tools For Visual Studio installed for this to play nice. Also, you might encounter issues if you made a NetCore/Net5+ WinForms project because some elements of new .NET don't support winforms properly
Footnote2: See https://bugs.mysql.com/bug.php?id=99199 if you're wondering why the tableadapter wizard option "Refresh the dataset" is not working
If you want to try something more modern, there are lots of good EF tutorials out there. EF is a tool that uses a database to create objects in your code. The data for the objects lives in the database and is automatically transported back and forth from/to objects/database by EF. If you get into it, EF Core Power Tools is a very useful VS addin to have

How do statements in SQL correlate with C#

I have created a database and i have linked it with a Windows Form Application
in Visual Studio and it is written in Visual C#. I am curious to know whether or not the buttons that i have added in the windows form application will correspond with
the statements that are written in SQL .
Will I need to implement code in the backend of SQL or C# or just one of the two.
You could try using something called Entity Framework, which can be installed if you right-click the project name and choose to Manage NuGet packages.
This will set up a framework for you so that you don't have to write any C# code connecting your form with your database. It is some what easy to use because it creates Table Adapters which makes the connection from a table in your database to your code, an example would be:
var myTableAdapter = new myDatabase_TableAdapters.myTableTableAdapter();
System.Data.DataTable myDataTable = myTableAdapter.GetData();
Now you have the data from your table in the SQL database in a DataTable and you have your TableAdapter as a connection between the two.
Say you want to take input from your users, then for our example consider the data comes from your text boxes then you could do something like:
string vehicleRegNum = vehicleRegNumTextBox.Text,
make = makeTextBox.Text,
engineSize = engineSizeTextBox.Text,
dateReg = dateRegTextBox.Text,
rentPerDay = rentPerDayTextBox.Text;
bool avail = availCheckBox.Checked;
myTableAdapter.Insert(vehicleRegNum, make, engineSize, dateReg, rentPerDay, avail);
This .Insert will add this data to your database (Here I am assuming all the text boxes go to one table in your database and that the order is as I have given them).
So in general,
Get Entity Framework setup in NuGet
Setup a table adapter from a table in your database
Update it with user input
A side note: I always like to add a user and date column to these kinds of tables so you can use:
string usr = System.Environment.UserName
var entryDate = System.DateTime.Now;
Clarification: It was pointed out to me by #DanRayson in the comments that I should be more clear about myDatabase_TableAdapters. It is not exactly a TableAdapter, it is however a TableAdapter which EntityFramework creates in the background for the user.

C# - Using database table to populate variables

EDIT: Thank you everyone, I figured out how to get it to work now! Details below...
I'm kind of a newbie to C#, and I'm trying to teach myself the language by programming a really simple RPG game.
Right now, I'm at the point where I want to start adding different enemies to fight (up until now I just used a single one hardcoded in for testing).
I've started setting up a database with enemy info (one column for name, one for HP, one for common stats and attacks, etc.). I have it so that when you start combat with an enemy, the player is able to select a creature from a dropdown, and whichever creature he has will set a variable called "EnemyID".
What I want to do is use that EnemyID variable to correspond to a row in my database, then pull the value of each column into variables that I can then reference during combat.
Is this something that's possible to do? If so, could someone explain the method to me in relatively simple terms? Even just a small example of how to import row data from any kind of database will do, I'm good at understanding code once I see it in use a couple of times.
(Oh yeah, if it matters, I'm using Visual Studio Express 2013, and my database is a SQL Server Express 2014 database.)
Thanks in advance!
EDIT:
After finding a simple tutorial for ADO.NET, and following a suggestion from one of the posters, I've come up with the following code.
public void DataPoll()
{
SqlConnection MonDat = new SqlConnection("Data Source=(local);
Initial Catalog=TestDatabase;Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
MonDat.Open();
SqlCommand cmd = new SqlCommand(
"select * from Monsters where Id = EnemyID", MonDat);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
EnemyIDBuffer = (int)rdr["Id"];
EnemyName = (string)rdr["Name"];
EnemyHPBase = (int)rdr["HP"];
EnemyAtkBase = (int)rdr["Atk"];
EnemyDefBase = (int)rdr["Def"];
EnemyMagBase = (int)rdr["Mag"];
PrimAtk = (string)rdr["PrimAtk"];
SecoAtk = (string)rdr["SecoAtk"];
TertAtk = (string)rdr["TertAtk"];
RareAtk = (string)rdr["RareAtk"];
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (MonDat != null)
{
MonDat.Close();
}
}
}
However, when I try to run it, my program stalls and crashes. I'm guessing I have something configured wrong (I just took script from the tutorial and tweaked it slightly). Can anyone give me a hand figuring out where I went wrong?
EnemyID is a variable I used to assign what enemy is fought, based on a menu selection. I'm trying to use that variable to generate the row ID to pull the rest of the row data from, but I think that might be causing an issue.
EDIT2: It took me longer than it really should have, but I figured it out. I had to change my code a little tiny bit.
SqlCommand cmd = new SqlCommand(
"select * from Monsters where Id = " + EnemyID, MonDat);
I have a habit of forgetting that you're able to join statements like this. I made a new project that only polled data and threw it into my variables, and from there put it into text boxes, and with this method I was able to poll two different sets of enemy stats by assigning different EnemyID values to two different buttons. Proof of concept, right there.
Thanks to both people who replied, both suggestions were equally useful to getting this working. :)
There's numerous tutorials out there on how to use a database, the first two use straight ADO.NET which is pure data access, making you responsible for its interaction in your code:
ADO.NET Overview
ADO.NET Tutorial for Beginners
The next two, one is for Entity, and the other for nHibernate, they connect to SQL databases and convert the objects there to usable code in your program through a process called object relational mapping.
Entity Framework Tutorials
nHibernate Tutorials
These are all relevant links to stuff in the most current years, with VS 2013; hopefully that provides you a good starting point.
You can do something like this:
Your SQL should pass in the procedure name and EnemyId.
The stored procedure would do a select * from Enemies where EnemyId = #EnemyId
DataSet dataSet = HSPDataAccessProxy.Instance.ExecuteDataSet(sql);
The dataSet has the table that is returned by the store procedure and you can retrieve the columns you need from that table.

How do you perform basic CRUD on a database using windows forms?

I have used the .Net framework extensively for backend processes and web pages but I have never needed to use Windows Forms. The only experience I have with Windows form type technology is with Delphi 6&7.
I have searched for tutorial as they seem to be too basic for what I am looking for. Or it seems inappropriate for what I am trying to do.
I would like to have a grid display (for this I have been using DataGridView) on a form (which I have managed to do) so that the user can view, filter and search for data. Other things like pagination would also be involved but I think that I can work out how to do that for myself.
All of the examples I come across use the DataGridView for editing, adding and deleting as well. I am not that comfortable with the idea that user user the grid for everything. It seems confusing and likely to be quite error prone.
I would like to have buttons to Add, Edit and Delete the various types of data. So for example if I had a Form to manage customers, I would like to be able to select the row to edit and click the button. This should open a new windows form with all the data preloaded in textboxes, radio buttons, checkboxes and dropdowns etc.
If they click add they would go to the same screen as the edit except all the information there would be blank. If they select a row and clicked delete it would then delete that customer and remove it from the DataGridView.
With some of the controls and databinding options I have tried it seems to fetch ALL the rows from the table. How would I be able to just get the row that I am interested in from the database. I am not sure what best practises are here.
I am suffering from information overload right now and would just appreciate someone point me in the right direction.
EDIT:
I should mention that from my Delphi days I am expecting to be able to set up something like a query or SqlCommand (Drag and drop on the gui) and set its SQL property, perhaps parameterize the SQL a little bit. Drag and drop a datasource on the form. Point the datasource to the SqlQuery/SqlCommand and click activate on the command. Now I can drag and drop compononents onto the form and set their datasource properties and to the field that they refer to.
Take a look at this sample. It shows basic ADO.NET binding to WinForm controls (not just the DataGridView).
You could do it in many ways. And there are a bunch of frameworks to help. Entity Framework, NHiberbnate.
but at a low level you can use the database related objects. SqlConnection, SqlCommand, DataReader. Below is SQL-Server related example to load a rows.
private IList<IPosition> PositionsLoad(SqlConnection connection, PositionsRequest request)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "select * from mytable WHERE x ";
cmd.CommandType = CommandType.Text;
//Get the reader
SqlDataReader reader = cmd.ExecuteReader;
IList<IPosition> ret = new List<IPosition>();
if (reader.HasRows()) {
//Create our converter to convert DataReader into a business object/s
DataReaderToPosition readerConvert = new DataReaderToPosition();
//loop rows
while (reader.Read) {
IPosition pos = readerConvert.DataReaderToBusinessObject(reader);
ret.Add(pos);
}
}
reader.Close();
return ret;
}
using the datareader:
Public Overrides Function DataReaderToBusinessObject(ByVal reader As System.Data.IDataReader) As IPosition
Dim res As IPosition = New Position
res.ItemDate = reader.GetDateTime(reader.GetOrdinal("Date"))
res.Strategy = reader.GetString(reader.GetOrdinal("Strategy"))
res.SubStrategy = reader.GetString(reader.GetOrdinal("SubStrategy"))
res.BrokerPrime = reader.GetString(reader.GetOrdinal("BrokerPrime"))
res.BrokerExecuting = reader.GetString(reader.GetOrdinal("BrokerExecuting"))
res.AccountName = reader.GetString(reader.GetOrdinal("AccountName"))
res.ExpectedLoss = reader.GetDouble(reader.GetOrdinal("Expected_Loss"))
res.RiskNotional = reader.GetDouble(reader.GetOrdinal("Risk_Notional"))
res.ModelDelta = reader.GetDouble(reader.GetOrdinal("Model_Delta"))
res.ExpectedTrancheLoss = reader.GetDouble(reader.GetOrdinal("Expected_Tranche_Loss"))
res.BaseCorrelation = reader.GetDouble(reader.GetOrdinal("Base_Correlation"))
res.LossOnSingleNameDefault = reader.GetDouble(reader.GetOrdinal("Loss_on_Single_Name_Default"))
res.RiskCapitalAllocation = reader.GetDouble(reader.GetOrdinal("Risk_Capital_Allocation"))
res.MarginFundingAllocation = reader.GetDouble(reader.GetOrdinal("Margin_Funding_Allocation"))
res.DataSource = reader.GetString(reader.GetOrdinal("DataSource"))
Return res
End Function

Retrieving SQL Server Extended Properties From 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);

Categories

Resources