|
Finally. Thanks for that.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
In this case, you could probably implement the validation by adding a navigation property:
public class Order : IValidateObject
{
public int Id { get; set; }
public int ItemId { get; set; }
public int Quantity { get; set; }
public virtual Item Item { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Quantity % Item.Multiple != 0)
{
yield return new ValidationResult("Quantity not multiple of item", new[] { Quantity });
}
}
} However, you'd need to test to make sure the property was always set.
Alternatively, you could override the ValidateEntity method on your DbContext :
DbContext.ValidateEntity(DbEntityEntry, IDictionary<Object,Object>) Method (System.Data.Entity) | Microsoft Docs[^]
NB: This wouldn't work with EF Core - it no longer tries to validate the entities before saving them. If you wanted to validate the entities before trying to save them, you would have to write your own validation logic - for example:
Improving Model Validation for Entity Framework Core 2.0 | Ballard Software[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello,
I really appreciate some assistance in explaining how to create a collection property of the same class, as in the following example:
public class Person
{
public int PersonId { get; set; }
public int ParentId { get; set; }
public virtual ICollection<Person> People { get; set; }
}
Note: I am using EF-Code First ..
Many Thanks
|
|
|
|
|
That should work if you make the ParentId property nullable.
public class Person
{
public int PersonId { get; set; }
public int? ParentId { get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> People { get; set; }
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I think you don't need the ParentId property. You just need the Person Parent line and EF takes care of setting it up.
Of course, it's been a few years since I did this crap in EF, so YMMV.
|
|
|
|
|
Thank for your response.
I did what you suggested in a resourse class.
public class Resourse
{
public int ResourseId { get; set; }
public int? ParentId { get; set; }
public virtual Resourse Parent { get; set; }
public virtual ICollection<Resourse> Resourses { get; set; }
}
the outcome is that EF created a foreign key dependency Parent_ResourseId .. The Null-able ParentId is just another property, please see the following:
CREATE TABLE [dbo].[Resourses] (
[ResourseId] INT IDENTITY (1, 1) NOT NULL,
[ParentId] INT NULL,
[Parent_ResourseId] INT NULL,
CONSTRAINT [PK_dbo.Resourses] PRIMARY KEY CLUSTERED ([ResourseId] ASC),
CONSTRAINT [FK_dbo.Resourses_dbo.Resourses_Parent_ResourseId] FOREIGN KEY ([Parent_ResourseId]) REFERENCES [dbo].[Resourses] ([ResourseId])
);
so i think i should remove the property ParentId and Rename the Auto Generated Foreign Key to ParentId.
Any Idea on how to do that, maybe fluent Api statement.
Thanks for your help.
|
|
|
|
|
For EF6:
Fluent API - Relationships - EF6 | Microsoft Docs[^]
modelBuilder.Entity<Resource>()
.HasOptional(r => r.Parent)
.WithMany(r => r.Children)
.HasForeignKey(r => r.ParentId);
For EF Core:
Relationships - EF Core | Microsoft Docs[^]
modelBuilder.Entity<Resource>()
.HasOne(r => r.Parent)
.WithMany(r => r.Children)
.HasForeignKey(r => r.ParentId);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
ICollection is implemented by List. You can create your list with:
public virtual ICollection<Person> People {get;set;} = new List<Person>();
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Ok solved this, by implementing
modelBuilder.Entity<Book>()
.HasMany<Book>(g => g.Books)
.WithRequired(s => s.Parent)
.HasForeignKey<int?>(s => s.ParentId);
thanks for your help.
|
|
|
|
|
I have a txtSearch and btnSearch and i have a web browser. a webrowser have a Textbox1 in element and a Button1. Is that possible, once i entered a value in txtsearch automatically inputted to the Textbox1 in web browser. and lastly how to avoid to clear the value in txtSearch once the webbrowser refreshing.
Thanks in advance
Code below is working for automatically click the button in web browser once click the BtnSearch.
private async void BtnSearch_Click(object sender, RoutedEventArgs e)
{
HTMLDocument doc = (HTMLDocument)MyWebBrowser.Document;
HTMLInputElement btnsearch = (HTMLInputElement)doc.all.item("Button1", 0);
btnsearch.click();
}
|
|
|
|
|
Hi , I have here an ping application implemented as a console application.
I want to turn this into a continuous ping application. Can someone give me a tip how to change this code so it runs continuously.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.NetworkInformation;
namespace PingAppConsole
{
class Program
{
static void Main(string[] args)
{
string host, data;
byte[] buffer;
int timeout;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
data = "Rodham street";
buffer = Encoding.ASCII.GetBytes(data);
timeout = 120;
host = "www.google.no";
PingReply reply = pingSender.Send(host, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine(" Ping communication status for {0}:", host);
Console.WriteLine(" ------------------------------------------");
Console.WriteLine(" Address: {0}", reply.Address.ToString());
Console.WriteLine(" RoundTrip time (mSec): {0}", reply.RoundtripTime);
Console.WriteLine(" Time to live: {0}", reply.Options.Ttl);
Console.WriteLine(" Dont fragment: {0}", reply.Options.DontFragment);
Console.WriteLine(" Buffer size: {0}", reply.Buffer.Length);
Console.WriteLine(" ------------------------------------------");
}
else
{
Console.WriteLine(" Error connecting to network address/name {0}", host);
}
Console.WriteLine(" Press CR or Enter to Quit the application");
Console.ReadLine();
}
}
}
|
|
|
|
|
put an infinite loop around the ping call
while ( true ) {
PingReply reply = pingSender.Send(host, timeout, buffer, options)
else
{
Console.WriteLine("Error ... ");
}
}
Not sure if you could ever break out of that, though. You'd probably want to reduce that to one line of output, similar to what you get from ping from the command prompt. Oh, and you'll probably want to add a delay at the bottom of the loop so you don't flood the network with ping requests. Thread.Sleep() seems like a good option.
|
|
|
|
|
Thanks
Is there a way I can check all the nodes in the network and also get the number of the nodes in my network segment?
|
|
|
|
|
It used to be that most nodes on a lan would respond to a broadcast ping, but most systems do not do so any longer. Many hosts also employ firewalls to block pings. And firewalls can be used to block all connections except from certain hosts, or maybe even all incoming connections.
If all your nodes are connected through a simple hub, then you might be able to sniff packets on the wire and see what the source and destination nodes are. If you're using smart switches then the switch might only forward packets between the ports the nodes are attached to, so you might not see packets.
So there's not any good way to do that. There's only the brute force approach, a la Windows | Nmap Network Scanning.
Be aware that scanning networks where you do not have permission to do so is not advised. Its not unlike someone going around the outside of your hose checking to see if any of your doors or windows are openable. There might not be any intent to create mischief, but it certainly looks like you're trying to break in!
|
|
|
|
|
Ok thanks. If you would write pseudocode for it, how would it look like based on my initial code?
|
|
|
|
|
Use a Timer. Call your routine from the Timer's Tick event. Disable / enable the Timer each time you handle the event to avoid reentrancy with short intervals. Though with a timer and status reporting, I would probably use a Windows app instead of a Console app.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Hi!
I have a question regarding the topic I mentioned in the subject.
I am trying to process numbers (voltage values) and print them nicely on the user interface of my software. What I do now is that I manually code everything. I have 8 different values and I do the following:
Label1.Text = value1.ToString("0.###") + " V";
Label2.Text = value2.ToString("0.###") + " V";
.
.
.
Label8.Text = value8.ToString("0.###") + " V";
"
It works, and everything, but I wonder if there is an elegant solution which runs through the labels and the variables at the same time? And also, is it faster in the more elegant way?
And I have another question related to the code above. Let's say, these values are smaller than 1. In that case, it would be nicer to print the voltage in milivolts, so we see the digits in a more convenient way. For that, my idea would be a simple if-else statement:
if(value1<1.0)
{
Label1.Text = (1000*value1).ToString("0.###") + " mV";
}
else
{
Label1.Text = value1.ToString("0.###") + " V";
}
But, the problem is similar as the first part of the problem. Should I go through each of these cases manually by writing 8 if-else statements for each values, or there is a better (faster), more elegant way?
My code is starting to have a lot of if-else statements because of similar things (for example, checking the state of check boxes) and I start to think whether it has a negative impact on the performance or not?
Thank you very much for your input!
|
|
|
|
|
You could put the values in a list or array and use a simple loop to format them. You may also need another array to contain all the label references.
|
|
|
|
|
Thank you, I continued along this idea. I looked up how to create lists and I put everything in their corresponding lists. The code looks more clean now.
|
|
|
|
|
My vote for list v array is to use an array. Populating it is, then, very simple
Label[] labels = [ label1, label2, ..., label8 };
The original message asked about performance. Forget about performance unless you get noticeable slowness. Your original method probably runs fastest, but it leads to lengthy hard to maintain code. Using lists or arrays makes it much easier to work with, very easy to modify for adding new labels etc, and the difference in performance is not going to be noticeable (unless you have thousands of labels, in which case you would use a different method).
|
|
|
|
|
I think this message was meant for the OP.
|
|
|
|
|
I agree with Richard: have an array.
It might be worth doing it this way:
Create a class to hold the value and it's associated label. You can then create an array or other collection of class instances, and just loop through them, doing the same code once.
To help with that, override the ToString method in the class, and have it return the "human readable" value:
public class DisplayValue
{
public double Value { get; set; }
public Label Label { get; set; }
public override string ToString()
{
return Value < 1.0 ? (1000 * value).ToString("0.###") + " mV"
: Value.ToString("0.###") + " V";
}
}
That way, it can be rather more flexible than just setting a label value.
foreach (DisplayValue dv in Values)
{
dv.Label.Text = dv.ToString();
}
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thank you for the very detailed response, I really appreciate it!
I made it with lists at this moment, just to clean up the code and test if I am able to do it. So far, it works, but I create a new branch for the code where I implement your solution.
|
|
|
|
|
Would be a good candidate to create a custom control; one that exposes the value, and has a dropdownlist to select the desired unit/multiplier for visualization purposes (meaning, without overwriting the value it is showing for editing).
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Thank you, this is a good idea! However, I only have either Volts or miliVolts, so I don't know if it is necessary to create a dropdown list just for two different units. But, when there's a broader range, I think it is a very good approach!
|
|
|
|