Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I made WPF application using Devexpress and Ado.net Connectivity mode with data base.I worked in other languages and now move to C#, i am new to WPF .I wrote this code to edit single and grouped rows:
void EditRow(int focRowHand, nrcsaEntities a)
{
Name nametext = grid.GetRow(focRowHand) as Name;
try
{
if (nametext.Name1 != string.Empty)
{
update_id = nametext.PK_ID;
txtName2.Text = update_text = nametext.Name1;
if (Panel3.Visibility == System.Windows.Visibility.Visible)
{
Panel1.Visibility = System.Windows.Visibility.Visible;
Panel3.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
Panel1.Visibility = System.Windows.Visibility.Collapsed;
Panel3.Visibility = System.Windows.Visibility.Visible;
}
}
}
catch (Exception err)
{
DXMessageBox.Show(err.StackTrace);
}
}
private void ToggleButton1_Copy_Click(object sender, RoutedEventArgs e)
{
if (view.FocusedRowHandle == -1)
{
DXMessageBox.Show("Please Select any Item From Grid List");
}
else
{
try
{
int FocRowHand = view.FocusedRowHandle;
nrcsaEntities a = new nrcsaEntities();
if (grid.IsGroupRowHandle(FocRowHand))
{
int childCount = grid.GetChildRowCount(FocRowHand);
for (int i = 0; i < childCount; i++)
{
int childHandle = grid.GetChildRowHandle(FocRowHand, i);
EditRow(childHandle, a);
}
}
else
{
EditRow(FocRowHand, a);
}
}
catch (Exception ee)
{
DXMessageBox.Show(ee.StackTrace);
}
}
As my client demands to generate code with high quality. It is possible that more than 1000 users will use this application and can save users data more than 5000, My Question is that : As i have less time to submit my application to my client. If i want to convert this code into MVVM, how to do this as it's little complex to convert for me. Secondly, What do you think about this code quality. I am very much confuse about this. I am looking forward to your reply.
All I can tell you is that if you convert this application to WPF and MVVM in particular, then you will need to re-write a LOT of code. One problem is that WPF is very different from other languages... most developers face an uphill struggle when first learning WPF because of these differences.
Then, if you want to use the MVVM design pattern, things become even more different... for example, it is generally frowned upon to write code in code behind files. Of course, it is possible to use the code behind files, but we tend to implement Attached Properties that 'wrap' the functionality of these UI control event handlers, such as SelectionChanged instead.
Typically, the code that you have shown us would have to be moved into a view model, but then you'd lose the ability to reference your controls and so you'd have to find other ways to re-implement the same behaviour, but in an MVVM way. You'd also need to implement a load of ICommand instances to replace a lot of your Click handlers, etc.
Now, I must admit that my comments so far may make you think that I am not recommending that you convert your project. However, I am not not recommending that you convert your project. There are great benefits to WPF and using the MVVM pattern... the graphics, animations, styles and the ability to make any control look like anything else among other things.
The last point that I'd like to make relates to your question about 'big data'. WPF is a processor hungry framework... there's no way around this. It can be slow when rendering tens of thousands of data items into pretty UI elements. However, after working on a large scale application for a couple of years now, I've found that there are ways of improving the situation.
We can make WPF use the power of installed graphics cards, or use virtualised panels that only load data for the visible items, among other things. You really need to hear this negative side of WPF before you start your conversion, because once it has been converted, it'll be too late. I would also recommend that the computers that will run the application are made powerful enough, one way or another.
I hope this 'summary' has not been too negative for you and has helped in some way. I would like to end by saying that I personally am a huge fan of both WPF and MVVM.
I suggest you to take more days from your client and go for Devexpress MVVM Scaffolding Wizard It is ready to use. You have to just make connection to database and just have to change interface of your application.
Related
I update UI-Components (espcially Text) regularly in my game. My code looks like this:
private void ShowScore(string newScore) {
var scoreText=Find("Score").GetComponent<Text>();
if (scoreText.text!=newScore) scoreText.text=newScore;
}
My idea behind this is to only update the textbox when the value has really changed and so preventing unneccessary updates that might cause performance issues and/or bad UI experience like "flickering" and so on.
Now my question is: Is that even necessary or does Unity itself already the same validation internally?
Since the source code of Unity's UI system is open-source, you can actually look this up. Regarding your question, the specific code is here: https://bitbucket.org/Unity-Technologies/ui/src/31cbc456efd5ed74cba398ec1a101a31f66716db/UnityEngine.UI/UI/Core/Text.cs#lines-212
The relevant part of the setter is
else if (m_Text != value)
{
m_Text = value;
SetVerticesDirty();
SetLayoutDirty();
}
which, as you suspected, makes sure that the element will only be marked as "dirty" (requiring a visual update) if the new text is different from the one it had before
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an application that have several methods which checks for various errors on a computer. Right now i am calling the methods on load event of the form, but i kinda want to display what the program is doing by updating a label text for everything it does, like a progressbar. It should go from method to method in order.
And later i also want to check if everything has runned successfully. Should i look into Threading Tasks for this? Like starting a task for each method, stopping the task if it fails?
I would suggest to create the following classes:
WorkstationCheckBase - should be the base class for all checks.
WorkstationCheckRunner - gets a list of all checks and summarize
the result of each WorkstationCheckBase.
With that, you will encapsulate the checking from your UI and separete these concepts.
Now for you second question to show up on the UI some information (my assumation is that you use WinForm). For that you need a background task and update the UI frequently. You could use the Backgroundworker class for that.
Short answer: No, don't use threading-
Long answer: It depends!
When you get yourself into threading you start to face loads of other concurrency related problems, if all you want is to show a label of what is happening I would not suggest to use threads.
Since I have no code to look at I can only give you suggestions for how to solve your problem (without threading). The simplest way would be:
public void CheckErrors()
{
string errorText = string.Empty;
if (ErrorOneHasOccured(out errorText))
{
ErrorLabel += errorText;
}
errorText = string.Empty;
if (ErrorTwoHasOccured(out errorText))
{
ErrorLabel += errorText;
}
}
private bool ErrorOneHasOccured(out string errorText)
{
bool errorHasOccured = false;
errorText = string.Empty;
// DO error checking somehting
if (errorHasOccured)
{
errorText = "An error description";
return true;
}
return false;
}
Where :
ErrorLabel is the string property for the error text you want to display.
ErrorOneHasOccured is an example method for error checking, using the "Try" pattern.
I think this is the simplest way you can do it, but you can obviously engineer it further depending on what and why you need it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
consider the next code. it is ad hoc one time solution (lot of logic skipped and the code itself simplified), but while i was writing it, i came up with a few questions.
it retrieves files from uri, and if there is and error when retrieving from folder 'j', it stops trying to retrieve from this folder further.
as i understand, this code is not thread safe? though it looks like it works fine for me, but out of curiosity and self education (as i have little experience with multithreading), i want to figure out once and for all:
are openedConnections and failed (there are actually Removes are present too) variables are under threat of data racing or something?
if it is not thread safe, what is the best practices of making it safe? where to add locks and so on?
is there any kind of inconsistency, if those variables were not present? i mean, is it good to add DownloadDataCompleted handler to several events?
is there some benefit of making DownloadDataCompleted a non-static member of some dedicated class and writing webClient.DownloadDataCompleted += new Dedicated().DownloadDataCompleted;?
in general, your opinion: what is the best way to solve this kind of task? not considering small code optimizations, but conceptionally (or must i write 'conceptually'? o_O)
public class SomeClass
{
static HashSet<int> failed = new HashSet<int>();
static int openedConnections = 0;
static void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
openedConnections--;
if (e.Error != null)
{
failed.Add(MyToken(e.UserState).j);
return;
}
//save data
}
public void Retrieve()
{
for (int i = 1; i < 10000; i++)
for (int j = 1; j < 10000; j++)
{
if(failed.Contains(j)) continue;
WebClient webClient = new WebClient();
webClient.DownloadDataCompleted += DownloadDataCompleted;
var uri = string.Format("someuri/{1}/{0}", i, j);
webClient.DownloadDataAsync(new Uri(uri+".jpg"), /*token here*/);
openedConnestions++;
while (openedConnections > 32)Thread.Sleep(111);
}
}
}
Of course.
lock() the lists themselves before every access (Add and Remove).
I don't really get the question. Is it ok to have the same handler for different events? Sure who cares, it's just code. Is this specific handler good? Not really, nor is your entire architecture, down to the TCP level. This is just not how Windows is designed to work with TCP connections.
Well if you get paid by the line of code, sure. That's how enterprise applications get written. Even better if you get paid by memory or CPU cycles wasted.
Conceptually, the traditional way of writing web crawlers is to spawn a number of threads (the number is defined by your system, how many connections it can handle), push your download URLs into an array (don't forget lock), and inside the handlers pop one URL from the array (again don't forget lock) and download it synchronously. When you're out of items simply return (or if you're dynamically adding items wait until you get more).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm using Visual c# 2010 express edition
I have nearly 1500 effective lines of code, and been using regions regularly, but it's getting out of control, how can i better organize or directly show a method, without having to click in the design form?
Edit: i've read about this http://msdn.microsoft.com/en-us/library/jj739835.aspx (Map dependencies) but it's for visual studio 2013, never heard of anything like it
It's part personal preference, but one can use CTRL+M, CTRL+L to collapse/expand everything to keep things a bit more compact.
Or, through the selector (top-right side of the editor window) you can go straight to a method.
Or (again), the good old Go to definition (F12)
I usually use comments if there's a lot of code in a single file and just ctrl-f to whatever I'm looking for or when applicable I break things up into class files
Try not to keep too much in a single file. Regions are great, but it's even better to avoid the need for them. There is a lot of dogma around "maximum number of lines in a file/class", but all you need to know is, if the file starts getting annoying to read, you need to try and split it up :)
ALways try to describe and name your classes by their functionality. For example, you may have a ScientificCalculator class. As you start to add functions, you start to notice groups of related functionality. Once they go beyond say, 2-3 functions, move them out into new classes!
So your ScientificCalculator class may now refer to smaller classes like BasicOperations, TrigonometricOperations, LogarithmicOperations, etc... you get the picture.
There are many advantages to this, including, but not limited to, easily finding your way around your code. Oh, you want to modify the Sine() function? You know exactly where to look - the TrigonometricOperations class! And that's a much more enjoyable experience in the long run.
Do you have 1500 lines of code in your entire project? Or 1500 lines in a single class? Or (much, much worse) in a single method?
1500 lines for a given project isn't so bad, provided that you've logically broken out your dependencies. 1500 for one class is probably way more than you want to manage.
When writing your classes, try to keep in mind what the class is responsible for. Is it doing to much? Are all the methods related to a single responsiblity? Does it mix things like logic and database interaction? Does it mix presentation logic with business logic?
And if it's 1500 lines of code for a single method, well...
Also, keep in mind that everything in this response should be prefaced with "In general" - there are no strictly prescriptive statements anyone can make about your code without actually seeing it, and there are always special cases.
Finally, if refactoring into separate classes seems like a large effort now, keep in mind that it will only become more and more difficult as your project grows in size and complexity.
Here's a tip that is a bit more controversial than others...
I'll assume the code is not directly under your control, say a legacy set of libraries or web site you inherited instead of designed... If this is not the case then there are much better options as already suggested by others (DRY, Encapsulate, Refactor, etc, etc, etc). However one stop-gap measure that has worked for me in the past is to make use of partial classes.
-----SuperBigClass.cs-----
class SuperBigClass {
public void MethodA(){
}
public void MethodB(){
}
public void MethodC(){
}
...
public void MethodZZTop(){
}
}
....can be separated into a couple smaller files....
-----SuperBigClass - Methods A through Z .cs -----
public partial SuperBigClass {
public void MethodA(){
}
...
public void MethodZ(){
}
}
-----SuperBigClass - MethodZZTop.cs -----
public partial SuperBigClass {
public void MethodZZTop(){
}
}
As long as the term partial is applied to the class definition of all class files and all class definitions are in the same namespace this will work just fine. Here's a link for more info: Partial Classes and Methods (C# Programming Guide)
Again... The best approach is to DRY up code, encapsulate, refactor, etc, etc, etc... but sometimes when you hop into a legacy app and you need to restructure the files themselves without making any functional changes, this shortcut (admittedly an unintended use of the partial class syntax) can be helpful for cutting large files up and helping to make sense of things.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've searched google and stackvoverflow to get the answers but it all boils down to: Create methods.
I want my code to be reusable. I don't want to create other methods in the same class. This class already contains a lot of code. How can I reduce the complexity while have a readable class?
I thought about creating another class and having all the new methods there.
The code
public Issue GetIssue(int issueId, IssueOption issueOption)
{
string resource = "issues/{id}.xml?";
if (issueOption.IncludeRelation)
{
resource += "include=relations&";
}
if (issueOption.IncludeChildren)
{
resource += "include=children";
}
//To fetch multiple associations use comma (e.g ?include=relations,journals
RestRequest request = new RestRequest(resource);
request.AddParameter("id", issueId, ParameterType.UrlSegment);
Issue issue = Execute<Issue>(request);
if (issueOption.IncludeVersion)
{
issue.Fixed_version = GetVersion(issue.Project.Id);
}
if (issue.Parent != null && issueOption.IncludeParent)
{
issue.Parent = GetIssue(issue.Parent.Id, issueOption);
}
if (issueOption.IncludeUsers)
{
if (issue.Author.Id == issue.Assigned_to.Id)
{
issue.Author = GetUser(issue.Author.Id);
issue.Assigned_to = issue.Author;
}
else
{
issue.Author = GetUser(issue.Author.Id);
if (issue.Assigned_to != null)
{
issue.Assigned_to = GetUser(issue.Assigned_to.Id);
}
}
}
if (issueOption.IncludeProject)
{
issue.Project = GetProject(issue.Project.Id);
}
return issue;
}
The road to readable code is very rough out of legacy code.
First off, you should have tests that fully cover the code you are refactoring otherwise you end up traversing that rough road in a blinding blizzard -- it's possible but not fun and very dangerous.
Once you've covered your butt there, you can start the refactorings. By and large, most of the early refactorings (assuming a lot of similar methods to what you have above) will be Extract Method. From there, some class behaviors should start becoming apparent and you can extract them out then.
I thought about creating another class and having all the new methods there.
This is analogous to cleaning your room by pushing everything under the bed. The room is clean but you've only hidden the mess. Don't do without any thought otherwise you'll end up with a Utility class that's even worse than what you have now.
From an OOP-perspective, working towards a SOLID solution is generally desired. The key tenet to focus on from a legacy standpoint is Single Responsibility for your classes. If you have that, the O-L-I-D tend to just fall into place (from my experience, though I've had way more brownfield development experience than I'd really like).
This class already contains a lot of code.
...
I thought about creating another class and
having all the new methods there.
That is exactly what you should do.
As you mentioned, breaking the code into smaller methods is the way to go. How about organizing your code using static extension methods, seeing as how Issue is the main subject of the code:
// top-down:
RestRequest request = GetRequestForIssueOption(issueId, issueOption);
Issue issue = Execute<Issue>(request);
// make it fluent...
return issue.SetVersion()
.SetParent()
.SetUsers()
.SetProject();
I think static extension methods make sense to use. Personally, I think making the static extensions fluent helps bring further clarity to code, not sure if that's your cup of tea though.
public static Issue SetVersion(this Issue issue_)
{
// code here
}
public static Issue SetParent(this Issue issue_)
{
// code here
}
public static Issue SetUsers(this Issue issue_)
{
// code here
}
public static Issue SetProject(this Issue issue_)
{
// code here
}