i need to write some data to a HDF5 file, i have a list of objects of the class "OPC_UA" inside a "BV" class, i want to create a dataset with the name of the BV and inside the dataset i want to have the list of the "OPC_UA" objects, tha OPC_UA Class have 3 attributes, a Long int ,one float value and a Datetime that i will convert to a timestamp, i can't seem to make it work, the Marshal.SizeOf() doesn't work with classes but i cant do it as a struct... Here is my code:
public void CriaHDF5Customizado(PackingConfigFile pf)
{
H5FileId fileId = H5F.create("pmdfq.h5", H5F.CreateMode.ACC_TRUNC);
H5GroupId infoGroupId = H5G.create(fileId, "informations");
H5G.close(infoGroupId);
H5GroupId datasetGroupId = H5G.create(fileId, "datasets");
long[] dims = new long[1];
foreach(BasicVariable bv in pf.basicVariableList.bvList)
{
OPC_UA aux = new OPC_UA();
var xx = bv.bvData;
int tamanho = Marshal.SizeOf(typeof(OPC_UA));
dims[0] = (long)bv.bvData.Count;
// dims[1] = (long)4;
H5DataSpaceId spaceId = H5S.create(H5S.H5SClass.SCALAR);
H5DataTypeId dataTypeId = H5T.create(H5T.CreateClass.COMPOUND, Marshal.SizeOf(typeof(OPC_UA)));
H5T.insert(dataTypeId, "TimeStamp", 0, new H5DataTypeId(H5T.H5Type.NATIVE_UINT));
H5T.insert(dataTypeId, "Quality", Marshal.SizeOf(H5T.H5Type.NATIVE_UINT), new H5DataTypeId(H5T.H5Type.NATIVE_UINT));
H5T.insert(dataTypeId, "Value", 2* Marshal.SizeOf(H5T.H5Type.NATIVE_UINT), new H5DataTypeId(H5T.H5Type.NATIVE_INT));
H5DataSetId dataSetId = H5D.create(datasetGroupId, bv.bvTag, dataTypeId, spaceId);
//H5D.write(dataSetId, new H5DataTypeId(H5T.H5Type.STD_REF_OBJ), new H5Array<OPC_UA>(bv.bvData.ToArray()));
H5D.writeScalar(dataSetId, dataTypeId, ref xx);
H5D.close(dataSetId);
}
H5G.close(datasetGroupId);
H5F.close(fileId);
}
And this is the OPC UA Class
public class OPC_UA
{
public DateTime timeStamp { get; set; }
public string data { get; set; }
public Int64 quality { get; set; }
public OPC_UA(DateTime? ts = null ,string dt = "",Int64 qlt = -99)
{
if (!ts.HasValue)
{
timeStamp = DateTime.Now;
}
data = dt;
quality = qlt;
}
public DateTime timeStamp { get; set; }
DateTime is not an atomic datatype. Convert it into long/Int64 ticks. Then you might be able to write it.
public DateTime timeStamp
{
get { return new DateTime(StartTimeTicks); }
set
{
StartTimeTicks = value.Ticks;
}
}
public long StartTimeTicks;
The constructor may also be hindering it.
The workaround would be making a structure. Note: Make the structure of fields or properties, depending upon (GetFields)fields or (GetProperties)properties you will to use in the reflection to read it.
public structure OPC_UA
{
public string data;
public Int64 quality ;
public DateTime timeStamp
{
get { return new DateTime(StartTimeTicks); }
set
{
StartTimeTicks = value.Ticks;
}
}
public long StartTimeTicks;
}
Hdf5DotnetTools is a working C# wrapper on Hdf.PInvoke. You can write a compound dataset by using a C# structure list.
If you have any difficulty in using the functions of either Hdf.PInvoke or Hdf5DotnetTools, you can use its UnitTest project.
Related
I am getting
Parameter 'Volm' can be removed; its initial value is never used,
despite, as far as I can tell, the value being used.
I am getting
Unnecessary assignment of a value to 'Volm'
for that same value being assigned.
And, on publish, I am getting
Function signature of "FillRow" method does not match SQL declaration for table valued CLR function'GetQuoteHistory' due to column 7,
despite having 7 columns for each, and matching data types.
If I comment out the last column in the function, table definition, and assignment, the project publishes.
I am banging my head, and not because there is music playing. Appreciate other sets of eyes. The above messages are noted on the relevant lines.
public class TableFunctions
{
[SqlFunction(FillRowMethodName = "FillQuoteHistoryRow",
TableDefinition = "Symbol NVarChar(10), TradeTime datetime,
Opn money, High money,
Low money, Clos money,
Volm int")]
public static IEnumerable GetQuoteHistory(string Symbol)
{
return new QuoteHistory(Symbol);
}
private static void FillQuoteHistoryRow(Object Item, ref string Symbol, ref DateTime TradeTime,
ref decimal Opn, ref decimal High,
ref decimal Low, ref decimal Clos,
int Volm) // mouseover: Parameter 'Volm' can be removed; its initial value is never used.
// on publish, builds, but returns:
// (278,1): SQL72014: .Net SqlClient Data Provider: Msg 6258, Level 16, State 1, Procedure GetQuoteHistory,
// Line 1 Function signature of "FillRow" method(as designated by SqlFunctionAttribute.FillRowMethodName)
// does not match SQL declaration for table valued CLR function'GetQuoteHistory' due to column 7.
{
QuoteHistoryItem QHItem = (QuoteHistoryItem)Item;
Symbol = QHItem.Symbol;
TradeTime = QHItem.Time;
Opn = QHItem.Opn;
High = QHItem.High;
Low = QHItem.Low;
Clos = QHItem.Clos;
Volm = QHItem.Volm; // mouseover: Unnecessary assignment of a value to 'Volm'
} // method
} // class TableFunctions
public class QuoteHistory : List<QuoteHistoryItem>
{
public QuoteHistory(string Symbol)
{
LoadQuoteHistory(Symbol);
} // method QuoteHistory
public void LoadQuoteHistory(string Symbol)
{
string path = "C:\\Github\\Uranus\\SQLCLR\\APIOrig\\";
string func = "TIME_SERIES_INTRADAY_EXTENDED";
string interval = "1min";
string slice = "year1month1";
string apikey = "XBM9114REDBJXZIV";
string QueryURL = "https://www.alphavantage.co/query" +
"?function=" + func +
"&symbol=" + (string)Symbol +
"&interval=" + interval +
"&slice=" + slice +
"&apikey=" + apikey;
QueryURL = "file:///" + path + "Example.csv"; // FOR TESTING
Uri queryUri = new Uri(QueryURL);
using (WebClient client = new WebClient())
{
using (MemoryStream stream = new MemoryStream(client.DownloadDataTaskAsync(queryUri).Result))
{
stream.Position = 0;
using (StreamReader APIData = new StreamReader(stream))
{
while (!APIData.EndOfStream)
{
var quoteLine = APIData.ReadLine();
var quoteFields = quoteLine.Split(',');
var QHItem = new QuoteHistoryItem(Symbol, quoteFields);
if (QHItem.Time > new DateTime(1900, 1, 1))
{
Add(QHItem);
} // if
} // while
} // streamreader
} // memory stream
} // webclient
} // LoadQuoteHistory
public class QuoteHistoryItem
{
public string Symbol { get; set; }
public DateTime Time { get; set; }
public decimal Opn { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Clos { get; set; }
public int Volm { get; set; }
public QuoteHistoryItem(string symbol, string[] quoteFields)
{
if (quoteFields != null && quoteFields.Length > 5)
{
try
{
Symbol = symbol;
DateTime.TryParse(quoteFields[0], out DateTime time);
Time = time;
decimal.TryParse(quoteFields[1], out decimal opn);
Opn = opn;
decimal.TryParse(quoteFields[2], out decimal high);
High = high;
decimal.TryParse(quoteFields[3], out decimal low);
Low = low;
decimal.TryParse(quoteFields[4], out decimal clos);
Clos = clos;
int.TryParse(quoteFields[5], out int volm);
Volm = volm;
}
catch (FormatException fx)
{
Console.Error.WriteLine(fx.Message);
}
}
} // method QuoteHistoryItem
I am very new to C#. I am writing a program using visual studio c# where it will first ask the user to enter an employee name. Next, it will pass that name through an API and will retrieve and display the employee signature. I have completed this portion.
Next, the program will ask the user to enter a designated "to" and "from" date. Next, the program should pass the date information as well as the signature obtained previously through a second API and retrieve and display information on to a grid data table accordingly.
For the Grid view data table, I understand that I should be connected to a SQL data server, which I am.
My problem is that
I am not sure how to write a code which will pass three parameters to an API (the "to" and "from" date, and the employee signature). I have tried the code below, however, I receive an error when I try to link the corresponding button to the JSON code to retrieve data. The error states that
"There is no argument given that corresponds to the required formal
parameter 'toDate' of 'WebAPI.GetTime(double, double, string).'
I am not sure how to pass the signature previously obtained from a different API through the new API.
Any help would be much appreciated.
Code for defining the JSON variables:
namespace TimeSheet_Try11_Models
{
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class OracleHour
{
public string orderNumber { get; set; }
public DateTime dateOfWork { get; set; }
public string description { get; set; }
public string surveyor { get; set; }
public string hourType { get; set; }
public double hours { get; set; }
public int status { get; set; }
public string savedInOlsonTimezone { get; set; }
public double invoicelinevalue { get; set; }
public string articleType { get; set; }
public DateTime dateOfWorkInSavedTimezone { get; set; }
}
public class MyArray
{
public string orderNumber { get; set; }
public string projectnumber { get; set; }
public string noteToInvoicer { get; set; }
public List<object> oracleCosts { get; set; }
public List<OracleHour> oracleHours { get; set; }
}
public class Root1
{
public List<MyArray> MyArray { get; set; }
}
}
Code calling out the JSON:
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string[] GetTime(double fromDate, double toDate, string username)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlNcert), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string url = "";
url = $"{StaticStrings.UrlNcert}?user={username}&fromDate={fromDate:yyyy-MM-dd}&toDate={toDate:yyyy-MM-dd}";
var respons = wc.DownloadString(url);
OracleHour ndata = JsonConvert.DeserializeObject<OracleHour>(respons);
var Get_Odnum = ndata.orderNumber;
var Dt_Work = ndata.dateOfWork;
var hrType = ndata.hourType;
var hr = ndata.hours;
var des = ndata.description;
var surname = ndata.surveyor;
string[] myncertdata = { Get_Odnum, Dt_Work.ToString(), hrType, hr.ToString(), des, surname };
return myncertdata;
}
}
Partial code attempting to connect the corresponding button to retrieve data (the error appears at the very last line):
namespace TimeSheets_Try_11
{
public partial class Form3 : Form
{
WebAPI WA = new WebAPI();
public Form3()
{
InitializeComponent();
webBrowser2.Url = new Uri(StaticStrings.UrlNcert);
}
private void Form3_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'timesDataSet.NCert_Data' table. You can move, or remove it, as needed.
this.nCert_DataTableAdapter.Fill(this.timesDataSet.NCert_Data);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void GtData_Click(object sender, EventArgs e)
{
var connetionString = ConfigurationManager.ConnectionStrings["Times"].ConnectionString;
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
using (SqlCommand Sqlcmd = new SqlCommand("NCert_Data", conn))
{
Sqlcmd.CommandType = CommandType.StoredProcedure;
int counter; string projectnumber; double hrs; string respname; string describe; string[] prjstat; DateTime dates;
for (counter = 0; counter < (dataGridView1.RowCount) - 1; counter++)
{
hrs = 0;
projectnumber = dataGridView1.Rows[counter].Cells[1].Value.ToString();
prjstat = WA.GetTime(projectnumber);
}
}
}
}
}
}
}
public string[] GetTime(double fromDate, double toDate, string username)
needs 3 parameter but
prjstat = WA.GetTime(projectnumber);
has only one...?
Looks like you have to add 2 more parameters
prjstat = WA.GetTime((double), (double), "text");
double fromDate, but you have "projectnumber" a .toString() ...?
Without knowing how the structure of your table looks like there is no way to know what the parameters are. How ever I think your function call should look like this:
prjstat = WA.GetTime((double)dataGridView1.Rows[counter].Cells["fromDate"], (double)(double)dataGridView1.Rows[counter].Cells["toDate"], dataGridView1.Rows[counter].Cells["username"].toString());
Where ["fromDate"], ["toDate"] and ["username"] should be the correct indexes of your expected data.
You may could loop through the cols and output the data with something like that:
for (counter = 0; counter < (dataGridView1.RowCount) - 1; counter++)
{
for (int i = 0; i < dataGridView1.Columns.Count, i++)
{
if (dataGridView1.Columns[i].HeaderText != null) {
System.Console.WriteLine(dataGridView1.Columns[i].HeaderText);
}
System.Console.WriteLine(dataGridView1.Rows[counter].Columns[i].ValueType.ToString());
System.Console.WriteLine(dataGridView1.Rows[counter].Columns[i].Value.ToString());
}
if (counter == 2) { break; }
}
Or just give some dummy values and look what happens ( :P ):
prjstat = WA.GetTime(0, 0, "bla");
Edit: Please note that .Value can be different types like numbers colors dates or what ever. So you have to cast it to a type (double) or use Convert.XYZ. By ValueType.toString() you maybe know what type it is. Or you already know it at all, no idea... ;)
...should pass the date information as well as the signature obtained previously through a second API and retrieve and display information on to a grid data table accordingly.
Well now I'm confused. Could you clarify if you want to store data received by WA.GetTime to dataGridView1 or do you want to send data to WA.GetTime obtained by the dataGridView1?
Btw.: A DataGridView do not "require" an sql database. It can also use xml as example.
Im making an Xamarin.Android application that will use "templates" , template is this:
[Table("Templates")]
public class Template
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Category { get; set; }
//[TextBlob("imagesBlobbed")]
[OneToMany, Unique]
public List<TemplateImage> TemplateImages { get; set; }
public string ImagesHash { get; set; }
//public string imagesBlobbed { get; set; }
}
[Table("TemplateImages")]
public class TemplateImage
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Category { get; set; }
public string ImagesHash { get; set; }
public int Image { get; set; }
[ForeignKey(typeof(Template))]
public int TemplateId { get; set; }
}
i want all the TemplateImages objects to be unique in my database, the attribute Unique doesnt do anything, cause i guess because TemplateImage table has an auto increment Id will always be unique, no matter if the Image or ImageHash is the same in 2 records.
I was thinking then how else i can be sure that TemplateImages will be unique (Notice: when i say unique i mean that there isn't any other List that have the exact Image for every TemplateImage, in the same order).
Also i was using the ResourceID of the images, as image, which is wrong cause they might change on every new compiled app update.
So i decided to make a hash md5 from the images. They only way that i have find to load resource images (my images are vector .xml files) in Xamarin.Android is by converting the resource to bitmap, and then convert the bitmap to byte, and then the byte to md5.
And also i should have a hash string for the template item too. so im creating an md5 hash for the template by combining all the byte[] of the images into one and then hasing that.
I create this crazy code for this job:
public static string GetMD5Hash(byte[] content)
{
using (var md5 = MD5.Create())
{
byte[] computedHash = md5.ComputeHash(Encoding.UTF8.GetBytes(BitConverter.ToString(content).Replace("-", "")));
return new System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary(computedHash).ToString();
}
}
private static SQLiteConnection instance;
public static SQLiteConnection db()
{
if (instance == null)
instance = new SQLiteConnection(System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "TemplatesData.db"));
return instance;
}
public static void CloseConnection()
{
if (instance != null)
{
instance.Close();
instance.Dispose();
instance = null;
}
}
}
public class TemplateDB
{
public static byte[] ConcatByteList(List<byte[]> list)
{
return list
.SelectMany(a => a)
.ToArray();
}
public static Bitmap GetBitmapFromVectorDrawable(Context context, int drawableId)
{
Drawable drawable = ContextCompat.GetDrawable(context, drawableId);
if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.Lollipop)
{
drawable = (DrawableCompat.Wrap(drawable)).Mutate();
}
Bitmap bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth,
drawable.IntrinsicWidth, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
drawable.SetBounds(0, 0, canvas.Width, canvas.Height);
drawable.Draw(canvas);
return bitmap;
}
public byte[] DrawableToByteArray(int resourceId)
{
var context = AppState.ApplicationState;
using (var bitmap = GetBitmapFromVectorDrawable(context, resourceId))
{
int size = bitmap.ByteCount;
byte[] byteArray = new byte[size];
ByteBuffer byteBuffer = ByteBuffer.Allocate(size);
bitmap.CopyPixelsToBuffer(byteBuffer);
byteBuffer.Rewind();
byteBuffer.Get(byteArray);
return byteArray;
}
}
public static void AddTemplate(int category, List<int> images)
{
var templateDB = new TemplateDB();
var imageByteList = new List<byte[]>();
foreach (int image in images)
{
imageByteList.Add(templateDB.DrawableToByteArray(image));
}
var tmpl = new Template()
{
Category = category,
};
var img1 = new TemplateImage()
{
Category = category,
Image = images[0],
ImagesHash = DatabaseHelper.GetMD5Hash(imageByteList[0]),
};
var img2 = new TemplateImage()
{
Category = category,
Image = images[1],
ImagesHash = DatabaseHelper.GetMD5Hash(imageByteList[1]),
};
var img3 = new TemplateImage()
{
Category = category,
Image = images[2],
ImagesHash = DatabaseHelper.GetMD5Hash(imageByteList[2]),
};
var img4 = new TemplateImage()
{
Category = category,
Image = images[3],
ImagesHash = DatabaseHelper.GetMD5Hash(imageByteList[3]),
};
var img5 = new TemplateImage()
{
Category = category,
Image = images[4],
ImagesHash = DatabaseHelper.GetMD5Hash(imageByteList[4]),
};
tmpl.TemplateImages = new List<TemplateImage>() { img1, img2, img3, img4, img5 };
tmpl.ImagesHash = DatabaseHelper.GetMD5Hash(ConcatByteList(imageByteList));
var result = DatabaseHelper.db().Query<TemplateImage>("Select * from Templates where ImagesHash=?", tmpl.ImagesHash);
if (result.Count == 0)
{
DatabaseHelper.db().InsertAll(tmpl.TemplateImages);
DatabaseHelper.db().Insert(tmpl);
DatabaseHelper.db().UpdateWithChildren(tmpl);
}
}
Which all of a sudden, gives out of memory exception.
After thinking for a while that i should stop programming and start belly dancing, i think that since im giving in sqlite AddTemplate function a list of ResourceIds that i have to manually create (can't avoid it), then why not to give them my own string hash code and compare that to find if a record exist?
What is the correct approach?
In the end, i was thinking to use guid as extra id fields and add the parameter unique,in that case i could be sure which templates have been inserted, but i decided to use transactions. With transactions i can know that all my data is created or none and also save the creation into a variable in SharedPreferences and avoid recreating or even checking if the database exist.
For checking if the data is correctly updated and no recreation is needed i used this code:
public bool FirstRun { get; set; } = true;
public int DatabaseCreatedVersionOf { get; set; } = -1;
public override void OnCreate()
{
base.OnCreate();
}
public void UpdateDatabaseCreatedVersion()
{
DatabaseCreatedVersionOf = Preferences.Get(Settings.DatabaseCreatedVersionOfKey,
Settings.DatabaseCreatedVersionOfDefault);
}
public void CreateTemplateDB()
{
UpdateDatabaseCreatedVersion();
if (DatabaseCreatedVersionOf == -1)
TemplateDB.CreateDB();
FirstRun = false;
}
public Template GetTemplateById(int id)
{
if (FirstRun)
{
CreateTemplateDB();
FirstRun = false;
}
return TemplateDB.GetTemplate(id);
}
public List<Template> GetAllTemplates()
{
if (FirstRun)
{
CreateTemplateDB();
FirstRun = false;
}
return TemplateDB.GetAllTemplates();
}
Now all i have to do is call GetTemplateById or GetAllTemplates and if any creation is required, it will happen.
I want to use the ML.Net Kmeans algo but I do not know during compile time the size of the dataset aka the number of features.
I see that the vector type length is supposed to be a const and thus trying to pass as an argument will not work.
class Data
{
public string ID{ get; set; }
[VectorType(5)] //I do not know the if the data will contain 5 or more features
public float[] Features { get; set; }
}
To be used:
InputData row = new InputData { AssetID = Data[0, i + 1].ToString(), Features = features };
var context = new MLContext();
var DataView = context.Data.LoadFromEnumerable(dataArray);
string featuresColumnName = "Features";
var pipeline=context.Transforms.Concatenate(featuresColumnName,"Features") .Append(context.Clustering.Trainers.KMeans(featuresColumnName, clustersCount: NumberClusters));
var model = pipeline.Fit(DataView);
If the dimension of the vector is fixed, you can work around at runtime:
private class SampleTemperatureDataVector
{
public DateTime Date { get; set; }
public float[] Temperature { get; set; }
}
notice this type has not annotations. You can create SchemaDefinition from it, than modify that schema. The initial SchemaDefinition will have the IsKnownSize property set to false. After the modification the Size will be set to the dimension you set it, 3 in this case.
var data2 = new SampleTemperatureDataVector[]
{
new SampleTemperatureDataVector
{
Date = DateTime.UtcNow,
Temperature = new float[] {1.2f, 3.4f, 5.6f}
},
new SampleTemperatureDataVector
{
Date = DateTime.UtcNow,
Temperature = new float[] {1.2f, 3.4f, 5.6f}
},
};
int featureDimension = 3;
var autoSchema = SchemaDefinition.Create(typeof(SampleTemperatureDataVector));
var featureColumn = autoSchema[1];
var itemType = ((VectorDataViewType)featureColumn.ColumnType).ItemType;
featureColumn.ColumnType = new VectorDataViewType(itemType, featureDimension);
IDataView data3 = mlContext.Data.LoadFromEnumerable(data2, autoSchema);
I wrote very simple class, that perfom data access.
It checks if line with that day exist in table and update her or create a new line.
public class DataAccessClass
{
public static DayWeather GetDayWeather(DateTime date)
{
try
{
using (var db = new Context())
{
var query =
(from day in db.DayWeather
where ((DateTime)day.DateOfDay).Date == date.Date
select new DayWeather((short)day.Temperature, (ushort)day.WindSpeed, (ushort)day.Pressure, (ushort)day.Humidity, day.Cloudiness, day.TypeRecip, (DateTime)day.DateOfDay)).First();
return query;
}
}
catch (Exception exp)
{
if (!EventLog.SourceExists("DataAccessSource"))
{
EventLog.CreateEventSource("DataAccessSource", "DataAccessErrorLog");
}
EventLog.WriteEntry("DataAccessSource", exp.Message);
throw new Exception("Problem with data get.");
}
}
public static void SaveDayWeather(DayWeather day)
{
try
{
using (var db = new Context())
{
var existingDay =
(from d in db.DayWeather
where ((DateTime)day.DateOfDay).Date == day.DateOfDay.Date
select d).SingleOrDefault<DayWeather>();
if (existingDay != null)
{
existingDay.Temperature = day.Temperature;
existingDay.WindSpeed = day.WindSpeed;
existingDay.Pressure = day.Pressure;
existingDay.Humidity = day.Humidity;
existingDay.Cloudiness = day.Cloudiness;
existingDay.TypeRecip = day.TypeRecip;
db.SaveChanges();
}
else
{
DayWeather newDay = new DayWeather();
newDay.DateOfDay = day.DateOfDay;
newDay.Temperature = day.Temperature;
newDay.WindSpeed = day.WindSpeed;
newDay.Pressure = day.Pressure;
newDay.Humidity = day.Humidity;
newDay.Cloudiness = day.Cloudiness;
newDay.TypeRecip = day.TypeRecip;
db.DayWeather.Add(newDay);
db.SaveChanges();
}
}
}
It use EF for generate database. The Contex class and class for save look like this:
public class DayWeather
{
public short Temperature { get; set; }
public ushort WindSpeed { get; set; }
public ushort Pressure { get; set; }
public ushort Humidity { get; set; }
public string Cloudiness { get; set; }
public string TypeRecip { get; set; }
public DateTime DateOfDay { get; set; }
public DayWeather(short Temperature, ushort WindSpeed, ushort Pressure, ushort Humidity, string Cloudiness, string TypeRecip, DateTime Date)
{
this.Temperature = Temperature;
this.WindSpeed = WindSpeed;
this.Pressure = Pressure;
this.Humidity = Humidity;
this.Cloudiness = Cloudiness;
this.TypeRecip = TypeRecip;
this.DateOfDay = Date;
}
public DayWeather()
{
}
}
internal class Context : DbContext
{
public DbSet<DayWeather> DayWeather { get; set; }
}
I call this methods by this code:
DataAccessClass.SaveDayWeather(new DayWeather(12, 12, 12, 12, "Yes", "rain", DateTime.Now));
DayWeather day = DataAccessClass.GetDayWeather(DateTime.Now);
Console.WriteLine(day.ToString());
Console.ReadKey();
It should generate new database, but error occurs. In message it write that can`t connect to the SQL Server.
Is somebody know what is wrong?
P.S. Sorry for my bad English.
P.P.S. I added EF by NuGet.
You can manually specify the connection string as follows
using (var db = new Context("connectionString"))
The default constructor looks up a connection string in the web.config with the same name as the derived context class Context.
If it fails to find one it defaults to
Data Source=.\SQLEXPRESS;
or
Data Source=(LocalDb)\v11.0;
depending on the version of sql server you are using.