c#,oop,design,interfaceRelated issues-Collection of common programming errors
LachlanB
c# c++ dependencies
Currently we are using Source Safe and have started migration to Subversion. All of our external SDK’s(> 500 MB) are held in Source Safe right now, and I am looking for ways to move them from VSS to a repository.We have C++ (mostly), C# (many), Java (few) projects. Hundreds of projects, all running on Windows.I looked at a couple of dependency managers but I’m not satisfied:NuGet – good for .Net but painful for C++ Ivy – not look in depth, but doesn’t seem acceptable for C++First question: what
System Down
java c# android
I’m a C# dev and I have plans of starting to develop apps targeting Android, which of course means Java. I have heard good things about Mono for Android and the idea of reusing my skill set is appealing, however the licensing cost (for now) is a bit prohibitive to me. On the other hand, from what I can see, Java is very similar to C#, so I’m predicting that shifting my skills to it will be more or less easy (easier than shifting to Obj-C I guess). Am I wrong in assuming that?Are there any hidden
Andrew Russell
xna c#
I’m making a particle engine so I develop a texture programatically and I want to display it in a Windows Form picture box. So I create the Texture2D which goes fine. Then I use this code to convert from a Texture2D to an Image for the picture box.public static System.Drawing.Image Texture2Image(Texture2D texture){if (texture.IsDisposed){return null;}MemoryStream memoryStream = new MemoryStream();texture.SaveAsPng(memoryStream, texture.Width, texture.Height);memoryStream.Seek(0, SeekOrigin.Beg
Vaccano
c# task-parallel-library async-await
I have a Queue that needs to try to process when anything updates in it (add, remove or update).However, I don’t want any of the callers to wait while the processing is happening (either for the processing to happen or while the processing is happening).This is what I came up with:private static readonly SemaphoreSlim asyncLock = new SemaphoreSlim(1); private async void ProcessQueue() {// Lock this up so that one thread at a time can get through here. // Others will do an async await until it i
ashenemy
c# dll pinvoke
Trying to use the command dll (c + +) project to c # Structure dlltypedef struct { SSP_FULL_KEY Key; unsigned long BaudRate; unsigned long Timeout; unsigned char PortNumber; unsigned char SSPAddress; unsigned char RetryLevel; unsigned char EncryptionStatus; unsigned char CommandDataLength; unsigned char CommandData [255]; unsigned char ResponseStatus; unsigned char ResponseDataLength; unsigned char ResponseData [255]; unsigned char IgnoreError; } SSP_COMMAND;typedef struct { unsigned __int64 Fix
dtb
c# .net apple-push-notifications sspi
I have got wierd problem going on. I am trying to connect to Apple server via TCP/SSL. I am using a Client certificate provided by Apple for push notifications. I installed the certificate on my server (Win2k3) in both Local Trusted Root certificates and Local Personal Certificates folder.Now I have a class library that deals with that connection, when i call this class library from a console application running from the server it works absolutely fine, but when i call that class library from an
mskfisher
c# string floating-point
I have a UTF-8 formatted data file that contains thousands of floating point numbers. At the time it was designed the developers decided to omit the ‘e’ in the exponential notation to save space. Therefore the data looks like:1.85783+16 0.000000+0 1.900000+6-3.855418-4 1.958263+6 7.836995-4 -2.000000+6 9.903130-4 2.100000+6 1.417469-3 2.159110+6 1.655700-32.200000+6 1.813662-3-2.250000+6-1.998687-3 2.300000+6 2.174219-32.309746+6 2.207278-3 2.400000+6 2.494469-3 2.400127+6 2.494848-3 -2.500000
user1918513
c# web-services ssl keystore truststore
I’m tryng to access a ssl server (web service) from a .net client (c#). I have access to a java client code that can connect to the server. Included in the source code are 3 files (saPubKey.jks, WebServices.pfx and trustStore) and I think that only 2 of the 3 are used in the java example.private void setSSLConnection(WSBindingProvider bp){KeyStore ks = KeyStore.getInstance(“pkcs12”);ks.load(this.getClass().getClassLoader().getResourceAsStream(“WebServices.pfx”), “password”.toCharArray());KeyMana
D.P.
c# .net
Possible Duplicate:Is using an existing object rather than creating a specific lock object safe? What do you think: is it good practice to lock on private static objects that are in use inside my class? For example, I have Dictionary that contains elements and on modifying it I do lock(myList). I prefer to use special private System.Object field that is used just as a lock, but my colleague thinks that it’s ok to use private static field, because it’s already private.
NayeemKhan
c# asp.net
Dear all, i have following code to open a file on click of a buttonSystem.Diagnostics.Process.Start(“soffice.exe”,filepath);soffice.exe is to open .odt files & filepath is containing the complete path of the file which i want to open.This is working perfectly when i m executing the code on my local system, but as i m hosting it on the iis server (5.1), its not taking any action (event not throwing any error too). My filepath is accessing a folder in my project, not outside. Kindly suggest th
Jamal
php oop
I could use some review on this Auth class, as I’m sure it could use many improvements!I wrote this fairly quickly, so please forgive any overseen bugs.Example usage:// Login a user if (Auth::attempt($_POST[‘username’], $_POST[‘password’])) {echo ‘You have successfully logged in.’; }// Check if the user is a guest if (Auth::guest()) {echo ‘Please log in to see this page.’; }// Logout a user Auth::logout();Source code:<?phpclass Auth {/*** Whether or not the user is currently logged in** @var
Jon Seigel
oop dependency-injection inversion-of-control castle-windsor
I’m using castle windsor for a pet-project I’m working on. I’m starting to notice that I need to call the IoC container in different places in my code to create new objects. This dependency on the container makes my code harder to maintain.There are two solutions I’ve used to solve this problemI tried to create abstract factories as wrappers around the container that I could inject into parts of my application that need to create objects. This works but has some drawbacks because castle has a ha
huzeyfe
json oop playframework
I am using Play Framework 1.2.4 with Java and using JPA to persist my database objects. I have several Model classes to be rendered as JSON. But the problem is I would like to customize these JSON responses and simplify the objects just before rendering as JSON.For instance, assume that I have an object named ComplexClass and having properties id, name, property1,…,propertyN. In JSON response I would like to render only id and name fields.What is the most elegant way of doing this? Writing cus
Gabriel Scerbák
c# oop
Here is only an example from my code. I’m looking for a good way to maintain my classes in order and following some OOP rules.This my abstract class Problem:public abstract class Problem<T> : IEquatable<T> {public abstract int ResultCount { get; }protected abstract bool CheckTheAnswer(params object[] results);public abstract bool Equals(T other); }Below is one class which derives from Problem, Arithetic class contains all the necessary that contains in a math problem, and how to reso
Ilari Kajaste
oop fluent-interface method-chaining
Method chaining is the practice of object methods returning the object itself in order for the result to be called for another method. Like this:participant.addSchedule(events[1]).addSchedule(events[2]).setStatus(‘attending’).save()This seems to be considered a good practice, since it produces readable code, or a “fluent interface”. However, to me it instead seems to break the object calling notation implied by the object orientation itself – the resulting code does not represent performing acti
Gordon
php oop class
I want to make a PHP class, lets say Myclass.php. Now inside that class I want to define just the class itself and some instance variables. But all the methods must come from a Myclass_methods.php file. Can I just include that file into the class body?I have good reasons why I want to seperate this. In short, I’ll have a backend in which I can change the business logic of a class, while all other things must remain untouched. The system maintains all the ORM and other stuff for me.But if this is
casperOne
oop inheritance language-agnostic aggregation
There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to “fill-in-the-blanks” when the superclass wants a particular interface but is agnostic about its implementation. Aggregation: create new functionality by taking other classes and combining t
roryWolf
php database oop
I am trying to display objects for a reminders list with the following fields: Title Date Added and a reminder image (a clock in my case)Currently i display the object with the following codeclass ReminderList{private $data;/* The constructor */ public function __construct($par){if(is_array($par))$this->data = $par; }public function __toString(){$image = $this->data[‘image’];// The string we return is outputted by the echo statementreturn ‘<li id=”todo-‘.$this->data[‘id’].'” class=”t
hakre
php oop
Hello there i have 2 classes for DB for language i want to use my language things in the DB so it outputs the resultex :class db_control{var $db_connection, $lang_var;//create the function for the connectionfunction db_connect(){//define some variablesglobal $db_host, $db_username, $db_password, $db_name, $lang_var;$this->db_connection = mysql_connect(“$db_host”,”$db_username”,”$db_password”)or die(“can’t connect to server with these informations”);//checl that the connection is establish
max
oop class inheritance override method-hiding
I’m trying to understand whether the answer to the following question is the same in all major OOP languages; and if not, then how do those languages differ.Suppose I have class A that defines methods act and jump; method act calls method jump. A’s subclass B overrides method jump (i.e., the appropriate syntax is used to ensure that whenever jump is called, the implementation in class B is used).I have object b of class B. I want it to behave exactly as if it was of class A. In other words, I wa
Jonik
java design encapsulation security
I’m having trouble understanding why java secure coding is important. For example, why is it important to declare variables private? I mean I get that it will make it impossible to access those variables from outside the class, but I could simply decompile the class to get the value. Similarly, defining a class as final will make it impossible to subclass this class. When would subclassing a class be dangerous for security? Again if necessary, I could decompile the original class and reimplement
raoulsson
java design refactoring
I have some code that I want to refactor. I have lots of methods that take multiple arguments of the same type, for example:public void foo(String name, String street, boolean b1, boolean b2) { … }and so on. Because the different objects can only be distinguished by name I would like to wrap them in Objects (Enums) so I can make use of the typesystem of the language (Java in this case). public class Name {private String value;public String getValue() { return value; }// … }Like this I could
pierocampanelli
.net winforms unit-testing design
I have an accounting & payroll client/server application where there are several input form with complex data validation rules. I am finding an effective way to perform unit testing of user interface.For complex validation rules I mean: “Disable button X if I Insert a value in textfield Y” “Enable a combobox if I insert a value in a textfield” …… ……Most promising pattern i have found is suggested by M. Fowler (http://martinfowler.com/eaaDev/ModelViewPresenter.html).Have you any exper
Ola Eldøy
css design magento content-management-system skinning
I am working with a client who has already purchased Magento -eCommerce CMS. I have never worked with this program and after reading over there extremely lengthy material I am not sure if I should take on the project. I am worried that this is a little outside of my skill set. I mostly do Design and Front-End Development. I have worked with WordPress somewhat regularly without any problems, however that is extremely well documented. My understanding of actual programming is limited. Has anyone c
Hunter McMillen
parsing design data-structures compiler recursive-descent
This is a follow up to a previous question I asked How to encode FIRST & FOLLOW sets inside a compiler, but this one is more about the design of my program.I am implementing the Syntax Analysis phase of my compiler by writing a recursive descent parser. I need to be able to take advantage of the FIRST and FOLLOW sets so I can handle errors in the syntax of the source program more efficiently. I have already calculated the FIRST and FOLLOW for all of my non-terminals, but am have trouble deci
srini.venigalla
java design api
Is it better to return a null value or throw an exception from an API method?Returning a null requires ugly null checks all over, and cause a major quality problem if the return is not checked.Throwing an exception forces the user to code for the faulty condition, but since Java exceptions bubble up and force the caller code to handle them, in general, using custom exceptions may be a bad idea (specifically in java).Any sound and practical advice?
Gennady Vanin Novosibirsk
wpf design architecture cross-platform conceptual
I saw a code example that creates a method Window_Loaded() which is called by XAML’s “Window Loaded” event:<Window x:Class=”TestModuleLoader.Window1″xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”Title=”Window1″ Height=”300″ Width=”300″ Loaded=”Window_Loaded”><Grid>…</Grid> </Window>But in the code behind, the code worked in both the constructor and the Window_Loaded() method:using System.Windows;na
1.44mb
node.js design express socket.io
I have almost completed a turn-based multiplayer game with node.js and socket.io. I have express.js as web server and another class acting as game server, using socket.io.My problem is that these two are running in the same application. I have a web-landing page where users can log in and see their player details and chat in the lobby. Now until here there is nothing related to game logic. So i’m asking myself why in the hell is this game server running in the same app with webserver. Also note
PVitt
.net design
Let’s say we have a client application that uses a network stack. The stack detects an error condition that leads the stack to close it’s connection and raises a ConnectionStateChanged event. Besides that the stack raises an ErrorOccured event to inform the client appplication about the error condition.So what to do first? Arrange the internal state (and raise the ConnectionStateChanged event) or inform the client application (raise the ErrorOccured event)?[EDIT]This question is not about the us
Thomas Owens
design optimization stability
In may Daily Job i come across this Dilemma :”Stable System Vs Better Design”In routine job when i am fixing some module, When i see bad design -> Badly written code-> Badly Written Algorithm-> Optimization possibleI would prefer to fix these also along with issue i am fixing But many people opposes my changes a few supports, People who opposes will say “You should be business oriented if system is stable, If you change some thing may cause regression, Hence do not favor business”some time : you
bjsn
c++ interface methods virtual
I read different opinions about this question. Let’s say I have an interface class with a bunch of pure virtual methods. I implement those methods in a class that implements the interface and I do not expect to derive from the implementation.Is there a need for declaring the methods in the implementation as virtual as well? If yes, why?
Strilanc
c# generics interface operator-overloading type-conversion
When I try to use a user-defined cast operator from an interface type to a generic struct type, I get a compile error stating the type can’t be converted:public interface J { } public struct S<T> {public static explicit operator S<T>(T value) {return new S<T>();} } public static class C {public static S<J> Test(J j) {return (S<J>)j; // <- error: cannot convert type ‘J’ to type ‘S<J>’} }Note that if J were a class, the conversion would work.There is a simila
RM.
delphi pointers interface av
I am getting an unexpected Access Violation error in the following code:program Project65;{$APPTYPE CONSOLE}{$R *.res}usesSysUtils;typeITest = interfaceend;TTest = class(TInterfacedObject, ITest)end;varp: ^ITest;beginGetMem(p, SizeOf(ITest)); p^ := TTest.Create; // AV heretryfinallyp^ := nil;FreeMem(p);end; end.I know that interfaces should be used differently. However I am working on a legacy codebase which uses this approach. And I was very surprised to see that it is not sufficient to reserve
mjn
delphi interface memory-leaks delphi-2009
This Delphi code will show a memory leak for an instance of TMyImplementation:program LeakTest;usesClasses;typeMyInterface = interfaceend;TMyImplementation = class(TComponent, MyInterface)end;TMyContainer = class(TObject)privateFInt: MyInterface;publicproperty Impl: MyInterface read FInt write FInt;end;varC: TMyContainer; beginReportMemoryLeaksOnShutdown := True;C := TMyContainer.Create;C.Impl := TMyImplementation.Create(nil);C.Free; end.If TComponent is replaced by TInterfacedObject and the con
Robottinosino
java oop design-patterns inheritance interface
In summary:object A has methods { m1, m2, … } which throw exceptions; after validation some of these methods will be known not to throw anymore. Model in OO this progression of validation stages where, as checks are run and they return positive results, an object is “promoted” to a higher level of confidence about the reliability of its methods and the exception checks are not forced on clients anymoreFull version:Could you kindly constructively critique this design choice:An interface describ
epologee
objective-c interface coding-style implementation
If you write method implementations in Objective-C, it is pretty standard to sum up the methods of a class in the corresponding @interface blocks. Publically accessible methods go in the header file’s interface, not-so-public methods can go in an empty category on top of the implementation file.But it’s not neccessary to declare an interface for every method. If you only reference the methods below their implementation code of the same class/file, there’s no need to put any declaration anywhere
fifigyuri
python ruby types interface
While coding in Ruby I did not really miss the type-orientedness of Java or C++ so far, but for some cases I think it is useful to have them. For Python there was a project PyProtocols which defined interfaces and protocols for objects. Does a similar initiative also exist for Ruby? I would like to be able to declare the expected parameters for some methods for some objects (for the entire code I find such think useless). It the method during the execution receives an unexpected input, it tries
Jim
java interface
I’m encountering an unexpected error (“inconvertible types”) when trying to cast an implementation of an interface to the interface.I’m given the following interfacepublic interface IAbc {…}and the following method in another classpublic class SomeClass {public doSomething(Iterable<IAbc> abcs) {…} }I’ve written the following classpublic class MyAbc implements IAbc {…}I’ve got a method elsewhere like thispublic class MyClass {public Iterable<MyAbc> getMyAbcs() {…} }I expected
Malachi
java interface
I have to implement an RMI server which will be a front end for two other RMI services. So I decided a logical thing to do would be to have the interface for this implement the interfaces for the other two services. public interface FrontEndServer extends Remote, BookServer, StudentServer {// Block empty so far }However there is a method on the StudentServer/*** Allows a student to borrow a book* * @param studentID of the student who wishes to borrow a book* @param bookID of the book the student
hakre
php interface
I’d like to create an interface, IFoo, that’s basically a combination of a custom interface, IBar, and a few native interfaces, ArrayAccess, IteratorAggregate, and Serializable. PHP doesn’t seem to allow interfaces that implement other interfaces, as I get the following error when I try:PHP Parse error: syntax error, unexpected T_IMPLEMENTS, expecting ‘{‘ in X on line YI know that interfaces can extend other ones, but PHP doesn’t allow multiple inheritance and I can’t modify native interfaces,
Web site is in building