InternetException

.NET

.NET · 77 posts (all categories)

Enhancing your .NET API with query language

· 1690 words · ~8 min read · updated · in .NET, ASP.NET, Hamster Wheel

#NuGet #LINQ #API design #HLinq

What is query language? SQL is Structured Query Language and you use it to query your database for data you are interested in. It does not have to do anything with your API. If you ever were working with big XML files you probably used XQuery or XPath, query languages designed to XML for data. There are specialized languages that are designed to work with APIs to query them for data. For example, you probably heard about GraphQL or even used it when you were working with some API.

Read the whole thing →

HLinq design

· 4639 words · ~23 min read · in .NET, ASP.NET, Hamster Wheel

#LINQ #delegates #reflection #Entity Framework

A bit of history

I remember the day when I started writing the HLinq query language. It was weekend and I was experimenting with writing Single endpoints for Hamster Wheel. Single endpoints were almost done and next step was to write List endpoint. This would allow to get list of records of specific type. After I got single GET returns correct data for chosen record id, list should not be hard to implement. Then just create, update and delete. Basic CRUD API in Hamster Wheel would be finished. I was thrilled that I actually was able to do such thing.

Read the whole thing →

Disable Xunit Test on specific OS

· 253 words · ~1 min read · in .NET, C#, debian, linux, testing

#Unit tests

Lately I was having a problem with some of my tests causing problems for other developers on the project I am working on. They were using Windows for their development while I am using Debian for my work. The application that was being tested was not designed for non Unix system - now rarely anybody is hosting they production code on Windows Server - everybody is using Unix for .net.

Read the whole thing →

Writing a simple C# source code generator with Fluent API

· 1812 words · ~9 min read · updated · in .NET, C#

#source generators #NuGet

Introduction

Usually in .NET world when you want to write generic code you use generic method or classes. But sometimes it is still not enough when you want to automate some things. I.e. you want to dynamically register in DI all the classes that implements some interface. Probably, in this case, you would do something like that:

var implementations = typeof(MyClass).Assembly.Types
   .Where(t => t.GetInterfaces().Any(i => i == typeof(IMyInterface))
foreach(var implementation in implementations)
{
   services.AddScoped<IMyInterface>(implementation);
}

And it would be completely fine. Even if Reflection is pretty slow, your application would not be getting significantly slower because of that. Certainly you would not notice the slow down.

Read the whole thing →

HamsterWheel.FluentCodeGenerators is out

· 159 words · ~1 min read · in Hamster Wheel, .NET

#source generators #NuGet

I released today first new Nuget package connected to my new project that I am working on for sometime: dynamically configurable, zero-downtime API, with low-code flows to write small pieces of logic - Hamster Wheel.

System heavily relies on dynamic source code generation. For that I wrote
https://www.nuget.org/packages/HamsterWheel.FluentCodeGenerators and https://www.nuget.org/packages/HamsterWheel.FluentCodeGenerators.Abstractions
small package that helps with writing C# incremental source code generators for Roslyn compiler.

Original Roslyn APIs are a bit hard to use so this package helps with that. Also it helps with:
\

Read the whole thing →

.NET/C# interview questions

· 146 words · ~1 min read · updated · in .NET, interview

#generics #reflection #async #Entity Framework

Read the whole thing →

Equals and GetHashCode

· 89 words · ~1 min read · in .NET, interview

Custom implementation is usually only necessary if default, reference equality is not enough. In example: entities value based equality value equality of deserialized objects custom comparisons based on other criterias public class ImaginaryNumber : IEquatable&lt;ImaginaryNumber&gt; { public double RealNumber { get; set; } public double ImaginaryUnit { get; set; } public override bool Equals(object obj) { return Equals(obj as ImaginaryNumber); } public bool Equals(ImaginaryNumber other) { return other != null &amp;&amp; RealNumber == other.RealNumber &amp;&amp; ImaginaryUnit == other.ImaginaryUnit; } public override int GetHashCode() { return HashCode.Combine(RealNumber, ImaginaryUnit); } }

Kestrel

· 36 words · ~1 min read · in .NET, interview

#ASP.NET

default application server for .net cross platform best performance and memory utilization may not have some advanced features of HTTP.sys on Windows may be used with proxy server or as internet facing server Further read: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-6.0

ASP.NET Core controller level exception handling

· 43 words · ~1 min read · updated · in .NET, interview

#ASP.NET MVC #ASP.NET

To handle exceptions on Controller/Action level Exception Filters are used. [TypeFilter(typeof(SampleExceptionFilter))] public class ExceptionController : Controller Exception Filters are implemented using IExceptionFilter with OnExcetion method override to handle exceptions. Exception Filters can be applied to Controller and Action level. Further read: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-7.0#exception-filters https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iexceptionfilter?view=aspnetcore-7.0

ASP.NET Core global exception handling

· 14 words · ~1 min read · in .NET, interview

#ASP.NET

To add global exception handling in ASP.NET Core just use configuration method: app.UseExceptionHandler https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0#exception-handler-lambda

What ASP.NET Middleware can do?

· 42 words · ~1 min read · updated · in .NET, interview

#ASP.NET MVC #ASP.NET

Pretty much everything. Default ASP.NET Core request handling pipeline is consisting of bunch of middlewares: Authentication Authorization CORS HTTP Logging MVC Static Files other Whole list of built-in middlewares can be found here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-7.0#built-in-middleware There is possibility to write custom middleware too.

Middleware in OWIN

· 141 words · ~1 min read · in .NET, interview

#delegates #async #ASP.NET

There are 2 ways of writing OWIN middleware in ASP.NET Core.

  • Pure OWIN - usefull if you want to integrate with OWIN compatible module but not written in C#
  • ASP.NET Core OWIN middleware

ASP.NET Core Middleware:

This type of middleware can be:

  • delegate of Func<HttpContext, Func<Task>, Task>
  • class with IMiddleware imlementation
app.Use(async (context, next) =>
{
    // Do work that can write to the Response.
    await next.Invoke();
    // Do logging or other work that doesn't write to the Response.
});

Pure OWIN Middleware:

This rather would be used to integrate with OWIN middlewares written in different language, so that ASP.NET Core implementation directly is not possible.

Read the whole thing →

Owin model and Kestrell request handling

· 89 words · ~1 min read · updated · in .NET, ASP.NET, interview

  • OWIN - Open Web Interface for .NET
  • allows web apps to be decoupled from web servers
  • defines standard way for middleware to be used in a pipeline to handle requests and provide responses
  • ASP.NET Core applications can interoperate with OWIN-based applications, servers and middleware

Microsoft.AspNetCore.Owin package provides two adapter implementations:

  • ASP.NET Core to OWIN
  • OWIN to ASP.NET Core

This allows ASP.NET Core to be hosted on top of an OWIN compatible server/host or for other OWIN compatible components to be run on top of ASP.NET Core.

Read the whole thing →

Expression Trees

· 81 words · ~1 min read · in .NET, interview

  • ’tree like’ data structure
  • each node is expression (method call, equality comparison, binary operation etc.) representing a piece of code
  • you can compile expression tree and run code it represent
  • enables dynamic code generation at runtime
  • LINQ queries on DBs are implemented with Expression Trees
  • used in the dynamic language runtime (DLR)
  • anonymous lambda expression can be converted to ExpressionTree via compiler (i.e. x => x*2 can be represented as tree instead of delegate or anonymous lambda function)

Further read:

Read the whole thing →

Linq

· 98 words · ~1 min read · in .NET, interview

#LINQ

consistent model for working with data from various kinds of sources and formats (XML, SQL, ADO.NET, Datasets, .NET collections etc) 3 stages of working with LINQ: obtain data source create the query execute the query data sources implements IEnumerable&lt;&gt; and are called queryable types IQueryable&lt;&gt; interface inherits from IEnumerable&lt;&gt; generally it is better to use LINQ via IQueryable&lt;&gt; which produces deferred query instead of producing result immediately queries can be executed multiple times queries can be forced immediate execution via Count(), Max(), ToList() or ToArray() etc. LINQ to DB libraries (like EntityFramework) usually are implemented via Expression …

Read the whole thing →

Entity Framework: Change Tracking

· 31 words · ~1 min read · in .NET, Entity Framework, interview

tracked entities are saved during SaveChanges() call entities being tracked when they are: returned from DB attached to context added as subentity tracking can be disabled (AsNoTracking() i.e.) Further read: https://learn.microsoft.com/en-us/ef/core/change-tracking/

Entity Framework: eager and lazy loading

· 71 words · ~1 min read · in .NET, Entity Framework, interview

  • lazy loading:

    • delaying load of data until we specifically request for it
    • i.e. accessing customer.Address loads Address of a customer in the background via separate SQL query
    • property needs to be public, virtual
    • context.Configuration.ProxyCreationEnabled should be true
    • context.Configuration.LazyLoadingEnabled should be true
    • to disable lazy loading completely Context.Configuration.LazyLoadingEnabled = false;
  • eager loading

    • opposite of lazy loading
    • loads related entities as part of the query
    • done via .Include() query

Further read:

Read the whole thing →

Pattern matching

· 103 words · ~1 min read · in .NET, interview

#design patterns #SOLID #C#

Pattern matching is used for: testing expression to check if some value have certain characteristics safer compare because &lsquo;==&rsquo; and &lsquo;!=&rsquo; can be overloaded Examples: a is int number sequence is IList&lt;T&gt; list switch statement: command switch { Operation.SystemTest =&gt; RunDiagnostics(), Operation.Start =&gt; StartSystem(), Operation.Stop =&gt; StopSystem(), Operation.Reset =&gt; ResetToReady(), _ =&gt; throw new ArgumentException(&#34;Invalid enum value for command&#34;, nameof(command)), }; switch with ranges: tempInFahrenheit switch { (&gt; 32) and (&lt; 212) =&gt; &#34;liquid&#34;, &lt; 32 =&gt; &#34;solid&#34;, &gt; 212 =&gt; &#34;gas&#34;, 32 =&gt; …

Read the whole thing →

Reflection

· 20 words · ~1 min read · in .NET, interview

#reflection

obtain information about types and members at runtime create instances, invoke or access them dynamic code generation Further read: https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection

Deployment models

· 35 words · ~1 min read · updated · in .NET, interview

Type Command framework-dependent executable for the current platform. dotnet publish framework-dependent executable for a specific platform. dotnet publish -r &lt;RID&gt; --self-contained false framework-dependent binary. dotnet publish self-contained executable. dotnet publish -r &lt;RID&gt; Further read: https://learn.microsoft.com/en-us/dotnet/core/deploying/#publish-framework-dependent

.NET AOT

· 46 words · ~1 min read · in .NET, interview

Ahead of the time compilation to machine code produces self-contained application which: starts quicker uses less memory does not require .NET runtime installed it is better for workloads with high deployment instances (clouds) makes runtime code generation impossible not all libraries are compatible Further read: https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/

.NET Jit

· 47 words · ~1 min read · in .NET, interview

Just - in - time compiler. part of CLR for all .net programs for all .net languages converts MSIL to native machine code compiles code when it is necessary at runtime also it is possible to pre-compile to native code at compile time instead Further read: https://www.geeksforgeeks.org/what-is-just-in-time-jit-compiler-in-dot-net/

Records

· 64 words · ~1 min read · in .NET, interview

can be class or struct creates methods overrides for enforcing value equality instead of reference equality: Object.Equals Object.GetHashCode operators == != implements IEquatable&lt;&gt; parameter implements ToString supports deconstruction supports with expression meant to be immutable Positional records is a more concise syntax for record: primary constructor parameters match the positional parameters of the record declaration public init-only properties for each parameter Further read: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records#characteristics-of-records

Is it possible to block GC?

· 26 words · ~1 min read · updated · in .NET, interview

We can. for some critical part of application code using GC.TryStartNoGCRegion method. using CER (Constrained Execution Regions) (obsolete) with GC LatencyModes Further read: https://learn.microsoft.com/en-us/dotnet/api/system.gc.trystartnogcregion?redirectedfrom=MSDN&view=net-7.0#overloads https://learn.microsoft.com/en-us/dotnet/framework/performance/constrained-execution-regions?redirectedfrom=MSDN https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/latency

Garbage Collector

· 67 words · ~1 min read · in .NET, interview

automatic memory management allocates and releases memory prevents memory leaks and accessing dead objects provides memory safety virtual memory space defragments/compacts memory heap have 3 generations 0 - for new objects; 1 - for objects that lives through GC from 0 2 - for long living objects from 1 and 0 also Large Objects Heap (LOH) for big objects like arrays over 85,000 bytes Further read: https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals?source=recommendations

Covariance and Contravariance

· 291 words · ~1 min read · in .NET, interview

#delegates

  • enables implicit reference conversions for
    • arrays
    • delegates
    • generic type arguments
  • Covariance preserves assignment compatibility
  • Contravariance reverses assignment compatibility
  • allows for matching signatures of delegates and method groups
    • to assign to delegates from method that returns more derived types - covariance
    • to assign to delegates from method that returns less derived types - contravariance
  • Covariance and Contravariance are supported in Generics for implicit conversions for type parameters
    • allows method to have more derived return type than defined by generic type parameter of the interface
    • this allows implicit conversions from one generic interface to another (from IEnumerable<string> to IEnumerable<object> even if first does not inherits from second)
    • allows generic types to have less derived argument types than specified by the generic parameter of the interface (implementation of IEqualityComparer<BaseClass> can be implicitly converted to IEqualityComparer<DerivedClass> because IEqualityComparer.Equals is contravariant)
    • implicit conversions works for interfaces but not classes that implement from those interfaces (i.e. this won’t work List<Object> list = new List<String>())

Assignment compatibility is when object of a more derived type is assigned to an object of a less derived type.

Read the whole thing →

.NET Generics

· 75 words · ~1 min read · in .NET, interview

#generics

Allow for:

  • generalization of logic based on available types
  • specify possible supported types
  • re-usability of code
  • type safety
  • defers the exact specification of logic until the class or method is declared and instantiated by user code with all type parameters specified
  • mostly used for collections (some non-generic versions of collection are not recommended like ArrayList i.e.)
  • information of exact type parameters used in a generic can be obtained at runtime by reflection

Further read:

Read the whole thing →

Data structures in .NET

· 71 words · ~1 min read · in .NET, interview

In table below official recommendations for choosing data structure for your needs:

GenericNon-GenericThread safePurpose
DictionaryHashtableConcurrentDictionarykey value pairs, lookup
ListArrayImmutableListaccess items by index
Queue-ConcurrentQueueFIFO queue
Stack-ConcurrentStackLIFO queue
LinkedList--access items sequentially
ObservableCollection--notfications after modification
SortedListImmutableSortedSetauto sorted collection
HashSetImmutableHashSetdictionary of just keys (high performance set operations)

Further read:

Read the whole thing →

Strings in .NET

· 49 words · ~1 min read · in .NET, interview

sequential collection of chars immutable max 2GB or about 1 billion characters reference type are interned - CLR saves memory by maintaining a table, called the &ldquo;intern pool&rdquo;, that contains a single reference to each unique literal string declared or created programmatically in your program. Further read: https://learn.microsoft.com/en-us/dotnet/api/system.string?view=net-7.0 https://learn.microsoft.com/en-us/dotnet/api/system.string.intern?view=net-6.0#remarks

What type can not be object field?

· 16 words · ~1 min read · in .NET, interview

ref struct type can not be used as object field. Further read: `ref struct` types https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct

`ref struct` types

· 66 words · ~1 min read · in .NET, interview

added as part of C# 7.2. defined with ref struct StructName always on the stack never part of heap cannot be element of an array cannot be field type of reference type can&rsquo;t implement interfaces can&rsquo;t be boxed can&rsquo;t be type argument can&rsquo;t be captured by closure of lambda or local function can&rsquo;t be used in async methods can&rsquo;t be used in iterators Further read: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct

Reference types vs Value types

· 41 words · ~1 min read · in .NET, interview

Reference types: passed via reference reside on the heap subject to GC inherits from System.Object Value types: passed via value reside on the stack, CPU registers or the heap no subject to GC inherits from System.ValueType Further read: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types https://www.infoworld.com/article/3043992/a-deep-dive-value-and-reference-types-in-net.html

.NET Type System

· 23 words · ~1 min read · in .NET, interview

shared type system across all .net languages primitives data types library 5 kind of types: classes structures enumerations interfaces delegates Further read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/common-type-system

ThreadPool

· 22 words · ~1 min read · in .NET, interview

provides a pool of threads can be used to execute tasks post work items process asynchronous I/O process timers Further read: https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadpool?view=net-6.0

Task Parallel Library (TPL)

· 23 words · ~1 min read · in .NET, interview

simplify process of adding parallelism and concurrency to application scales concurrency automatically data parallelism task based async programming data flow Further read: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl

Locking with integer

· 35 words · ~1 min read · in .NET, interview

In short: it will not work because it requires boxing and boxing will create new object for reference in lock every time code is executed so lock statement will not prevent anything. Further read: https://intellitect.com/blog/locking-a-block-of-code-with-an-integer/

Locking in .NET

· 141 words · ~1 min read · in .NET, interview

  • lock statement blocks execution of a code block for single thread that hold lock
  • the same thread can acquire and release lock again
  • any other thread is blocked from the statement
  • lock on dedicated instance only
  • using the same instance on multiple lock statements may lead to deadlock
  • avoid using as lock
    • this, as it might be used by the callers as a lock
    • Type instances, as those might be obtained by the typeof operator or reflection
    • string instances, including string literals, as those might be interned
  • Hold a lock for as short time as possible to reduce lock contention.

Below code block is translated by compiler

Read the whole thing →

Thread vs task in . NET

· 13 words · ~1 min read · in .NET, interview

task is asynchronous operation thread is abstraction on OS thread Further read: https://www.c-sharpcorner.com/article/task-and-thread-in-c-sharp/

What is SynchronizationContext in .NET

· 126 words · ~1 min read · in .NET, interview

  • multi threaded programs usually uses one of the threads as means of synchronization
  • there are message loops to pass unit of works (like Windows message queue)
  • message queues require messages formats and convention for handling it
  • single thread to handle ASP.NET request is waste of the resources (before .NET 2)
  • thread pool was better but inconvenient to work with
  • instead SynchronizationContext queues work for given context not thread
  • thread have current context
  • context does not have to be unique but can be shared between multiple threads
  • thread can change context but this is rare
  • SynchronizationContext keeps count of all asynchronous operations
  • Windows Forms uses WindowsFormsSynchronizationContext
  • WPF and Silverlight uses DispatcherSynchronizationContext
  • Console app and WindowsServices and ThreadPool threads uses default SynchronizationContext
  • ASP.NET uses AspNetSynchronizationContext

Further read:

Read the whole thing →

Does async/await creates new thread?

· 111 words · ~1 min read · in .NET, interview

#async

In short: no.

Longer explanation:

  • task that want to do I/O write call to driver write
  • driver operations are performed asynchronously
  • write operations on devices is done without CPU involved
  • finish of writing is done via interrupt
  • interrupt, schedules Deferred Procedure Call
  • DPC schedules Asynchronous Procedure Call
  • APC notifies thread that I/O write is done
  • task that was doing I/O is scheduled with continuation of its method after I/O is done.
  • some threads might need to be borrowed for handling APC and such but no thread is spawn to handle I/O

I recommend reading this post: https://blog.stephencleary.com/2013/11/there-is-no-thread.html . This will explain the topic much better than I can.

Read the whole thing →

Avoid deadlock with asynchronous methods

· 31 words · ~1 min read · in .NET, interview

#async

avoid doing AsyncOperation.Result parent method waits for Result while child method waits for parent thread to take control, after being done with async I/O both waits deadlock Further read: https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d https://stackoverflow.com/questions/15021304/an-async-await-example-that-causes-a-deadlock

Asynchronous programming in .NET

· 46 words · ~1 min read · in .NET, interview

#async #design patterns

Asynchronous programming patterns in .NET: Asynchronous Programming Model (BeginOperation/EndOperation) Event-based Asynchronous Pattern (invoke event with result from async job) Task-based Asynchronous Pattern (Task&lt;&gt;) Ways of achieving asynchronous code in .NET async, await Task class API (Run, WhenAll, WhenAny, etc.) ThreadPool.QueueUserWorkItem(ThreadProc); Further read: async/await in .NET https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/

async/await in C#

· 119 words · ~1 min read · in .NET, interview

#async

async/await syntax should be used for I/O bound asynchronous operations only.

public async Task<int> GetUrlContentLengthAsync()
{
    var client = new HttpClient();

    Task<string> getStringTask =
        client.GetStringAsync("https://docs.microsoft.com/dotnet");

    DoIndependentWork();

    string contents = await getStringTask;

    return contents.Length;
}

Compiler transforms code into a state machine that to track yielding execution for await and resuming execution when a background job is finished.

Things to keep in mind:

  • async method needs await
  • add Async suffix to asynchronous methods
  • async void for ‘Fire and Forget’ work i.e. event Handlers
  • be aware of mixing LINQ with async lambdas
  • wait for tasks in a non-blocking manner (do not use Task.Result i.e.)
  • for tight loops use ValueTasks
  • Consider using ConfigureAwait(false) for performance and for avoiding deadlocks

Further read:

Read the whole thing →

CPU bound vs I/O bound

· 158 words · ~1 min read · in .NET, interview

#async

There are two types of asynchronous operations in .NET.

  • I/O bound
  • CPU bound

For I/O bound async/await syntax should be used. TPL should not be used for this. async methods does not spawns new thread to hand le I/O work asynchronously.

For CPU bound operations TPL should be used (Task.Run). This spawns new thread. Performance testing should be done to check if overhead of new thread and context switching is not greater than actual work to be done.

Read the whole thing →

SupressFinalize in IDisposable interface

· 143 words · ~1 min read · updated · in .NET, interview

  • informs GC that object does not need to be added to finalizer queue
  • finalizer execution is not deterministic and objects can live for long time in queue - this is optimization technique
  • to make sure that object disposes of any unamanaged resources even if Dispose will be not called we need to implement finalizer

Basically finalizer execution time is not deterministic. We cannot predict when this will be called and till that time - object is existing and still taking memory space. Since we are controlling creation and disposal of those resources we can say to GC: ‘Do not worry about that! It already had been taken care of!’. So this way object will be destroyed sooner, leaving this space to be used by something else possibly.

Read the whole thing →

IDisposable interface pattern

· 218 words · ~1 min read · updated · in .NET, interview

#design patterns

Example implementation of IDisposable

public class MyResource : IDisposable
{
    public MyResource(IntPtr handle)
    {
        this.handle = handle;
    }

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(!this.disposed)
        {
            if(disposing)
            {
                component.Dispose();
            }

            CloseHandle(handle);
            handle = IntPtr.Zero;
            disposed = true;
        }
    }

    ~MyResource()
    {
        Dispose(disposing: false);
    }
}

MyResource object have pointer which is unmanaged. This is why this class should implement IDisposable interface. Implementation should be correct according to recommended pattern (see below for documentation).

There a re few points to highlight here:

Read the whole thing →

Automatic scrolling to edited text box in Xamarin Android.

· 858 words · ~4 min read · updated · in .NET, Android, C#, Xamarin

Important note: this should work well with newer version of Xamarin (2.3.3). If you cannot update for some reason this article will explain workaround.

Introduction

In previous article I explained how to detect show and hide events of software keyboard in Xamarin Android. I did it in my project because of the fact that some of text boxes was hidden by software keyboard that suppose to edit contents of those text boxes. In this article I will explain how to work around this issue in some older versions of Xamarin.

Read the whole thing →

Xamarin with TinyIoC

· 3190 words · ~15 min read · updated · in .NET, Android, C#

#XAML #dependency injection #Xamarin

Introduction

This article is builds on topics and solutions introduces in ViewFactory for Xamarin application and Xamarin Master-Detail Page articles. It shows method for easier navigation and use of services via IoC in Xamarin application. Knowledge from previous examples is not necessary, but makes this article bit easier to understand.

Read the whole thing →

Genereting proxies during runtime using Reflection.Emit

· 4156 words · ~20 min read · updated · in .NET, C#, WCF

#reflection #self-hosting #delegates #XAML

Reflection.Emit is very powerful tool. It creates IL code and since C# is converted into IL too, we have the same functionality as in C# and even more. It is very powerful and at the same time very complicated. Because of that it is worth to discuss how and for what it should be used. One idea is to create dynamic code with automatic implementations of interfaces - proxy types.

Read the whole thing →

Faster than Reflection: Delegates. Part 3.

· 6868 words · ~34 min read · updated · in .NET, C#

#delegates #reflection #generics #NuGet

This is third article in series, that explains how to create delegates for public and non-public members of public, non-public or not known in compile-time types. If you are not familiar with previous articles and looking for detailed explanation of how delegates works, how they are created and why, I strongly encourage you to read first two. If you are just looking for a way to create delegates for methods or constructors it is not necessary. Code with new features and with bug fixes is available on GitHub and as Nuget package.

Read the whole thing →

Faster than Reflection: Delegates. Part 2.

· 5330 words · ~26 min read · updated · in .NET, C#

#delegates #reflection #NuGet

This is second article in series, that explains how to create delegates for public and non-public members of public, non-public or not known in compile-time types. If you are not familiar with previous article and looking for detailed explanation of how delegates works, how they are created and why, I strongly encourage you to read it first. If you are just looking for a way to create delegates for methods or constructors it is not necessary. Last article in series you can find here . Code with new features and with bug fixes is available on GitHub and as Nuget package. In previous article and first one in series, we covered:

  1. Static
    1. Properties
    2. Fields
  2. Instance
    1. Properties
    2. Fields
    3. Indexers

Now it is time to cover following members.

  1. Static
    1. Methods
  2. Instance
    1. Methods
    2. Constructors

Read the whole thing →

Faster than Reflection: Delegates. Part 1.

· 10477 words · ~52 min read · updated · in .NET, C#

#delegates #reflection #NuGet

This article is first part of the series of three. Next ones you can find here and here . Code for all three articles, with new features and bug fixes is available on GitHub and as Nuget package.

Why not Reflection?

If you working with .NET and C# (probably other languages too), at some point, you will have to write more advanced and generic code, that i.e. reads all properties of a type, searches for attributes, etc. Or maybe you want to call some private method or property? It is not that rare to use some internal mechanism of framework or library. Usually, the first solution involves Reflection. But the thing is: Reflection is slow. Of course, it is sufficient if you need to use Reflection rarely and it is not the main code of the application. If it is used more often at some point, you will probably try to optimize it. And now is the fun part: how to do it?

Read the whole thing →

ViewFactory for Xamarin application

· 5652 words · ~28 min read · updated · in .NET, Android

#delegates #reflection #async #XAML

First things first - Why?

First of all I do not like how creating of views and navigation works in Xamarin. There is much boilerplate needed to just navigate from one page to another. Typically like in Xamarin documentation we have to obtain INavigation interface instance, create instance of a new page, create instance of view model and all dependencies it requires. When you page do not require view model things are real easy and Xamarin sample is just enough.

Read the whole thing →

Xamarin Master-Detail Page

· 5408 words · ~27 min read · updated · in .NET, C#

#XAML #design patterns #Xamarin

This article as previous ones (Frame With Padding , Frame Outline Problem , Inheritance from Implicit Styles ) also will be about Xamarin. This time we will inspect Master-Detail page control/mechanism. You can find official documentation for this control here . Quick spoiler: I never used this in any production application. Why? I will explain. Whole article will be to explain why this is just not worth your time. In this and subsequent articles I will introduce much better solution.

Read the whole thing →

Xamarin Style based on implicit Style

· 1251 words · ~6 min read · updated · in .NET, C#, Xamarin

#XAML #WPF

Next article about bugs in Xamarin will touch topic of Styles. Styles for all of controls not only Frame (and if you wondering why Frame you should check first two articles about Xamarin here and here) . First of all if you are using Styles in Xamarin you probably know how to define implicit styles. If not here is a sample:

<Application.Resources>
  <ResourceDictionary>
    <Style TargetType="Label">
      <Setter Property="FontSize" Value="45" />
    </Style>
  </ResourceDictionary>
</Application.Resources>

Read the whole thing →

Xamarin Frame and disappearing Outline

· 777 words · ~3 min read · updated · in .NET, Android, C#, Xamarin

#XAML

This is another article in mini series of Xamarin bugs and workarounds for them :) Previous one you can find here . This one is again about Frame control. I promise that another one will be about something else B) Issue can be observed when you bind BackgroundColor property of Frame control and something will trigger change of view model source property binded to background color.

Read the whole thing →

Xamarin Frame and Style with Padding

· 496 words · ~2 min read · updated · in .NET, Android, C#, Xamarin

#XAML

If you are a bit advanced with Xamarin you should already now that there is possibility of styling your controls almost like in WPF. Almost, because there is a few strange bugs involving this. For example there is a problem with styling a Padding property in Frame. Consider following Xaml of Xamarin application (I tested it in Android):

Read the whole thing →

Safe cast string to enum

· 1039 words · ~5 min read · updated · in .NET, C#

#enums

In on of my projects I had make an interface between database and web service in C# code. One of problem I had to face was need to cast strings to enumerable types, because of simple fact that database have no idea what is an ’enum’. Yes simplest mapping between an enumeration and database type is integer. It is simplest but in my idea not best. For example I really do not remember (or do not WANT to remember) what is the meaning of 4 integer value in case of package shipment status.

Read the whole thing →

Smart string builder

· 579 words · ~2 min read · updated · in .NET, C#

In this rare times when I was writing code that suppose to create large string from smaller chunks and with some non string parameters I was using StringBuilder class of course. Of course because string adding, or string concatenation is very costly when talking about memory utilization. It is because every time you do this:

var text = "Hello world!"+ "n"+ "How are you?";

new string is created for every ‘+’ operation in memory. Not a best way of doing strings creations. StringBuilder is better because it do not creates strings until you call .ToString method of StringBuilder class.

Read the whole thing →

Expression parsing and nested properties

· 729 words · ~3 min read · updated · in .NET, C#

In one of projects I was working on, I needed to get property value from property path and property path from expression. First, lets cover second case. With expression in form of nested property value:

()=>object1.object2.object3.object4

we cannot take simple value of some property, because we have only root object, object1.

Read the whole thing →

WebSocket libraries comparison

· 1786 words · ~8 min read · updated · in .NET

#WebSocket #async #ASP.NET MVC #NuGet

Web project often requires to push data to clients as fast as possible, whenever it is necessary without waiting for client request. It is perfect for website with real time communication between users, like with online communicators for example. Or document collaboration tools. Or maybe system status updates on long running calculation/tasks performed by server. In every case two way communication mechanism is ideal.

Read the whole thing →

Ninject and WCF

· 817 words · ~4 min read · updated · in .NET, ASP.NET

#Ninject #WCF #API design

Ninject is very simple and in the same time powerful IoC container. I used it in few project and had very little or none problems. Most of the time getting instances from Ninject kernel requires simple line with binding expression, or even this is sometime unnecessary if type is self bind able (i.e. if it is concrete class with parameterless constructor). Little harder is getting Ninject to work with WCF. You cannot just bind interfaces types because proxies which implements them are created through .NET mechanism. Luckily WCF system is very flexible and mostly can be changed/extended with custom functionality.

Read the whole thing →

Entity Framework and Base Entity class

· 906 words · ~4 min read · updated · in .NET, Entity Framework

#AutoMapper

Entity Framework does great job with taking care of entities changes and entities collection internally. And its uses almost plain POCO objects. Almost because collections of dependents data like in 1 to many tables relationship needs virtual keyword. Its understandable since EF needs to track what happens to collection. For instance lets have 2 tables: Customer and dependent Order.

Read the whole thing →

Ninject and Entity Framework

· 730 words · ~3 min read · updated · in .NET, C#, Entity Framework

#Ninject

Last time I wrote about problem with testing Entity Framework in Visual Studio 2012. During working on this project I also encounter problems with configuration of Ninject to allow injecting Entity Framework classes from its Patterns extension. To be frankly this was not much a problem then lack of documentation. I just was forced to experiment with Ninject and new-thing-for-me Entity Framework Patterns extension.

Read the whole thing →

Curious Case of Visual Studio project compatibility.

· 320 words · ~1 min read · updated · in .NET, Visual Studio

Recently I was asked at work for quick review of small project. It was created (or updated) in newest version of Visual Studio - 2012. I don’t have installed VS 2012. I could install it, yes, but it would be just waste of time since browsing through code in that project took me only few hours. So I decided to try to open that in VS 2010.

Read the whole thing →

Using Matlab from C# application.

· 1606 words · ~8 min read · updated · in .NET, C#, Matlab

While writing an application for my Masters degree diploma, I wrote a simple application that was using COM Matlab server. I have found it hard to use it mainly due to lack of documentation, which is really basic with only few code examples for C#. I guess writing programs that use Matlab for calculating is not encouraged by MathWorks, you would became competition that way :) Nonetheless, I accomplished why I was required to do, so I decided to share this with the rest of the world.

Read the whole thing →

Server controls in separete assembly part 2

· 795 words · ~3 min read · updated · in .NET, ASP.NET, C#

Yesterday I was writing about creating server controls in separate assembly . Today I will cover more complicated example then simple “Hello World!” control. My goal was to create text box that will take handler method to run when validation event will be triggered, and when validation fail will show appropriate message. Text box with builtin validation would be nice, since you always should validate user input , right? But lets start creating our control.

Read the whole thing →

Server controls in separate assembly

· 394 words · ~1 min read · updated · in .NET, ASP.NET, C#

In my project I wanted to create text box control with builtin configurable validation. ASP.NET definition in .aspx or .ascx file would get validation function by name. But I do not wanted to create just .ascx file with text box. I could not then reuse that control in other projects and it certainly would be nice, right? Creating such server control from code is not hard, but maintainability of HTML code in C# (it cannot be done other way) is not good. It’s pain really. Why Microsoft would create way to automatically create C# code from .ascx, .aspx files is mystery for me.

Read the whole thing →

Better algorithm for finding UpdatePanel that will be updated during page request.

· 496 words · ~2 min read · updated · in .NET, ASP.NET, C#

#UpdatePanel

Other day I was experimenting with finding which UpdatePanel will be updated during page post back. I found out that my solution was not working correctly for complex triggers, like user controls with custom events, which will trigger async postbacks and update of panel. Or for grids with buttons. It was big issue. Also it was not pointing to correct UpdatePanel if name of control was not entirely unique (for example when you have multiple same custom controls on page). It would return first panel, even if it wasn’t updating.

Read the whole thing →

Display message on client from anywhere in code with ASP.NET

· 890 words · ~4 min read · updated · in .NET, ASP.NET, C#

#UpdatePanel

When I was working with WinForms application in previous work I have found one of most useful feature, ability to show some message to the client. For example user cannot edit some entity in particular time (it is being edited by someone else) or should change password because it will expire in x days. I wanted to do something similar in my web application.

Read the whole thing →

Getting private field or property from object

· 201 words · ~1 min read · updated · in .NET, C#

Yesterday I was playing with finding all UpdatePanel controls on page during generating response in ASP.NET. Since object with this information is private itself and collection of panels is private in that object, I had to write some code to extract that data. I ended up with to extension methods for Object type, for getting private field an private property. It’s pretty straightforward, besides one thing: since member is private. And we don’t know in witch type exactly (every type in base/descendant hierarchy have it’s one private members) we have to search them all. So this is final code:

Read the whole thing →