Skip to main content

Posts

Showing posts with the label C#

Code Review: Class Comments

Let's talk in this post about code comments, around the following example. /// <summary> /// ... summary comments ... /// Note: If you change environment make sure you clear this file,as it will contain cached configuration /// </summary> public class ConfigurationPersister { public T GetConfiguration<T>() { ... } public void PersistConfiguration<T>(T configuration) { ... } internal bool HasConfiguration<T>() { ... } private string CreateConfigFileName(string fileName) { ... } private void CheckConfigDirectory() { ... } } Tags First thing that we might notify is the 'NOTE' part. For this kind of scenarios we should use custom tags like '<remarks>'. In this way the other developer that is using the ConfigurationPersister (class), can see more clearly any remarks. /// <summary> /// ... summary comments ...

[Post Event] August 30-31, 2015 - DOTNET Core (Fundamentals)

Last week I delivered a two days workshop about .NET Fundamentals. This two days workshop covered the base pillars of programming in C#. Topics like: - C# Syntax - Creating methods - Handling exceptions - Monitoring applications - Working with classes - Type-Safe collections - Class Hierarchy - Using Inheritance - Accessing Database - Working with streams - Improve application performance - Improve application responsiveness - Encrypting / Decrypting - Reusable Types and Assemblies - Reflection - C# 6.0 were covered during this workshop.

New features of C# 6.0

If you already had the opportunity to look over the new features of C# 6.0 than you may not be so interested to read this post. Otherwise, this post is perfect for you. The main scope of this post is to take a look over new features of C# 6.0 that are already available and identify use cases where we can use them with success. Auto-property initializer Starting from now we will be able to set a default value of a property directly. We don't need anymore to initialize the value from constructor. On top of this, we can set a default value for a properties that have only a getter, without a setter. In this way we can replace the read only fields that are public exposed.    public class Foo { public int Value { get; set; } = -1; public string Name { get; } = "Tom"; } This is not all, on top of this, we can set the default value of a property in a constructor even if we don't have a setter. This is a big change from the old C# language. p

How to NOT expose a read only collection in C#

These days I had the opportunity to make a review over an ecommerce application. They tried to use CQRS and they almost succeeded.  I notified a problem on their queries classes that can become a big problem in time, if you want to sell this solution as a platform. Also, from some perspective, these problems also violate the CQRS principle. Let’s see some code now: public class Order { Collection<OrderItem> _items; public IEnumerable<OrderItem> Items { get { return _items; } } ... } What do you see here strange?  We want to expose the OrderItem collection as a read only collection. To do this, we convert it to IEnumerable. Hmmm… sounds good? Nope. Big mistake! Nobody stop us to convert the Items back to an ICollection and Add/Remove items from it. Order order = new Order(); … var orderItems = (Collection<OrderItem>)oder.Items; What should we do? .NET framework has specials collections that can be used

Mixing UI controllers in a Windows Store App (Metro App) for Windows 8

More and more people (especially developer) are very excited about Windows 8 and the new features that come with him. As you already know we have free native languages that can be used to write Windows Store Applications (Metro Apps): C++ using DirectX or XAML C# using XAML JavaScript using HTML5 Also we can use Visual Basic and XAML. One interesting feature is the mixing components support. We can use components written in C# or C++ and use them in project written in JavaScript, C++ or C#. This is what WinMD and WinRT offer to us. Because of this we can imagine a lot of scenarios developing a part of the application in C# and the UI part in JavaScript for example. Sounds great and this is possible and also recommended. We can develop great application in this way. Also, WinRT API is not 100% available in any language. Even if JavaScript, C# and C++ are native languages and WinRT is native for all of them, there are things that can be done only from a specific language. For examp

C# error at compile time challenge

Problem : I have a challenge for you. You will find at the end of thispost a link to a zip that contains a .NET 4.0 projects. The challenge is tomake this project to compile and give me the cause of the problem. I will letyou until Friday morning. Good luck. https://skydrive.live.com/redir?resid=BB7D9F52E4FDB024!259&authkey=!APfTPi6HWX0VJQg Solution : In the ‘class’ word from the Foo class we had an odd character for Unicode world. The character named is ‘Zero with space’. Is like a space between words but without a visible space (width). Because Visual Studio can process also Unicode files, we have no limitation to add Unicode characters that are not visible using a normal editor. If we open the file with Total Commander viewer for example we will be able to see the character (in hex view for example). Nice job :-)

Applications bugs that can be caused by 'ref' keyword

Zilele acestea ma uitam peste un cod si am intalnit urmatoarea linie de cod: Foo foo1 = new Foo(); ... Foo foo2 = foo1; ... DoSomeAction(ref foo1) { ... foo1 = new Foo(); ... } ... Pentru unele cazuri se ajungea ca in interiorul metodei DoSomeAction sa se creeze o noua instanta a obiectului Foo. Iar in unele cazuri aplicatia crapa intr-o alta locatie destul de urat. Nu o sa incep sa explic ce face keyword-ul ref si out. Totusi am adaugat un citiat din MSDN ca sa pornim de la un punct comun. The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method. The value of a reference parameter is always the same as the value of the underlying argument variable. An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have

Some cool stuff debugging with Debugger Canvas

Continui seria de posturi ( 1 , 2 ) despre cum sa facem debug in Visual Studio cu un post dedicat Debugger Canvas. Cati dintre voi ati apucat sa o folositi intr-un mediu real? Mai mult ca sigur v-ati jucat cu ea, dar ati reusit sa o folositi mereu? Eu va spun sincer ca nu. Sunt cazuri cand poate sa fie foarte utila, dar in unele situatii, cand vrem sa facem un debug simplu e mult prea complexa. Acesta este un tool free, care poate sa instalat in Visual Studio. Il puteti download din urmatoarea locatie http://download.microsoft.com/download/5/A/7/5A7FB2E7-5720-4739-BDDE-28A684C5B291/Microsoft.DebuggerCanvas.vsix si daca ma intrebati pe mine, este unul din tool-urile care nu poate sa lipseasca din Visual Studio. Cand mi se pare extrem de utila? In momentul in care este nevoie sa facem debug intr-un mediu cu multe thread-uri care ruleaza simultan sau cand avem parte de recursivitate. In aceste cazuri este extrem de usor sa urmarim valorile  la fiecare field sau variabila din call stac

Could this be a good case when to use 'params'

In urma cu cateva saptamani am discutat putin despre keyword-ul params si cautam locuri unde acesta ar putea sa fie folosit cu un scop clar, nu doar de dragul de a il folosi. Zilele acestea am gasit un caz unde acesta ar putea sa isi gaseasca locul. Sa presupunem ca scriem o metoda care genereaza semnatura unei metode pe baza. Numarul de parametrii a unei metode poate sa fie variat de la 1 la n si chiar 0. Din aceasta cauza pentru a putea sa acoperim cele doua cazuri ar fi nevoie sa avem ca si parametru o colectie de parametri care sa accepte sa fie si null. public string GetMethodSignature(string methodName, List<object> parameters = null) Acuma apar usoare probleme pentru cel care ne foloseste metoda. Pentru fiecare apel cand are unul sau mai multi parametri o sa fie nevoit sa creeze o lista de elemente. myObj.GetMethodSignature( "FooAction" , new [] { param1 }); In acest caz, o implementare folosind params ne simplifica putin atat apelul cat si modul in care pro

Windows 8: Error on video playing

Pentru aplicatiile Metro in Windows 8, adaugarea de video la un view se face destul de simplu, utilizand componente precum MediaPlayer . <MediaPlayer x:Name="VideoMediaPlayer" AutoPlay="False" Loaded="VideoMediaPlayer_Loaded"/> ... private void VideoMediaPlayer_Loaded(object sender, RoutedEventArgs e) { MediaPlayer player = (MediaPlayer)sender; IRandomAccessStream videoStream = GetVideoStream(); player.SetSource(videoStream, "video/mp4"); } Binding-ul la source se poate face in diferite moduri. Nu are importanta cum il faceti. In schimb pe versiunea curenta de Windows 8 ( Consumer Preview) aplicatia voastra o sa crape uneori cand userul face play/stop sau schimba pagina curenta. Eroarea care se arunca are forme asemanatoare cu aceasta: Windows.UI.Xaml.UnhandledExceptionEventArgs Exception from HRESULT: 0xC00D3E85 Call to UIASendMessageTimeout failed Nu incercati sa faceti FIX la aceasta problema in codul vostru. Problema este un bug pe care

Use lock in a block that contains a call to an async method (await keyword)

Citeam urmatorul post http://qedcode.com/content/awaitable-critical-section , in care se explica o modalitate de a face lock in cazul in care in block-ul de lock contine un apel la o metoda async. Pe scurt, pentru a evita ca doua sau mai multe thread-uri sa scrie simultan in acelasi fisier, se incerca sa se faca lock. Dar .NET 4.5 nu ne lasa sa avem urmatorul cod (si foarte bine face): lock( this ) { var f = await storageFile.OpenAsync(); ... await file.WriteAsync("some content"); } Eroarea pe care o primim arata in felul urmator: The 'await' operator cannot be used in the body of a lock statement. In link-ul pe care l-am dat mai sus, s-a incercat implementarea unei solutii custom care face lock la o anumita portiune de cod. O alta varianta ar putea sa fie sa incerca sa folosim Task.Run. Cea ce am obtine ar fi ceva asemanator cu urmatorul cod lock( this ) { var f = await storageFile.OpenAsync(); ... Task.Run(async () => {await f.Writ

DataContractSerializer and list of abstract class

Plecam de la urmatoarea structura: public abstract class BaseCar { public string Name { get; set; } } public class SportCar : BaseCar { } public class UtilityCar : BaseCar { } public Foo { public Foo() { Cars = new List<BaseCar>(); } public List<BaseCar> Cars { get; set; } } ... Foo myFoo = new Foo(); myFoo.Cars.Add( new SportCar()); DataContractSerializer serializer = new DataContractSerializer(typeof(Foo)); serializer.WriteObject(myXmlWriter, myFoo); Cand nu avem specificat nici un atribut de tip DataContract, toate campurile care sunt publice se serializeaza. In cazul nostru codul se compileaza fara probleme si obtinem un obiect serializat. Problema apare cand vrem sa deserializam obiectul nostru si ne trezim ca proprietatea Cars este null. Chiar daca in constructor inializam aceasta proprietate obtinem in continuare NULL. Cand ne uitam peste cod realizam ca lucram cu o clasa abstracta, iar in acest caz avem nevoie de atributul KnownTypes pe care il si ad

The secret behind "params" keyword

Jucandu-ma putin cu codul din C# am redescoperit "params". Acesta in general poate sa fie gasit intr-o aplicatie consola in Main, dar putem sa il folosim si in alte cazuri. Prin intermediul acestui keyword putem sa specificam o lista de parametri despartiti prin virgula. public void MyMethod(params string[] words) { foreach(string word in words) { Console.WriteLine(word); } } Nu este nimic special cu acest keyword. Cand am inceput sa invatam limbajul C#, am vazut ca exista, dar nu l-am vazut niciodata folosit intr-un cod de productie si mi-am pus intrebarea DE CE? In primul rand vrea sa vedem ce putem face cu acesta. De exemplu avem o metoda care accepta zero, unu sau mai multe elemente de acelasi tip (o lista de elemente). In mod normal am avea urmatorul cod: public void MyMethod(string[] items) { // Some action. } Pentru a putea folosi aceasta metoda am avea urmatoarele apeluri: MyMethod(); // Eroare la compilare. MyMethod(new string[0]); // Nici un

Custom button image of AppBar in a Windows 8 Metro application

Intr-o aplicatie Metro pentru Windows 8, in partea de jos avem un app bar in care putem sa punem diferite comenzi. Este extrem de asemanator cu app bar-ul de pe pe Windows Phone 7. By default, framework-ul contine o lista de icoane pe care le putem folosi pentru aceste comenzi. Pe langa aceste imagini, sunt cazuri cand dorim sa avem iconite custom, pe care noi le-am definit. Aceste imagini trebuie adaugate sub forma unor resurse png. (48px pe 48px). In general avem cel putin doua resurse, una cand butonul este selectat, iar cealalta pentru starea normala. Urmatorul pas este sa ne definim un stil pentru a avea un efect pe buton cand acesta este apasat. Acesta se poate face ca in felul urmator: <Style x:Key="CustomMyCommandAppBarButtonStyle" TargetType="Button" > <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <

What are the base async patterns in .NET world

In momentul de fata exista diferite paternuri care sunt folosite pentru apeluri asyncrone. Am observat ca destul de multa lume incurca aceste paternuri si se face un mix intre acestea. Din cate am observat pana acuma exista 3 paternuri principale care sunt folosite in general in .NET (mai putin 4.5, despre care o sa vorbim separat). EAP (Event based Asynchronous Pattern) - in acest patern orice schimbare de stare (actiune se termina de executat, apare o eroare, progresul) sunt notificate prin intermediul unor evenimente. public class FooEAP { public void CalculateAsync(int value1, int value2) { int sum = value1 + value2; OnCalculateComplete(sum); } public event CalculateCompleteEventHandler CalculateComplete; private void OnCalculateComplete(int result) { if( CalculateComplete != null ) { CalculateComplete(this, new FooCalculateEventArgs(result)); } } } APM (Asynchronous Programming Model) - paternul este destul de usor de recunoscut prin format

Use LINQ to get items of specific type

Ma uitam peste un cod scris de mine in urma cu cateva zile si am gasit urmatoarea linie de cod: var fooCollection = items.Where( x => x is Foo).Select(x => x as Foo); In cazul in care vrem sa extragem elementele dintr-o colectie care sunt de un anumit tip putem sa folosim metoda OfType . Aceasta metoda returneaza toate elementele din colectie de un anumit tip. Colectia pe care o returneaza o sa contina doar elemente de tipul specificat de catre noi. Daca rescriu linia de mai sus o sa obtinem: var fooCollection = items.OfType<Foo>(); Colectia returnata o as fie de tipul dupa care filtram datele. In exemplul dat de mine, rezultatul returnat o sa fie de tip IEnumerable . Astfel incat nu mai este nevoie sa facem nici un fel de conversie. Mai jos gasiti un link pagina MSDN care descrie aceasta functie: http://msdn.microsoft.com/en-us/library/bb360913%28v=vs.110%29.aspx