|
You're welcome!
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 area how much intersected that part need to be code and change the boarder color allow user to choose in c# windows appication
|
|
|
|
|
We are more than willing to help those that are stuck: but 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.
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!
|
|
|
|
|
I have run into an issue using "LINQ Where" on a tree structure, to create a list of leaf nodes. After I delete those nodes in a loop, I would expect "leaf nodes" to be an empty list. Instead it contains 2 nodes. Can anyone explain this behavior?
Specifically the application does the following:
- convert a list of folder paths to a simple tree structure
- use LINQ to select terminating paths (folders with no sub-folders)
- convert/copy the linq iterator to a List<node> using "toList()"
- loop over the list and delete these nodes from the tree
- After processing, the LINQ iterator contains 2 nodes instead of 0 nodes
See 100 line example below...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>
{
@"\base",
@"\base\001",
@"\base\001\cfg",
@"\base\001\cfg\network",
@"\base\001\cfg\network\mgmnt",
@"\base\001\cfg\network\users",
@"\base\002",
@"\base\002\copy",
@"\base\002\copy\cfg",
@"\base\002\copy\cfg\network",
@"\base\002\copy\cfg\network\mgmnt",
@"\base\002\copy\cfg\network\users",
};
Tree tree = new Tree(list[0]);
foreach (string item in list)
{
tree.Add(item);
}
var nodes_to_delete_iter = tree.Root.Descendants().Where(d => d.Children.Count == 0);
var nodes_to_delete_list = nodes_to_delete_iter.ToList();
int start_count = nodes_to_delete_iter.Count();
for (int index = nodes_to_delete_list.Count - 1; index > -1; index--)
{
Node leaf = nodes_to_delete_list[index];
Console.WriteLine("Removing " + leaf.Path);
nodes_to_delete_list.Remove(leaf);
tree.Remove(leaf);
}
int final_count = nodes_to_delete_iter.Count();
Console.ReadKey();
}
}
public class Tree
{
public Node Root { get; private set; }
public Tree(string root_path)
{
Root = new Node(root_path);
}
public Node FindParent(string node_path)
{
int index = node_path.LastIndexOf("\\");
string parent_path = node_path.Substring(0, index);
Node parent_node = Root.Descendants().FirstOrDefault(n => n.Path == parent_path);
return parent_node;
}
public Node Add(string node_path)
{
Node parent_node = FindParent(node_path);
Node node = new Node(node_path);
if (parent_node != null) { parent_node.Children.Add(node); }
return node;
}
public void Remove(Node node)
{
Node parent_node = FindParent(node.Path);
parent_node.Children.Remove(node);
node = null;
}
}
public class Node
{
public string Path { get; private set; }
public List<Node> Children { get; private set; }
public Node(string value)
{
Children = new List<Node>();
Path = value;
}
public IEnumerable<Node> Descendants()
{
return new[] { this }.Concat(Children.SelectMany(child => child.Descendants()));
}
public override string ToString()
{
return Path;
}
}
modified 9-Nov-20 20:02pm.
|
|
|
|
|
You're manipulating a (realized) "list" that contains references to the contents of a (dynamic) LINQ query; and then trying to make sense of the count of the query result. You're expecting too much from a scenario that has quite likely been corrupted.
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
|
|
|
|
|
Thank you Gerry!
After reading your response, I followed up by searching for "c# modify ienumerable" which reinforced your point that these collections should not be modified, or if they are, then the results should not be interpreted.
c# - Update item in IEnumerable - Stack Overflow
Thanks again.
|
|
|
|
|
You're welcome! Glad I could help.
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
|
|
|
|
|
Stellar Developer wrote:
public IEnumerable<Node> Descendants()
{
return new[] { this }.Concat(Children.SelectMany(child => child.Descendants()));
} There's no need to create a new array here. Just use an iterator method.
public IEnumerable<Node> Descendants()
{
yield return this;
foreach (Node child in Children)
{
foreach (Node descendant in child.Descendants())
{
yield return descendant;
}
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I'm creating a RestSharp wrapper class. It has a generic ExecuteAsync() method:
public async Task<APIResponse<T>> ExecuteAsync<T>()
{
var task = await Task.Run(() =>
{
var apiResponse = new APIResponse<T>
{
Success = true
};
IRestResponse<T> response = client.Execute<T>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
apiResponse.Result = response.Data;
return apiResponse.Result;
}
else
{
apiResponse.Success = false;
LogError(new Uri(baseURL), request, response);
return default(T);
}
});
return task;
}
It's won't compile on the the "return default(T)" line with
"Cannot implicitly convert type 'T' to 'APIResponse<t>'"
Here's the response class
public class APIResponse<T> : EventArgs
{
public APIResponse()
{
Messages = new List<ReponseMessage>();
}
public List<ReponseMessage> Messages { get; set; }
public T Result { get; set; }
public bool Success { get; set; }
}
public class ReponseMessage
{
public string Message { get; set; }
public Exception Exception { get; set; }
}
I'm calling it like this:
public APIResponse<Disclaimer> GetDisclaimer(int id)
{
APIExecutor webAPIExecutor = new APIExecutor("Disclaimer/GetDisclaimer");
Task<APIResponse<Disclaimer>> results = webAPIExecutor.ExecuteAsync<Disclaimer>();
return results.Result;
}
I think there's some confusion with the T parameter in the method name and the return type.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Your method defines the return type to be Task<apiresponse<t>> but on failure you try to return default(T) instead of a Task<apiresponse<t>>
Wrong is evil and must be defeated. - Jeff Ello
Never stop dreaming - Freddie Kruger
|
|
|
|
|
Ignoring the Task , since this is an async method, your return type is declared as APIResponse<T> . However, you are returning APIResponse<T>.Result , which is most likely of type T .
It's not clear why you're using Task.Run instead of RestSharp's built-in async support.
public async Task<APIResponse<T>> ExecuteAsync<T>()
{
IRestResponse<T> response = client.ExecuteTaskAsync<T>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
return new APIResponse<T>
{
Success = true,
Result = response.Data,
};
}
LogError(new Uri(baseURL), request, response);
return default;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks Richard. That did it
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Hello
I am planning to make an app which could be used between defined times and if the time is not between the defined time then the app would give a warning and close the app.
Originally thinking about making a parental control app for parents and their kids so the parents can tell when it is enough.
I am using C# to make everything possible and I am using a database (MYSQL) to get the details.
The following are my questions:
Which way I should save in the database for different parents the timezone?
How I make the app to use that timezone which the parents defined?
If the parent will change the timezone while the app working and the time when the app can work then how the app will recognize that the data changed in the database?
I am newbie and I would be thankful for example or open source and some explanation if it is possible.
Thank you in advance all of the answers.
|
|
|
|
|
Store all datetimes as UTC. Your UI, of course, will have to know this and display all datetimes converted to the system timezone and all input converted to UTC for storage in the database.
|
|
|
|
|
"Parents" don't set / change "time zones". Your app should use the appropriate setting of the operating system (date and time; culture). Windows automatically syncs the time when it has access to the internet; including daylight saving.
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
|
|
|
|
|
I have made a custom filestream class that creates a copy of a file and uses the copy as the source to rewrite the file while making changes to values that match a specific criteria. Here is the basic setup:
public class MixedCompressionStreamRewriter : FileStream
It uses two modes: Parse mode reroutes the stream into a buffer to be analyzed and potentially rewritten before it gets sent to the output stream. When parse mode is false, it simply copies the base stream to the output stream. It also allows analysis of compressed data inside the stream because the source files will often have such data. Because of these use cases I had to override the Read method as such (commented so that one can trace where everything goes wrong in a debug session):
The issue occurs while executing the ReadUint32 call in the code below:
public static RecordHeaderBase FromFile(BinaryReader reader, uint internalIDMask = 0xFFFFFFFF)
{
ModRecordConsolidator consolidator = reader.BaseStream as ModRecordConsolidator;
if (consolidator != null)
consolidator.EnableParseMode = true;
RecordTypeInfo typeInfo = (RecordType)reader.ReadUInt32();
if (consolidator != null)
consolidator.EnableParseMode = false;
if (typeInfo == RecordType.TES4)
return new GameHeader(reader);
else if (typeInfo.isContainer)
return new GroupHeader(reader, typeInfo, internalIDMask);
else
return new RecordHeader(reader, typeInfo, internalIDMask);
}
This call leads to the execution of the overridden read method below which is where the actual problem occurs:
public override int Read(byte[] array, int offset, int count)
{
int result;
if (compressionHeaderStream == null)
{
result = base.Read(array, offset, count);
if (!parseMode)
{
long equivalentBufferLocation = MemoryBufferStart + MemoryBuffer.Length;
if (Position > equivalentBufferLocation)
{
long bufferCopyBytes = Position - equivalentBufferLocation;
if (bufferCopyBytes > int.MaxValue)
throw new OverflowException();
offset += (count - (int)bufferCopyBytes);
MemoryBuffer.Write(array, offset, (int)bufferCopyBytes);
}
if (MaxBufferSize != 0)
if (MemoryBuffer.Length >= MaxBufferSize)
FlushToOutput();
}
}
else if (MemoryBuffer == null)
result = base.Read(array, offset, count);
else
result = MemoryBuffer.Read(array, offset, count);
return result;
}
For some reason the *** starred line causes the file stream to read several thousand bytes rather than just four (which is confirmed by the value of count during debug). I have no idea why. During the base class read process, it accesses the following overridden methods:
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
I have no idea why the base method (which is Microsoft provided) would do this.
EDIT: Even weirder: the base method returns that it only read 4 bytes. It might help to know that ModRecordConsolidator in the first code block inherits from MixedCompressionStreamRewriter (the class whose code is shown)
modified 6-Nov-20 22:35pm.
|
|
|
|
|
I think you've over-engineered and should have stuck with FileStream (and an adapter pattern). You've been caught up in the fog of indirection.
Inheritance has proven to be less useful than first thought; and requires a lot more thought.
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
|
|
|
|
|
I am not really understanding a detail of your advice here. "Fog of indirection"? I chose the simplest solution I could think of for my needs as inventing a separate class would require me sending additional parameters through a lengthy call chain involving multiple methods COMBINED with the need to use just a regular filestream to perform the same function at other times. The code worked previously. It stopped working after I reinstalled windows, Visual Studio and made some changes to add additional functionality which left that part of the code untouched.
|
|
|
|
|
See. Still no clarity. "Another class" is a psychological limitation, not a real one.
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
|
|
|
|
|
Is your point to help or to show how superior your knowledge of programming is? No it isn't a psychological limitation. It is a practical one. The file stream behind the reader is used as both an indexer to keep instance data separate in a static dictionary structure AND as a way to call required additional functionality on the stream. What you suggest would require me to change a significant amount of code to pass currently unnecessary data, making it more complex that it currently is since currently I can handle separate use cases with the same sections of code (that was the reason I used the current approach). Either way the solution is complicated so why not try and fix the problem first? Unless you are saying that the problem can't be fixed using an inherited FileStream because of its "complex" nature.
|
|
|
|
|
An "adapter" pattern lets you manipulate the filestream; instead, you want to "act" like a filestream. Since you didn't write filestream, you really have less control.
You also outlined 2 distinct functions. So, filestream in fact, is now schizophrenic.
Anyway, your problem seems to be you "request" "count" bytes, read, then don't bother to check "result" (actual bytes read) against "count"; and then proceed to calculate a new offset using "count" (instead of result).
Not "superior"; I'm just not the coddling kind. Have a nice day.
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
|
|
|
|
|
I don't need to be coddled lol. I just need something beyond vague references as I did not major in CS and there are a few gaps in my learning (mostly self taught). And yes... I DID check "result" which was reported as 4 bytes. So that is not the issue.
The issue is that for some reason it is filling the buffer and counting it as being read when it isn't supposed to. I HAVE checked into that and confirmed it. I reported the issue on MSDN forums as something for them to look into and was told that inheriting/overloading FileStream itself can be unreliable if mixing in other unrelated functionality. I was advised to inherit Stream instead. This is similar to your original suggestion but serves my other needs as well.
|
|
|
|
|
We can't necessarily duplicate your problem from that code: we are lacking half the stuff that makes it work, such as the construction of your BinaryReader and it's FileStream.
So start by creating a minimum subset app which demonstrates the problem: uses the appropriate (cut-down) classes, dumps all the extraneous code, and shows the problem in as short a code as possible (but reflecting the structure you have in your existing code).
If that still shows the fault, show us the complete code so we can run it ourselves. If it doesn't, start looking at what you removed and put it back until it does ... then we can run it or it'll be fairly obvious what causes it.
Me? Without running it - and I can't - I'd guess that it's working but looks like it's failing for other reasons: if the return value is count then it's unlikely that the read is fetching considerably more data than that (somebody would have noticed by now). So you - and we - need a minimum app to show the problem so it can be looked at closely.
Sorry, but there is nothing I can do with those code fragments to prove your problem even exists!
"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!
|
|
|
|
|
Yes... it is even hard for ME to duplicate as it doesn't happen in all circumstances. I have tried my class on other files successfully. The one in this particular debug was the only one giving me the issue at the time and there is nothing I can isolate. See my other recent posts if you are curious but I did solve the issue with a workaround while I change the class to inherit from Stream instead of FileStream for the final solution.
|
|
|
|
|
By "several thousand", do you mean 4096?
The FileStream class buffers the file as it reads it. By default, it uses a 4Kb buffer.
FileStream buffers input and output for better performance.
You can pass a custom buffer size to the constructor if you want to override this behaviour. However, if you make the buffer too small, it could have a negative impact on performance.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|