|
There are clever ways to do this, and they are overkill.
You could use Tuple voodoo in C#7; you may have round-off errors with floating-point numbers, if you do some maths trickery.
Stand up in class and tell the instructor using a temp variable is the right thing !
Be sure and give your instructor the link to this story: [^]
cheers, Bill
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
Dear fellow C# programmers.
I am trying to model a command that I will send to a product. The command payload consists of:
Header (byte)
Command (byte)
Length (byte)
Data (byte[])
Checksum (byte[2])
Now, the values for the header and command are always static for a particular function. The user only needs to change the data directly.
Indirectly, the Length and Checksum properties will change, but I have written methods which automatically calculate these upon any change of Data.
My idea is I can define a set of these commands as a template to accommodate all the different functions. The user can then use the commands, setting their own data as necessary.
When a user "uses" a command, I don't want them to change the Data property in the template commands. I want the user to create a clone of the command, such that when they change the Data property then these changes are only present in their local instance of the command.
I thought I understood that I could model the command as a struct, so that each command would be a "value type".
Then, when I do:
Command DestroyProduct = new Command(byte header, byte command, byte[] data);
...
...
Command LetOutMagicSmoke = new Command();
LetOutMagicSmoke = DestroyProduct;
LetOutMagicSmoke.Data = new byte[] {0x00, 0x01, etc};
Then the changes to Data are only present in LetOutMagicSmoke and not in DestroyProduct.
This is not how the code is behaving. Instead, changes made to LetOutMagicSmoke.Data are also made to the template command.
The only explanation I can think of is that since byte[] is a reference type, then when I say LetOutMagicSmoke = DestroyProduct; the byte arrays are copied by reference.
This is not the behaviour I want!
My next idea is to put some code in the 'getter' for the Command which iterates over the byte array, extracting out all the bytes, and then putting them into a new byte array, before returning the command to the user.
I haven't implemented that yet but I would like to get my understanding of this issue hashed out first.
Have I understood what is going on correctly? Is my next idea the best way forwards?
Many thanks.
|
|
|
|
|
Arrays of anything are always reference types, even if the base element is a value type. So when you copy the struct, you will copy the reference. Take a simple struct:
private struct MyStruct
{
public char X;
public int[] Ia;
public MyStruct(char x, int[] ia)
{
X = x;
Ia = ia;
}
}
MyStruct ms1 = new MyStruct('1', new int[1] {101});
MyStruct ms2 = ms1;
Console.WriteLine("{0}:{1}", ms1.X, ms1.Ia[0]);
Console.WriteLine("{0}:{1}", ms2.X, ms2.Ia[0]);
Understandably, you get:
1:101
1:101 But, they are independent from that point on:
MyStruct ms1 = new MyStruct('1', new int[1] {101});
MyStruct ms2 = ms1;
Console.WriteLine("{0}:{1}", ms1.X, ms1.Ia[0]);
Console.WriteLine("{0}:{1}", ms2.X, ms2.Ia[0]);
ms2.Ia = new int[1] { 202 };
Console.WriteLine("{0}:{1}", ms1.X, ms1.Ia[0]);
Console.WriteLine("{0}:{1}", ms2.X, ms2.Ia[0]);
Will give you
1:101
1:101
1:101
1:202 As you would expect.
But you can't expect the copy to create new reference objects becasue the new keyword is never used:
MyStruct ms1 = new MyStruct('1', new int[1] {101});
MyStruct ms2 = ms1;
Console.WriteLine("{0}:{1}", ms1.X, ms1.Ia[0]);
Console.WriteLine("{0}:{1}", ms2.X, ms2.Ia[0]);
ms2.Ia[0] = 202;
Console.WriteLine("{0}:{1}", ms1.X, ms1.Ia[0]);
Console.WriteLine("{0}:{1}", ms2.X, ms2.Ia[0]);
Will give you what you are seeing:
1:101
1:101
1:202
1:202 Because arrays are reference types and the struct copy will copy the reference to the array - which is exactly what it should do!
What you are looking for is a deep copy of the struct, which is not possible using "normal" operations - that's why structs should be immutable! Choosing Between Class and Struct | Microsoft Docs[^]
Quote: CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
AVOID defining a struct unless the type has all of the following characteristics:
It logically represents a single value, similar to primitive types (int, double, etc.).
It has an instance size under 16 bytes.
It is immutable.
It will not have to be boxed frequently
This may help: Using struct and class - what's that all about?[^]
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
This is an excellent response for which I appreciate that you have taken considerable time to formulate. Thank you for passing on your understanding to me Mr.OriginalGriff!
|
|
|
|
|
You're welcome!
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi Coders
i'm trying to create an discussion forum similar to msdn-forum/code-project forum in my asp.net Application.
How to do it.
Please help
|
|
|
|
|
The first step is to decide on your requirements. Do a lot of research. Ask a lot of questions. Only when you know exactly what it is you're planning on building should you start actually attempting to write any code. At that stage, feel free to come back and ask questions BASED ON THE CODE that you have. We're not going to just give you code; that's not the way this site works. For a start, we don't know exactly how you plan to use the forums so any code we gave would be making assumptions.
This space for rent
|
|
|
|
|
hello I'm learning c # language. I want to make my own mail program in visual studio. I want to get the design of this mail program like in windowsmail. Can you help me with this design? now thanks.
|
|
|
|
|
Not really, no - this is your homework, not ours!
So start at the beginning and decide what exactly you want it to do and when, and then decide how you want it to look. Write yourself a specification based on that - the more detailed, the better.
From the spec, look at breaking it into modules, or even layers: Presentation for the UI, Business for the rules, Data access for the actual email send and receive. Work out what goes in each layer, and how the layers interact.
Then start working on each layer as a separate project within the same solution, and design that and how it will work.
You can then begin coding, testing, changing the design, changing the spec, and repeating until you are finished!
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hmm, I should really try that some time.
|
|
|
|
|
You do - but you've been at it often enough that most of the stages are mental for you these days!
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi, I am trying to upload an Excel file by passing excel data as User Defined Datatype to a stored Procedure using Entity Framework and C# Code in an ASP.Net Application as below:
public System.Int32 UploadServiceProgram(List<ServicePrograms_Upload> serviceProgList, string Fiscal_Period_Code, string CreatedBy)
{
DataTable serviceProgramDataTable = new DataTable();
serviceProgramDataTable.Columns.Add("ServiceCode", typeof(string));
serviceProgramDataTable.Columns.Add("ProgramCode", typeof(int));
serviceProgramDataTable.Columns.Add("UnitTypeDesc", typeof(string));
serviceProgramDataTable.Columns.Add("RateCap", typeof(decimal));
serviceProgramDataTable.Columns.Add("CountyCode", typeof(string));
foreach (var item in serviceProgList)
{
serviceProgramDataTable.Rows.Add(item.Provided_Service_Code, item.Program_Code, item.Unit_Type, item.Rate_Cap);
}
var parameter = new SqlParameter("@ServiceProgram", SqlDbType.Structured);
parameter.Value = serviceProgramDataTable;
parameter.TypeName = "dbo.ServicePrograms_UDT";
var parameter2 = new SqlParameter("@Fiscal_Period_Code", SqlDbType.NVarChar, 15);
parameter2.Value = Fiscal_Period_Code;
var parameter3 = new SqlParameter("@CreatedBy", SqlDbType.NVarChar, 50);
parameter3.Value = CreatedBy;
using (var context = new CRSContext())
{
context.Database.CommandTimeout = 360000;
var result = context.Database.SqlQuery<int>("usp_Upload_ServicePrograms @ServiceProgram, @Fiscal_Period_Code, @CreatedBy", parameter, parameter2, parameter3).FirstOrDefault();
return result;
}
}
It is failing for some reason, but the same Excel file I have exported into a Table, then creating a Table Variable of type (the User Defined Type) that I am using then inserting into that Table variable from the Table that I have Excel data in, then executing the Stored Procedure is not failing actually importing the Data as it is, I am not sure why the Stored Procedure executes but the above method fails, in both the cases Stored Procedure and Excel are the same. Here is how I am executing the Stored Procedure:
declare @ServiceProgram ServicePrograms_UDT
declare @fiscalPeriod nvarchar(15)='FY 2016-2017', @CreatedBy nvarchar(50)='aaleemmo'
insert into @ServiceProgram(ServiceCode, ProgramCode, UnitTypeDesc, RateCap, CountyCode)
select [service code], [Program Code], [Unit Type], [Rate Cap], [County Code] from SUDCRS..zzServiceProgramCountyExcelData
exec dbo.usp_Upload_ServicePrograms @ServiceProgram, @fiscalPeriod, @CreatedBy
And one more doubt I have is, when my WCF Service is posting this huge excel data as datatable to the Database, would it lose the Data when it is posting huge data, if it is losing that, is there any other approach I can execute this stored procedure.
Please let me know anything that's possible, a suggestion, a code snippet or even a tiny suggestion, any thing helps, its little bit urgent - please, thanks a lot.
|
|
|
|
|
DO NOT repost the same question over and over. You posted this in the QA forum 22 hours ago.
|
|
|
|
|
Sorry I thought these two are considered differently and I was not able to delete that one before posting here. I don't know, is there a way to delete QA posts, if there is can you please let me know how?
|
|
|
|
|
OK, thanks...
I`m failing to write to the data field, in the original Python code the method is GET and still i see data on the request data field but on the C# code I’m not sure how to get the same capture, im getting something like this, where my data (the commands to the remote system) been attached to the header:
GET /loadinst.cgi <EEX Ver='1.0'><CMD ....
Host: xxx.xxx.xxx.148
Accept-Encoding: identity
and the data field is empty, so the remote instrument refuse the connection.
So my question is what is the C# implementation to get something like this:
Hypertext Transfer Protocol
GET /loadinst.cgi HTTP/1.1\r\n
Host: xxx.xxx.xxx.148\r\n
Accept-Encoding: identity\r\n
Content-Length: 119\r\n
\r\n
[Full request URI: http:
[HTTP request 1/1]
[Response in frame: 30]
File Data: 119 bytes
Data (119 bytes)
Data: <EEX Ver='1.0'><CMD...
[Length: 119]
thanks for the help...
|
|
|
|
|
Uhhh...I think you posted this reply to the wrong thread. It has nothing to do with the question that was asked.
|
|
|
|
|
Sorry.. posted in the wrong place...
|
|
|
|
|
Yeah I haven't got any reply in both the forums buddy, any help my friend?
|
|
|
|
|
Nope. I don't use UDTs let alone use them with EF.
|
|
|
|
|
Is that a bad Combination buddy?
|
|
|
|
|
|
am using this code inside insert method
Insert into table (startdate) values (DateTime.ParseExact(Startdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture))
i have textbox and want to insert null value
|
|
|
|
|
There are a couple of things here:
1) Text boxes don't contain NULL values - they can contain empty strings, but that is a very different thing.
2) ParseExact will fail if the string doesn't match - which means you must either use a try...catch block, or better use TryParseExact instead, reporting a problem to the user instead of trying to pass anything to the DB.
3) What you show won't work: even if it did what you think, it would pass the string version to SQL via concatenation, and that really should be avoided as it makes SQL convert the string back to a DateTime and that can introduce errors.
So verify the TB at the start of the method, and pass DateTime or NULL like this:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO myTable (startDate) VALUES (@SD)", con))
{
object o;
if (string.IsNullOrWhitespace(Startdate.text)) o = DbNull.Value;
else o = valueConvertedToDateTimeEarilerWhenYouValidatedIt;
cmd.Parameters.AddWithValue("@SD", o);
cmd.ExecuteNonQuery();
}
}
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I have 8000 records i want put server side pagination and search
|
|
|
|
|
|