|
It may be worth pointing out that as the code stands Port interface has no access to FooData1 or FooData2.
public class Foo : Foo.Port
{
private Foo() { }
public int FooData1 { get; set; }
public int FooData2 { get; set; }
public interface Port
{
static Port Default = new Foo();
protected int FooData1 { get; }
protected int FooData2 { get; }
static (int, int) Action()
{
return (Default.FooData1, Default.FooData2);
}
}
}
Now we have access to FooData1 and FooData2. Foo is private and the only instance of Foo or Port is Foo.Port.Default and we can access it as such.
var bar = Foo.Port.Default;
var foobar = (Foo)bar;
foobar.FooData1 = 10;
foobar.FooData2 = 20;
Console.WriteLine(Foo.Port.Action());
If we want more than the single instance of Foo we need a Clone() method in Foo which can be easily done like this.
public object Clone()
{
var (X, Y) = Foo.Port.Action();
return new Foo()
{
FooData1 = X,
FooData2 = Y
};
}
modified 10hrs 10mins ago.
|
|
|
|
|
Console.WriteLine doesn't write to the debugger Output window in .NET 8.
It always works in the .NET Framework, but not in the new .NET.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
|
Ah! Makes sense. Thanks!
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Hi
I need to make a game using window form in c#
just an example
thx.
|
|
|
|
|
|
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.
So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.
Just saying "I wanna write a game" doesn't help anyone!
If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
bool playing = true;
public Form1()
{
InitializeComponent();
}
private Button[] Cells => new Button[]
{
button1,
button2,
button3,
button4,
button5,
button6,
button7,
button8,
button9
};
private bool IsBoardFull
{
get
{
bool result = true;
foreach (Button btn in Cells)
{
if (btn.Enabled) { result = false; break; }
}
return result;
}
}
private bool IsThreeInRow
{
get
{
if (Cells[0].Text == "X" && Cells[1].Text == "X" && Cells[2].Text == "X" ||
Cells[0].Text == "O" && Cells[1].Text == "O" && Cells[2].Text == "O" ||
Cells[3].Text == "X" && Cells[4].Text == "X" && Cells[5].Text == "X" ||
Cells[3].Text == "O" && Cells[4].Text == "O" && Cells[5].Text == "O" ||
Cells[6].Text == "X" && Cells[7].Text == "X" && Cells[8].Text == "X" ||
Cells[6].Text == "O" && Cells[7].Text == "O" && Cells[8].Text == "O" ||
Cells[0].Text == "X" && Cells[3].Text == "X" && Cells[6].Text == "X" ||
Cells[0].Text == "O" && Cells[3].Text == "O" && Cells[6].Text == "O" ||
Cells[1].Text == "X" && Cells[4].Text == "X" && Cells[7].Text == "X" ||
Cells[1].Text == "O" && Cells[4].Text == "O" && Cells[7].Text == "O" ||
Cells[2].Text == "X" && Cells[5].Text == "X" && Cells[8].Text == "X" ||
Cells[2].Text == "O" && Cells[5].Text == "O" && Cells[8].Text == "O" ||
Cells[0].Text == "X" && Cells[4].Text == "X" && Cells[8].Text == "X" ||
Cells[0].Text == "O" && Cells[4].Text == "O" && Cells[8].Text == "O" ||
Cells[2].Text == "X" && Cells[4].Text == "X" && Cells[6].Text == "X" ||
Cells[2].Text == "O" && Cells[4].Text == "O" && Cells[6].Text == "O")
return true;
return false;
}
}
private IEnumerable<Button> PossibleMoves()
{
return Cells.Where((button) => button.Enabled);
}
private void CheckForWinner()
{
string draw = "Sorry, it was a draw.";
string playAgain = "Another Game?";
string sorry = "Sorry, you lost.";
string congrats = "Congratulations, you won.";
if(IsThreeInRow)
{
string state = playing ? congrats : sorry;
DialogResult dialogResult = MessageBox.Show(
state, playAgain, MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
ResetGame();
return;
}
Close();
}
else if(IsBoardFull)
{
DialogResult dialogResult = MessageBox.Show(
draw, playAgain, MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
ResetGame();
return;
}
Close();
}
}
private void Cell_Click(object sender, EventArgs e)
{
if (!playing) return;
Button btn = (Button)sender;
if(string.IsNullOrEmpty(btn.Text))
{
PerformMove(btn);
return;
}
}
private void PerformMove(Button btn)
{
if(playing)
{
btn.Text = "X";
btn.Enabled = false;
CheckForWinner();
playing = false;
ComputerPlay();
return;
}
btn.Text = "O";
btn.Enabled = false;
CheckForWinner();
playing = true;
}
private void ResetGame()
{
foreach(Button btn in Cells)
{
btn.Text = null;
btn.Enabled = true;
}
}
private void ComputerPlay()
{
if (playing) return;
var possibleMoves = PossibleMoves();
int index = new Random((int)DateTime.Now.
Ticks).Next(0, possibleMoves.Count());
Button btn = possibleMoves.ElementAt(index);
PerformMove(btn);
}
|
|
|
|
|
How do I check for existance or clear the contents of a SharePoint List from C# code?
I have complete the code that creates a sharepoint List from scratch, creates the columns, and loads the data that I get from an API GET query of an external database.
How do I:
check and see if the SharePoint List already exists
clear the contents of the sharepoint list
load the list with new data.
Without doing these steps, I am left with creating the list from scratch each time and giving it a unique name each time.
Is there some source of information on how to do this that I can find online? The Microsoft AI chat bot has given me some code that does not work at all.
|
|
|
|
|
|
Hi Charles,
I sure can. Editing it or presenting it in such a way where company information is no there is going to take time. The code first assumes it is creating the list for the first time and when an exception is thrown if the list already exists, it just loads the list. Here is the code
string listTitle = "TripLegs" ;
string listDescription = "This is a new list created using CSOM";
Microsoft.SharePoint.Client.List? newList = null;
Next, we use the "using" method and start a block like this:
using (var authenticationManager = new AuthenticationManager())
using (var context = authenticationManager.GetContext(site, user, password))
{
context.Load(context.Web, p => p.Title);
await context.ExecuteQueryAsync();
Console.WriteLine($"Title: {context.Web.Title}");
Web web = context.Web;
ListCreationInformation creationInfo = new ListCreationInformation();
creationInfo.Title = listTitle;
creationInfo.Description = listDescription;
creationInfo.TemplateType = (int)ListTemplateType.GenericList;
newList = web.Lists.Add(creationInfo);
THis is when the try catch block is used if an exception is NOT thrown, then we assume that we are dealing with a list that has not been created yet and the use of the ListCreationInformation class is the proper thing to do. The code in the "TRY" block proceeds to create the columns.
try
{
context.Load(newList);
context.ExecuteQuery();
Console.WriteLine("List created successfully!");
FieldCollection fields = newList.Fields;
#region ColumnHeaders
<pre> FieldCreationInformation fieldInfo_1 = new FieldCreationInformation(FieldType.Number)
{
DisplayName = "TripId",
InternalName = "TripId",
Group = "Custom Columns",
AddToDefaultView = true
};
string fieldSchema_1 = $"<Field Type='{fieldInfo_1.FieldType}' Name='{fieldInfo_1.InternalName}' DisplayName='{fieldInfo_1.DisplayName}' Group='{fieldInfo_1.Group}' />";
Field Field_1 = newList.Fields.AddFieldAsXml(fieldSchema_1, true, AddFieldOptions.DefaultValue);
Field_1.Update();
context.ExecuteQuery();
then the code generates all the columns. The example I just posted shows the creation of just the first column.
So, now we get to the Catch block which would be executed if the list already exists and we just need to access it in order to load the already existing list
}
catch (Exception ex)
{
After this is some JSON code that deals with the parsing of the code to put in the list which I am intentionally leaving out. But the code is put into a class and then from the class, it is loaded into the Sharepoint List like this:
Legs singleTripLeg = JsonSerializer.Deserialize<Legs>(inputLegsJSON);
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem newItem = newList.AddItem(itemCreateInfo);
newItem["TripId"] = singleTripLeg.TripId;
newItem["ExternalReference"] = singleTripLeg.ExternalReference;
newItem["DepartureAirportId"] = singleTripLeg.DepartureAirportId;
newItem["ArrivalAirportId"] = singleTripLeg.ArrivalAirportId;
newItem["LandedLocal"] = singleTripLeg.LandedLocal;
newItem["LandedPinned"] = singleTripLeg.LandedPinned;
newItem.Update();
context.ExecuteQuery();
So there you have it.
Now I need to know the call to clear out the SharePoint List before I load it.
|
|
|
|
|
|
using locks, from my understanding this should work as long as lock is being called on the same object.
internal static async Task Lock<T>(this T lockObject, Action DoAction) where T : class
{
await Task.Run(() => { lock(lockObject)
{
DoAction();
}});
}
|
|
|
|
|
From what I can see, the code you've provided isn't going to achieve what you might expect it to achieve. I'm going to break the logic down so you can see where the confusion lies.- The await operator here does not appear to affect the locking behaviour. It's only waiting for the Task.Run to complete.
- Inside the
Task.Run , we have a lock statement. You can think of this as running on a different thread from the caller. - Each call to this method will create a new task, which will attempt to acquire the lock independently.
The end result is multiple calls to this method could run concurrently, each in its own task, defeating the purpose of the lock. The lock will still work within each individual task, but it won't prevent multiple tasks from running simultaneously. To my mind, a better version of this would be this:
private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
internal static async Task Lock<T>(this T lockObject, Action DoAction) where T : class
{
try
{
await _semaphore.WaitAsync();
DoAction();
}
finally
{
_semaphore.Release();
}
}
|
|
|
|
|
Thanks for the hint on the using the SemaphoreSlim. This works much better than the original extension I was using.
|
|
|
|
|
From what I can see, it should work. Whilst held, the lock prevents any other thread from obtaining the lock. And the thread that's holding the lock never* yields, so nothing else can be run on the same thread.
(* Assuming DoAction doesn't do anything odd, such as point to an async void method.)
But wouldn't it be better to use a proper async-friendly lock instead?
Building Async Coordination Primitives, Part 6: AsyncLock - .NET Parallel Programming[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Within the DoAction() it performs read/write operations on a memory pointer
|
|
|
|
|
This is how the lock is being used.
public async Task<short[]> GetSamples()
{
if (!ContainsAudio())
throw new ArgumentException(nameof(G711.Alaw));
short[] samples = [];
NativePointer pointer = _nativePointer!;
await pointer.Lock(() =>
{
unsafe
{
var sampleCount = pointer.Size >> 1;
samples = new short[sampleCount];
var memoryBlock = pointer.GetMemoryBlock();
var value = (short*)memoryBlock;
for (var i = 0; i < sampleCount; i++)
{
samples[i] = *value++;
}
}
});
return samples;
}
|
|
|
|
|
I have a dot net 8.0 C# DLL project that holds a reference to a C++ .net 8.0 mixed mode DLL project.
Whenever the mixed mode project is rebuilt, then none of the projects that depend upon it will load the previous build of the mixed mode DLL. It gives a library version not found error if I try to run the previous build.
This is annoying because this happens whenever the mixed mode DLL is rebuilt, even if there are zero code changes in that project.
Just where do you think Visual Studio is managing this auto-incrementing build number that is disrupting my development feng shui?
When I open the Properties dialog for the mixed mode DLL, I can't find anything that looks like it implements an auto-incrementing build number. Remember, this would be the Properties window that is presented for native projects, not dot net projects.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
If I understand the question correctly it is not a 'version number'
A dll has a header that describes the contents. That includes things like a version number but it also includes the code type which is something like '32bit', '64bit' and 'any'. There are other thinks in there like the full name, encryption info, etc.
I think the following page discusses some of this.
PE Format - Win32 apps | Microsoft Learn[^]
|
|
|
|
|
Yes, but it would refuse to load the DLL even if there were no code changes or assembly property changes.
I think I have solved it however. There is a file in the DLL project named AssemblyInfo.cpp, and it contains an assembly attribute named AssemblyVersionAttribute. And it was set to L"1.0.*". I think this was causing the problem. The asterisk means that it should autoincrement the version number.
I changed the value to L"1.0.0" and it no longer fails to load the DLL if the DLL is rebuilt.
Thanks for reading my post and for your input!
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I've been trying to convert ulaw to alaw following a few examples that I found online. I'm able to covert the alaw to ulaw quite well but when converting back to alaw the output becomes distorted. If anyone knows a better solution please do share. Here is the code that is producing the distorted alaw.
public static NativePointer Encode(G711.Ulaw ulaw)
{
if (ulaw == null || !ulaw.ContainsAudio()) throw new Exception(nameof(ulaw));
List<byte> bytes = [];
NativePointer pointer = ulaw._nativePointer!;
byte[] result = new byte[pointer.Size];
Marshal.Copy(pointer, result, 0, pointer.Size);
foreach(byte byt in result)
{
bytes.Add(LinearToALawSample(MuLawToLinearSample(byt)));
}
return new(bytes);
static byte LinearToALawSample(short pcm_val)
{
int mask;
int seg;
byte aval;
if (pcm_val >= 0)
{
mask = 0xD5;
}
else
{
mask = 0x55;
pcm_val = (short)-pcm_val;
if (pcm_val > EncoderInfo.ALAW_MAX)
{
pcm_val = EncoderInfo.ALAW_MAX;
}
}
if (pcm_val < 256)
{
aval = (byte)(pcm_val >> 4);
}
else
{
seg = 1;
for (int i = pcm_val; i > 256; i >>= 1)
{
seg++;
}
aval = (byte)((seg << EncoderInfo.SEG_SHIFT) | ((pcm_val >> (seg + 3)) & EncoderInfo.QUANT_MASK));
}
return (byte)(((aval & EncoderInfo.SEG_MASK) ^ mask) & EncoderInfo.SIGN_BIT);
}
static short MuLawToLinearSample(byte muLaw)
{
int sign = (muLaw & EncoderInfo.SIGN_BIT) >> 7;
int exponent = (muLaw & EncoderInfo.SEG_MASK) >> 4;
int mantissa = muLaw & 0x0F;
int sample = ((mantissa << 3) + EncoderInfo.BIAS) << (exponent + 2);
return (short)(sign == 0 ? sample : -sample);
}
}
Here is the EncoderInfo class.
internal static class EncoderInfo
{
public const int BIAS = 0x84;
public const int SEG_MASK = 0x70;
public const int SIGN_BIT = 0x80;
public const int ALAW_MAX = 0xFFF;
public const int QUANT_MASK = 0xF;
public const int SEG_SHIFT = 4;
}
modified 14-Sep-24 20:37pm.
|
|
|
|
|
Disclaimer: I never tried to do any such conversion myself.
But I read in the G.711 standard:
-------------------
If a m-A conversion is followed by an A-m conversion, most of the octets are restored to their original values. Only those octets which correspond to m-law decoder output value numbers 0, 2, 4, 6, 8, 10, 12, 14 are changed (the numbers being increased by 1). Moreover, in these octets, only bit No. 8 (least significant bit in PCM) is changed. Accordingly, the double conversion m-A-m is transparent to bits Nos. 1-7.
Similarly, if an A-m conversion is followed by a m-A conversion, only the octets corresponding to A-law decoder output value numbers 26, 28, 30, 32, 45, 47, 63 and 80 are changed. Again, only bit No. 8 is changed, i.e. the double conversion A-m-A, too, is transparent to bits No. 1-7.
A consequence of this property is that in most of the analogue voice frequency signal range the additional quantizing distortion caused by m-A-m or A-m-A conversion is considerably lower than that caused by either m-A or A-m conversion (see Recommendation G.113).
-------------------
It sounds to me like you cannot do a bit transparent mu-A-mu or A-mu-A conversion cycle. Extra distortion will be introduced. Maybe this is the distortion you are referring to.
In case you do not have the G.711 standard document (from which the above quote is taken), you can retrieve it from www.itu.int
Note the red text: Corresponding ANSI-C code is available in the G.711 module of the ITU-T G.191 Software Tools Library. This is a huge library; the source text fills almost 70 MB. You might find useful code there.
Religious freedom is the freedom to say that two plus two make five.
|
|
|
|
|
Thanks, I will look deeper into this and see where it leads. The distortion I speak of could very well be explained by this. I will need to look at a ulaw file that has not been encoded by my alaw/ulaw encoders first to determine if it's do to the specs or something within my encoders causing it.
|
|
|
|
|
Further to the above excellent suggestions, why not create a 0..FF ramp and pass it through your process? Spotting the distortion would be very easy then.
Anything involving bit-shifting like this makes me very wary about sign extension. I've been bitten by assuming something is unsigned, wondering where all the high order 1's came from when I used >> .
Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012
|
|
|
|
|