|
<pre lang="c#"> plese help me solve this problem i am trying to make a auto fill button by using 3 layer architecture in asp.net c# on windows form
<pre>BELayer:
public string quantity { get; set; }
public string prod_id { get; set; }
public string party_id { get; set; }
DALayer page code:
public SqlDataReader autofillparty_id(BEL beobj)
{
try
{
cmd = new SqlCommand("select * from product where prod_id='" + beobj.prod_id + "'", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spsearchpartyid";
cmd.Parameters.AddWithValue("@prod_id", beobj.prod_id);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return sdr;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
BALayer code
public SqlDataReader autofillquantity(BEL beobj)
{
try
{
return daobj.autofillparty_id(beobj);
}
catch (Exception ex)
{
throw ex;
}
}
Main Page code::
private void button1_Click(object sender, EventArgs e)
{
if (baobj.autofillquantity(beobj).Read())
{
txtboxpartyidquant.Text = (beobj.party_id.ToString());
}
}
this code is not working i know problem is in my main page but i don't know how can i solve this problem please help me ...
|
|
|
|
|
Look, it really doesn't matter where you post this: as long as you are not listening to us, you will still be vulnerable to sQL injection.
So I'll say it for the third time in two days:
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.
When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood' The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable; Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x'; A perfectly valid SELECT
DROP TABLE MyTable; A perfectly valid "delete the table" command
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.
So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
If you don't listen to what we tell you, there really isn't any point in talking to you ...
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi,
What is the correct way to do Business Validation on entities with Entity Framework 6. By business Validation I mean validation that require more than one entity in process with, sometime, a little more complex rules that involve all these entities. A validation that require the system to call he database.
I already checked this post:
ScottGu's Blog - Class-Level Model Validation with EF Code First and ASP.NET MVC 3
But, like most example about EF and validation all validations are limited to simple check that consider only the current entity. I need to do some check based on other entities.
Example: I have a order entity that contain a quantity of product but this quantity must be a multiple of a variable stored in my item entity. This is what I call the business validation. To perform this validation on order I need to go in database and check the item selected for this order.
public class Order : IValidateObject
{
public int Id { get; set; }
public int ItemId { get; set; }
public int Quantity { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var item = DbContext.Items.Find(ItemId);
if (Quantity % item.Multiple != 0)
yield return new ValidationResult("Quantity not multiple of item", new[] {Quantity});
}
}
public class Item
{
public int Id { get; set; }
public int Multiple { get; set; }
}
How should I implement this kind of business validation that require other entities? I'm more looking for a good tutorial about this subject. I search but each time I think I find the subject the tutorial is limited to classic validation with Data Annotation or other type of classic validation.
Maybe you will juste tell me there is no problem to class my context in the Validate method. It is just that most of tutorial separate the entity layer from the context layer suggesting entities must only be simple POCO with no behavior. I most and most disagree with this but I feel alone.
|
|
|
|
|
The "Enumerable" makes no sense. "Validation" is an all or nothing proposition. If you want to return multiple error / messages, return a list. If the list is "empty", you might consider things valid and then do a "save".
Other than that, you've provide no information about the environment: online, batch, whatever.
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
|
|
|
|
|
|
So, instead of "one" call, he does multiple calls to get all the errors "because there may be multiple properties". Sorry, I fail to see the connection. The interface is at the "class level", not the property level.
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
|
|
|
|
|
No, there's one call to get the list of validation errors. Each error can be associated with one or more properties, by specifying the member names in the ValidationResult .
The interface is designed for validation rules on a class which need access to other properties of the class. Validation attributes on a property only get access to that property's value. That's fine for simple validation rules like "required" or "greater than zero", but it doesn't work for things like "confirm password must be equal to password".
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Still doesn't answer why an enumerable is "better" than a list in this case. All you're doing is trading a yield for an Add (and making it more complicated for some … as indicated by OP's post).
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
|
|
|
|
|
The interface defines the method as returning IEnumerable<ValidationResult> .
If you wanted to return a List<ValidationResult> instead of using an iterator method, you could certainly do that. But I don't see how it would make things significantly simpler.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Gerry Schmitz wrote: Still doesn't answer why an enumerable is "better" than a list in this case. No one ever said it is "better".
This is just how the interface is built. Implementers are free to return whatever they want, provided it implements IEnumerable .
"Five fruits and vegetables a day? What a joke!
Personally, after the third watermelon, I'm full."
|
|
|
|
|
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?
|
|
|
|