Loop Through The Diagonal Elements In Two Dimensional Array

0
Comments

If you need to only loop through the diagonal elements of the two-dimensional array you can use the following C# code (but should be more or less the same for any programming language). It calculates the diagonal index based on a simple formula and has O(n) complexity, where n = max(width, height)

Read further...

Deploy and run .NET Core application without installed runtime. Self-contained applications.

2
Comments

.NET Core framework provides one very useful feature - Self-contained application. You don't need to install any .net runtime on your computer, you can just copy your application to the target host and run it. Furthermore, you can run it on any platform (Windows, Linux, OSX)! When you create a self-contained application, after publishing, you will see the whole .net runtime next to your application. There are some advantages: You do not need to have installed .NET Core on a target machine You ca...

Read further...

Speed up Selenium WebDriver's page parsing time

0
Comments

If you are using Selenium WebDriver as a web crawler and thinking that it's too slow, welcome inside! In this article, we will see how to make page parsing time around 50 times faster. As an example, I will parse comments from another article from this blog. I will first parse it using default WebDriver API (FindElement... methods) and then will compare it to CsQuery Here is WebDriver parsing code: var driver = new ChromeDriver(); driver.Navigate().GoToUrl("/2014/07/fixed-setup-was-unable-t...

Read further...

[Mono] Selenium with headless ChomeDriver on Ubuntu Server

0
Comments

If you want to run C# application (mono) with Selenium ChomeDriver on Ubuntu Server 16.04 in headless mode, you definitely should read this article. We will use Xvfb as X server, this will let us emulate "headless" mode because Xvfb performs all graphical operations in memory without showing any screen output. Install mono sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF echo "deb http://download.mono-project.com/repo/debian whe...

Read further...

ZohoPeopleTimeLogger v1.4 - Smart filtering

0
Comments

Changes: Show vacations only for currently logged in user (Previously, if you have access to other user's leave tracker you will see his days off as your vacation) Show only days off with Holiday and Sick type (Exclude 2hours short leave and others) Display leave type in calendar (Before was always Vacation, now Holiday or Sick) Download (GitHub) ZohoPeopleClient This C# library was also updated to v1.0.2. There are two new methods available in Fetch Record API: public enum SearchColumn { EMPLOY...

Read further...

C# 7.0 Pattern Matching. Part1

1
Comments

Great news! You can already try new C# 7.0 features. All you need is Visual Studio 15 Preview. Let's start! Today we are going to talk about Pattern Matching and will look under the hood of this nice feature. Unfortunately, it is only partly available in VS 15. So we need to wait until next release. Or you can try to get latest Roslyn from GitHub. is operator The is operator is extended to test an expression against a pattern. With that you can replace this: object obj = "Hello, World!...

Read further...

C# 7.0 Local Functions

10
Comments

C# 7.0 is coming! Even 6.0 is not released yet, you can already try new C# 7.0 features. To do that you need: Visual Studio 15 preview Set __DEMO__ and __DEMO_EXPERIMENTAL__ as Conditional compilation symbol in project settings. Not all of the new features available in current preview, but you can already play with some of them. But today we gonna look closer at Local Functions private static void Main(string[] args) { int LocalFunction(int arg) { return 42 * arg; } Console.WriteLine(LocalFuncti...

Read further...

[Unity3d] Serialize and Deserialize System.Guid using JsonUtility

1
Comments

Unity3d 5.3.0 introduced JsonUtility class which will help you with JSON serialization and deserialization. But this class has some limitation, and one of them: "You cannot serialize\deserialize System.Guid type" That's a pity, especially if you're using System.Guid in your DTO objects. But, there are solutions: You can change a data type, for example, use System.String or System.UInt32 instead of System.Guid. But if you have a lot of code which uses your DTO objects it might be painful to refac...

Read further...

[ASP.NET Core 1.0] Automatic Migrations in Entity Framework 7 (EF Core 1.0)

1
Comments

There is no more public Configuration() { AutomaticMigrationsEnabled = false; } in Entity Framework Core 1.0 (formerly  EF 7.0) Now you can use extension Migrate method during database initialization. For example, you have custom DBInitializer class: public class DBInitialization { public static void Initialize() { using (var context = new DbContext()) { context.Database.Migrate(); // Other db initialization code. } } } There is also async version of this method. This method will apply any pendi...

Read further...

ZohoPeopleTimeLogger v1.3 - Show me the error

0
Comments

At Novility, we have  found that we cannot log working time anymore. You just press "Make me happy" button and nothing :( When ZohoPeopleTimeLogger tries to make you happy it needs information about current jobs from ZOHO. For example, if I try to log time for January 16 and there is no job for this date I will get an error. But user was not able to see that error. That is fixed in release v1.3. Download GitHub User will see message box with detailed description and nice instructions:

Read further...

Build and test ASP.NET 5 application using AppVeyor

1
Comments

For those who do not know, AppVeyor is Continuous Integration and Deployment service for .NET projects. It is free for open-source projects. Currently, AppVeyor supports latest DNX version (1.0.0-rc1-final) and I've recently migrated my pet project to this version. I will show you how easy it is to build and run all unit tests on CI server every time you commit to GitHub. Visual Studio project (MSBuild) In LearnWordsFast project we are using Visual Studio 2015 as a development environment, so in...

Read further...

[ASP.NET 5] Lazy DBContext initialization with Entity Framework 7

2
Comments

I will show you how to do lazy db context initialization with Entity Framework 7. The idea is simple, we need an easy way to get database context in a request. If db context was used in the request we should call SaveChanges method and dispose used context if not we shouldn't do anything. For "client", code should look like this: public class SomeRepository { private readonly IDbContext _db; public SomeRepository(IDbContext db) { _db = db; } public void Add(Item item) { _db.Current.Items.Add(ite...

Read further...

[WPF][MVVM] TreeView: Scroll To Selected Item

0
Comments

Here is the MVVM way to bring selected TreeViewItem into a view. First we need an attached behavior. We cannot use regular behavior because we will attach this property through Style. public class BringSelectedItemIntoViewBehavior { public static readonly DependencyProperty IsBringSelectedIntoViewProperty = DependencyProperty.RegisterAttached( "IsBringSelectedIntoView", typeof (bool), typeof (BringSelectedItemIntoViewBehavior), new PropertyMetadata(default(bool), PropertyChangedCallbac...

Read further...

[ASP.NET 5] Production Ready Web Server on Linux. Kestrel + Supervisord

2
Comments

In the previous article I've used nohup + su + init.d script to run kestrel in a background. But as Daniel Lo Nigro suggested in comments it's much easier to do the same with Supervisor And he was absolutelly right, config is much smaller, and you can easelly see status and output of a program. First, install supervisor: sudo apt-get install supervisor Now you can create config for your application: sudo nano /etc/supervisor/conf.d/kestrel_default.conf With following content: [program:kestrel_de...

Read further...

ZohoPeopleTimeLogger v1.2 - Special for Andre

0
Comments

Because Andre is so special, the previous version of ZohoPeopleTimeLogger was not working with his account. I've fixed couple issues in the program to make him happy. Now, my friend, you can enjoy this lovely program! This release (v1.2) is dedicated to you! Download Now seriously! There was a small issue in a way I got information from zoho. I used user email to get user specific data (time log) but as I found out it is case sensitive, so Andre@something.com and andre@something.com are differen...

Read further...

[C#] Zoho People Client Library

0
Comments

 Zoho People Client v1.0.0 released. ZohoPeopleClient - C# asynchronous client library to interact with the Zoho People API. Supported API TimeLogAPI (Get/Add/Delete) JobsAPI (Get) LeaveAPI (GetHolidays) FetchRecordAPI (Get) NuGet Package Source Code GitHub Current Release Build Status Examples Sign in with login and password var client = new ZohoClient(); var token = await client.LoginAsync(login, password); // save token for further use Sing in with token // load token from storage var client...

Read further...

ZohoPeopleTimeLogger v1.1 Even Smarter Than Before

0
Comments

Yes! It finally happened. New version of ZohoPeopleTimeLogger released :) Download In ZohoPeopleTimeLoger v1.1 you don't need to think about your time tracking at all! This smart program will do everything for you. Do you have any booked vacation in this month? Not a problem. Press "Make me happy!" button and ZohoPeopleTimeLogger will fill all days in this month except vacations   The same with public holidays! It will leave them empty... But, wait for this..... You can now fill in a single...

Read further...

ZohoPeopleTimeLogger v1.0.0 Keep Your Time Tracker Up-To-Date

0
Comments

Are you tired of filling in monthly time reports in Zoho People because of it's stupid UI? Then ZohoPeopleTimeLogger is just a right solution for you. Only one button which will make you happy! One click and you are done!   How does it work? ZohoPeopleTimeLogger will automatically find Job that is relevant for the selected month and will fill each empty day with 8 non-billable hours. That's all! If you don't need any of those days, just press a delete button... Easy, right? So why do you st...

Read further...

[ASP.NET 5] Production Ready Web Server on Linux. Run Kestrel In The Background

3
Comments

In the previous article we have installed nginx as a "gate" for our ASP.NET 5 application. Today we will see how to start kestrel server in the background. We will do even more, we will create init.d script to control our APS.NET 5 application and start it on  the system's startup. The simplest way to start kestrel in the background from console: nohup k kestrel & But if you want to start your application at the system's startup you need init.d script. Eventually, we will have following comm...

Read further...

C# 6.0 await in catch/finally

2
Comments

C# 6.0 become more asynchronous-friendly than before. Finally, you can use await keyword in catch and finally blocks! Here is example: class Program { static void Main(string[] args) { do { Console.WriteLine("Before caller " + Thread.CurrentThread.ManagedThreadId); CallerMethod(); Console.WriteLine("After caller " + Thread.CurrentThread.ManagedThreadId); } while (Console.ReadKey().Key != ConsoleKey.Q); } public static async void CallerMethod() { try { throw new Exception(); }...

Read further...

[Raspberry Pi 2] Create C# Background Application for Windows 10 IoT Core

18
Comments

In this article,  we will see how to create simple Web Server for Raspberry Pi 2 running Windows 10 IoT Core. Because it is a Web Server we don't need UI for this application, we can run it in headless mode. Open Visual Studio 2015 RC and create Windows IoT Core Background Application solution. Now we need a web server. This will be simple one. It will always response with "Hello, World!" string. internal class WebServer { private const uint BufferSize = 8192; public void Start() { StreamSocketL...

Read further...

[vNext] ASP.NET 5 Automatic Migrations with Fluent NHibernate

0
Comments

As I said in the previous article, I am gonna tell you about Automatic migrations with NHibernate and Fluent NHibernate in ASP.NET 5 applications. Automatic migrations is a really powerful feature, but you should be also really careful with it. Sometimes it might corrupt your schema or even data. Now back to ASP.NET 5 and migrations. I have already explained how to install and configure Postgresql with NHibernate. To enable automatic migrations you need to modify configuration a bit: private sta...

Read further...

[ASP.NET 5] Production Ready Web Server on Linux. Kestrel + nginx

7
Comments

You can run ASP.NET 5 applications on Linux using kestrel web server. This is development web server, so it has limited functionality. But sometimes you need more functions, for example, https or virtual hosts support. Today we will see how to configure a system, so you can access your application through a domain name. First, you need ASP.NET 5 environment up and running.  You can use my article to install and configure everything, but it's a bit outdated, so it's better to use official documen...

Read further...

C# 6.0 Detailed Overview Of The New Features

0
Comments

C# 6.0 has a lot of great new features, which save developer's time and make code more clean and short. At the conclusion of the C# 6.0 series let's go through the whole list of the new C# 6.0 features again (all titles are active). Each article contains detailed explanation of the particular feature with resulted IL code and "old-school" way of doing the same things. String Interpolation var a = 1.2345; Console.WriteLine($"test {a}"); Console.WriteLine($"test {a} {a} {a}");...

Read further...

C# 6.0 Expression-Bodied Methods

2
Comments

The last but not the least feature of the C# 6.0 that I am going to cover is expression-bodied methods. We all have experience writing single line methods: private string name; public override string ToString() { return "Name :" + name; } Now, we have shorter way of defining the same method: public override string ToString() => "Name: " + name; As you can see, now we can use lambda style to define method's body. But there is one difference from lambda expressions, we canno...

Read further...

C# 6.0 Index Initializers

0
Comments

Hi, folks! Today we are gonna talk about new indexer initialization syntax introduced in C# 6.0. As we know, we already have good way to initialize dictionary: var dic = new Dictionary<string, int> { {"Apple", 2}, {"Pear", 10} }; but in C# 6.0 we have a better way to do the same: var dic2 = new Dictionary<string, int> { ["Apple"] = 2, ["Pear"] = 10 }; As for me, it is a bit nicer because we already have curly brackets in the beginning and endin...

Read further...

C# 6.0 Exception Filters. try catch when

0
Comments

Exception filters is a new C# 6.0 feature. Visual Basic.NET and F# have this functionality for a long time. That is because exception filtering was implemented in CIL but not in C#. Now, this technique available for us. That's how you can use it: try { Method(); } catch (Win32Exception ex) when (ex.NativeErrorCode == 0x07) { // do exception handling logic } catch (Win32Exception ex) when (ex.NativeErrorCode == 0x148) { // do exception handling logic } catch (Exception) { // log unhandled excepti...

Read further...

C# 6.0 Auto-Property Initializers

0
Comments

The next new feature of the C# 6.0 is auto-property initializers and get-only auto property. The main problem that they suppose to solve is immutable type declaration. Before C# 6.0, if you want to create immutable type with properties, you have no possibility to use auto property: public string Property { get; set; } So, you were forced to use regular get-only (read-only) property with read-only backing field: private readonly string prop; public string Prop { get { return prop; } } public Ctor...

Read further...

C# 6.0 nameof Operator

1
Comments

C# 6.0 has a lot of new features, one of them is nameof operator. Let's see how it's implemented internally and what we can do with it. This operator will help us get rid of "magic strings" in our code. We all know following use case: public void Method(int arg) { if (arg < 0) { throw new ArgumentOutOfRangeException("arg"); } } With nameof operator we can rewrite code in a nicer way: public void Method(int arg) { if (arg < 0) { throw new ArgumentOutOfRangeException(nameof(arg));...

Read further...

C# 6.0 Null Propagation Operators ?. and ?[]

1
Comments

C# 6.0 introduced two new null-propagation operators: ?. and ?[]. They will make null reference check much easier. In this article, we will see how they work and how they implemented internally. We all know about NullReferenceException and how to avoid it in our code. We just need to check everything for null before accessing some fields\properties\methods. Null Propagation Operator ?. var str = GetString(); if (str != null) { return str.Length; } else { return 0; } Now we can use Null Propagati...

Read further...

C# 6.0 String Interpolation

0
Comments

One of the top ten requests on uservoice is String Interpolation. Today we are going to see how to use this feature and how it is implemented in C# 6.0. We all use similar expressions: var str = string.Format("Date: {0}", DateTime.Now); This is string interpolation in C# before 6.0. Now, in C# 6.0, we have new string interpolation technique: var str = $"Date: {DateTime.Now}"; There was nothing new added in to runtime, this is just a syntaxis sugar for "old shcool" interpolati...

Read further...

Raspberry Pi 2 Benchmark. Linux vs Windows

4
Comments

I have installed Windows 10 on Raspberry Pi 2, then I have created a simple C# application for it. Now, I am curious what is the difference in performance between Windows 10 IoT Core and Raspbian. To test that I will run a simple C# code on both OS. Code I will do a simple calculation in a loop and will run this code in multiple threads. The amount of threads - 4, because Raspberry Pi 2 has 4 cores. This will load CPU up to 100%. I know that I am using different CLRs and different compilators, b...

Read further...

Create C# Universal Application for Raspberry Pi 2

1
Comments

It is time to create our first C# Windows 10 Universal Application for Raspberry Pi 2. You can find LED blinking example in an official documentation, so today we are gonna create weather application. This application will connect to the remote server and get actual weather information based on city and country name, and display this information on a screen. Prepare your computer Download Visual Studio 2015 Community Edition RC Select Custom installation and enable Universal Windows Apps Develop...

Read further...

[Unity3d] Yet Another State Machine for Unity3d

0
Comments

If logic in your controller to complex for 'if' or 'switch\case' constructions, here is small State Machine implementation for you. Let's start with example how to use this state machine, and then we go through implementation details: public class Test : MonoBehaviour { private StateMachine stateMachine; private State firstState = new State(); private State secondState = new CustomState(); private State finishState = new State(); // Use this for initialization void Start () { var initChild = new...

Read further...

[Unity3d] How-to play video in Unity project. MovieTexture

3
Comments

If you want to play movie clip in your Unity3d project you need to have Pro version! If you are using Windows machine you also need to have QuickTime installed. After you have everything prepared just drag (or copy) your movie clip into Asset folder, after that you will see it imported. You need a MovieTexture instance to use imported clip. To play movie clip use following code: MovieTexture movie; public void Play() { movie.Play(); } To stop or pause: movie.Pause(); movie.Stop(); You can access...

Read further...

[vNext] ASP.NET 5 Dependency Injection with Autofac

1
Comments

In this part of the vNext tale, I am gonna tell you about dependency injection in ASP.NET 5 (vNext) stack. Default Dependency Injection container First, let's see what is shipped with ASP.NET 5 by default. There is already simple DI container. It gives you a possibility to register service with three different lifetimes: scope, singleton and transient. For now it supports only constructor injection. Let's see how to use it and what is the difference between these lifetimes. Create empty ASP.NET...

Read further...

[Unity3d] ReadOnly InputField

1
Comments

New UI system was introduced in Unity3d 4.6, it includes InputField control, but this field could not be read only. You can make it non interactable by disabling "Interactable" property in the editor, but then you will not be able to select and copy text from InputField. To have proper ReadOnly input field you should do small modification to the original control: using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [AddComponentMenu("UI/Read Only Input Field", 32)]...

Read further...

[Unity3d] WaitForFrames in Coroutine

1
Comments

If you are using Coroutines in Unity3d, you probably know about WaitForSeconds, WaitForEndOfFrame and WaitForFixedUpdate classes. Here is an example: public IEnumerator CoroutineAction() { // do some actions here yield return new WaitForSeconds(2); // wait for 2 seconds // do some actions after 2 seconds } But sometimes you need to wait for some amount of frames before executing some action. I have created simple class to help you with that: public static class WaitFor { public static IEnumerato...

Read further...

[Решение] Ошибка "The ‘Microsoft.ACE.OLEDB.12.0′ provider is not registered on the local machine"

0
Comments

Причины проблемы: Microsoft.ACE.OLEDB.12.0 драйвер имеет две версии: x86 и x64. Эти две версии не могут быть установленные одновременно, соответственно если ваше .net приложение собирается под AnyCPU то в случае 64 битной системы оно будет пытаться использовать 64 драйвер, и наоборот. Решение: - В Configuration Manager установите сборку приложения под x86 платформу (BUILD > Configuration > Active > Solution > Platform > x86) - Установите x86 драйвер Microsoft.ACE.OLEDB.12.0 Альтер...

Read further...

[vNext] Use PostgreSQL + Fluent NHibernate from ASP.NET 5 (DNX) on Ubuntu

7
Comments

In the previous part we have installed APS.NET 5 application on Ubuntu, now we are gonna install and configure PostgreSQL on Ubuntu and access database from our application through NHibernate. Install and configure PostgreSQL First, install PostgreSQL: sudo apt-get install postgresql postgresql-contrib Next, set root password: sudo -u postgres psql postgres \password postgres And then create test database: sudo -u postgres createdb mydb Add Fluent NHibernate to the application Open project.json...

Read further...

[vNext] Install ASP.NET 5 (DNX) on Ubuntu

10
Comments

ASP.NET MVC application on Linux? Easy! As you may know, Microsoft recently released a lot of their products under MIT license. .NET Core runtime, .NET CoreFX, ASP.NET 5, MVC 6, Entity Framework 7, MSBuild, everything is now available on GitHub. Our goal is: run Asp.Net MVC application with postgresql database on ubuntu server Today we are gonna start with setting up .NET environment. In the new asp.net stack you can choose between full .NET runtime and .NET Core. For now .NET Core has a lot of...

Read further...

[How-to] Record sound in .NET application

0
Comments

First import mciSendStringA from winmm.dll: [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback); To start recording: mciSendString("open new Type waveaudio Alias recsound", null, 0, 0); mciSendString("set recsound time format ms bitspersample 16 channels 2 samplespersec...

Read further...

[WPF] Binding ItemsSource to Enum

2
Comments

Suppose you need to bind ItemsSource dependency property to enum's values. For example in ComboBox. You have following enum: public enum ExampleEnum { Red, Green, Yellow } Now you can use ObjectDataProvider <Window x:Class="ExampleApplication.Window" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace...

Read further...

[How-To] Horizontal Field Of View for Unity3d camera

0
Comments

In Unity3d you can change only vertical field of view for a camera by default. This means whenever you change height unity will automatically scale environment. But if you change width unity will just add some space (or decrease) to left and right side of the screen (no content resizing). If you want to have opposite behavior, so when you increase width all content will  be scaled and if you increase height only space added to the view, you need to modify camera fieldOfView field. Here is a simp...

Read further...

[Fixed] The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

12
Comments

The problem arises when you have your application compiled for AnyCPU Platform, you are running on a 64bit system and the installed ADO.NET provider (Microsoft ACE.OLEDB.12.0) is the 32bit version. When using the AnyCpu target Platform your code will be executed as 64bit code on 64bit systems and as 32bit code on 32bit systems. An application executed as 64bit cannot use 32bit drivers (and viceversa). The Microsoft.ACE.OLEDB.12.0 has two different version for 64 and 32bit that cannot be installe...

Read further...

Enity Framework "column in table is of a type that is invalid for use as a key column in an index"

1
Comments

After adding Index attribute with IsUnique set to true for string value in my code first model [Index(IsUnique = true)] public string Email { get; set; } , I've tried to update my database, but got following error: "column in table is of a type that is invalid for use as a key column in an index". I've got this error because unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for my field would be 450 characters. To add th...

Read further...

[urlHandler] MSI installation released

0
Comments

Now you could install UrlHandler by using msi installation. This installation is in progress now, so for now it is necessary to perform some post installation steps. In the future all installation process will be automated. Please read README file. Download: Msi installation Source code 

Read further...

[sevennet.org] Идея заработка в интернете

2
Comments

Решил я заработать деньжат в интернете, но вестись на разводы "легкого заработка в интернете" я не собирался. Подумав немного на чем в интернетах можно сделать денег, была выбрана реклама. Но для заработка на рекламе нужны посетители и сайт на который они будет заходить. Для заходов нужно появляться в поисковой выдаче, а что бы быть не в самом конце списка желателен уникальный контент. [caption id="" align="alignright" width="330"] КДПВ[/caption] Но где брать уникальный контент? Тут то мне и при...

Read further...

[WPF] ContextMenu Commnad binding issue fixed

0
Comments

If there is no focused element in the window's main focus scope, the CanExecute routing will stop at the ContextMenu, so it will not reach to the CommandBinding on the Window, one workaround is to bind MenuItem's CommandTarget to the main window. <ContextMenu > <ContextMenu.Items> <MenuItem Command="ApplicationCommands.Open" CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/> </ContextMenu.Ite...

Read further...

[WPF] Auto Scroll Behavior for ListBox

3
Comments

If you want scroll ListBox to the end automatically when new item added in ItemsSource collection you could use following attached behavior. This approach perfectly suit for MVVM way. ListBoxBehavior.cs: using System.Windows; namespace ListBoxBehavior { /// <summary> /// ListBox AutoScroll attached properties /// </summary> public static class ListBoxBehavior { public static readonly DependencyProperty AutoScrollProperty = DependencyProperty.RegisterAttached( "AutoScroll",...

Read further...

Darwin Descriptor GUID Converter

0
Comments

If you don't know what is Darwin Descritor you should read this article first. To show you what it is and where you could find it here: Also you could read about Darwin Descriptor structure here . I have wrote simple C# implementation of DarwingDescriptors GUID converter. Assembly: DarwinDecriptor.dll Namespace: DarwinDecriptor .Net Framework: 4.0 Convert Darwing Descriptor GUID to System.Guid: var converter = new GuidConverter(); var encodedDarwinDescriptorGuid = "ykG^V5!!!!4!!!!MKKSk...

Read further...

Compare performace of WPF Converters, DataTriggers and Direct Binding

1
Comments

Hello, I have made some performance tests with DataTriggers and Converters. For testing purposes I have chosen Visibility property. In first case I have binded Visibility property to IsVisible view model boolean property with standard BooleanToVisibilityConverter converter. <Border Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Blue" /> Next case was written with DataTrigger <Border Background="Red">...

Read further...

[PDF] Agile Principles, Patterns and Practices in C#

1
Comments

It was really hart to find this book in pdf format. With the award-winning book Agile Software Development: Principles, Patterns, and Practices, Robert C. Martin helped bring Agile principles to tens of thousands of Java and C++ programmers. Now .NET programmers have a definitive guide to agile methods with this completely updated volume from Robert C. Martin and Micah Martin, Agile Principles, Patterns, and Practices in C#. This book presents a series of case studies illustrating...

Read further...

WPF Binding examples

2
Comments

I have found very nice WPF XAML Data Binding Cheat Sheet, so I'll just leave it here for further use. Basic Binding {Binding} Bind to current DataContext. {Binding Name} Bind to the “Name” property of the current DataContext. {Bindind Name.Length} Bind to the Length property of the object in the Name property of the current DataContext. {Binding ElementName=SomeTextBox, Path=Text} Bind to the “Text” property of the element XAML element with name=”SomeTextBox” or x:Name=”SomeTextBox”. XML Binding...

Read further...

Advanced Tic Tac Toe final release

0
Comments

Сегодня состоялся последний плановый релиз замечательной стратегической игры Advanced Tic Tac Toe. В этом релизе добавлена подсветка последнего хода противника, страница описывающая правила игры и немного информации о нашей замечательной комманде ;) Но на этом мы не заканчиваем, у нас еще полно идей и желания для реализации будущих проектов. Advanced Tic Tac Toe был проектом для "разогрева" и он с ним справился. Теперь он переходит в стадию поддержки (громко сказано :-)). Спасибо всем за внимани...

Read further...

Host WCF service library in ASP.NET MVC 4 application

4
Comments

If you have existed WCF service library and want to host this WCF serivce in your ASP.NET MVC4 application I have prepared this short how-to. For example you have WCF service located in FooWCF assebly and  MVC4 application located in BarWeb project. Open BarWeb project and add reference to FooWCF assebly. Now, add testService.svc WCF Service file in to BarWeb project, remove ItestService.cs and testService.svc.cs files from project. Open testService.svc and replace <%@ ServiceHost Language=...

Read further...

Deploy ASP.NET MVC 4 application + WCF service to the free AppHarbor cloud

0
Comments

This article is a step by step instruction to deploy your ASP.NET MVC 4 application that hosts WCF service to the free AppHarbor cloud hosting with MS SQL server and NewRelic monitoring functionality. Configure AppHarbor You need to register an account on https://appharbor.com/, then go to "Your Applications" and create the new one. For example we will create application with name "testForBlock". Then you should add SQL server add-on to your site. Go to "add-on catalog", select "SQL Server" and...

Read further...

Оптимизации в WPF MultiDataTrigger

0
Comments

Использовал я однажды MultiDataTrigger в WPF приложении, и стало мне интересно а применяется ли для условий оптимизация на подобии оператора && в C#, когда второй операнд вычисляется только если первый равен true. Напомню, для того что бы сработал MultiDataTrigger необходиом выполнение всех условий заданных в блоке Conditions: <Style TargetType="Grid"> <Setter Property="Background" Value="MediumAquamarine" /> <Style.Triggers> <MultiDataT...

Read further...

Tic Tac Toe Advanced - web edition

3
Comments

Доброй ночи, Не зря были прожиты два выходных дня. Рады представить вам Tic Tac Toe Advanced web edition. Теперь поиграть в увлекательную игру можно с любого девайса у которого есть доступ в интернет, нормальный браузер и включенный java script. Над первой версией js игры в альтернативные крестики нолики, не покладая рук, трудились Андрей Сташук и Иван Деревянко :) Пока что реализован базовый функционал игры. Регистрация\авторизация будет доступна в следующей версии (вы можете регистрироваться и...

Read further...

Первый релиз Tic Tac Toe Advanced

0
Comments

[caption id="attachment_479" align="alignleft" width="300"] TicTacToe[/caption] После прочтения поста на Хабре об Альтернативных крестиках-ноликах захотелось реализовать приложение для сетевой игры. После недолгих обсуждений с друзьями, было решено написать WCF сервис и клиенты под самые популярные платформы. Пишем дружной командой, встречайте: Ярослав Потушинский Артем Дяченко Андрей Левин Андрей Сташук Иван Деревянко На данном этапе готов сервер и клиент под Windows. Приятной игры :) Windows к...

Read further...

HomeMoney for Windows 8 minor release

0
Comments

Состоялся минорный релиз HomeMoney - приложение для учета расходов, интегрированное с популярным онлайн сервисом домашней бухгалтерии homemoney.ua - онлайн сервисом для оптимизации расходов, планирования затрат и ведения бюджета.   В данном релизе: Исправлена ошибка с отображением имен счетов\категорий которые содержат кавычки. Добавлена английская локализация Установить приложение можно в Windows 8 Store

Read further...

Публикация приложения в Windows 8 store

0
Comments

Добрый день, После успешной публикации приложения, в разработке которого я принимал непосредственное участие, хотел поделиться приобретенным опытом, может кому-то будет полезно. Лирическое отступление: Приложение - клиент для онлайн сервиса домашней бухгалтерии homemoney.ua Первая версия приложения умеет вносить расходы за сегодня, посматривать остатки на счетах и количество потраченных денег за месяц по конкретным категориям.  В интернете уже есть множество статей на данную тематику, например н...

Read further...

Unit test Data Access Layer (Entity Framework) with in-memory database

2
Comments

Unit testing code that uses data from database is a difficult task. If you use Entity Framework you can stub your data with Effort - in-memory Entity Framework data provider. David Bywaters describes how to use Effort if your create you context based in DbContext class. But if you use model first approach (.edmx already exists) you can follow this guide: First of all install Effort from NuGet: Install-Package Effort -Pre Then add add App.Config file to your unit test project. App.Config file sho...

Read further...

[WinRT] Binding ListView to CollectionViewSource in design time

4
Comments

It would be really useful if you could see all binded data in design time in VisualStudio or Blend. To do this you should set page DataContext in xaml: <Page.DataContext> <viewModels:MainPageViewModel /> </Page.DataContext> In this case you will use the same ViewModel for design and run time. If ViewModel require different data loading logic for design and run time you should use Windows.ApplicationModel.DesignMode.DesignModeEnabled in ViewModel constructor to determine in witc...

Read further...

urlHandler or how to open url in the right browser

1
Comments

Hi All Problem:  Due to certain habits I use the Opera browser, but unfortunately Opera does not work properly with SharePoint portals, and when I receive links to our corporate portal (in Skype, Outlook, etc...), I open it in Internet Explorer. Regular ctrl+c, ctrl+v make me sad, so I realized that I should solve this problem. Task: Write a little program,  that will track clicks on the link in the applications (Skype, Outlook, etc...) and for specific links launch Internet Explorer instead of...

Read further...

urlHandler или как открыть ссылку в нужном браузере

0
Comments

  Всем привет.  Проблема:  В силу определенных привычек я пользуюсь браузером Opera, но к сожалению Opera не очень хорошо дружит с SharePoint порталами, и поэтому когда я получаю ссылки на наш корпоративный портал (через Skype, Outlook, etc...), то открываю их в Internet Explorer. Постоянный ctrl+c, ctrl+v меня удручал, вот и надумал я решить эту проблему. Задача: Написать приложение, которое будет отслеживать клик на ссылку в приложениях (Skype, Outlook, etc...) и для определенных адресов...

Read further...

How to determine if user connected to UltraVNC server

0
Comments

To check if user connected to UltraVNC server you should enable logging in ultravnc.ini: DebugMode=2 Then you just need to read log file and check if this file contains string "vnchttpconnect.cpp : HTTP client connected" for http connections and "vncclient.cpp : client connected" for VNC client connections. C# example that wait for incoming http or vnc connection during localTimeout period: bool isUserConnected = false; var startTime = DateTime.Now; localTimeout = 10000; do { using (var fileStre...

Read further...

UltraVnc password encryption and decryption (C#)

2
Comments

Hello all! I had to deploy and configure UltraVnc server to the remote computers. For this purpose it was necessary to write UltraVnc password encryption method. Passwords stores in   ultravnc.ini [ultravnc] passwd=<Encrypted password> passwd2=< Encrypted password > passwd - full control password passwd2 - read-only password Password must be no more than 8 characters long. Missing characters filled with null characters ('�').  Password is encrypted with DES + 2 symbols at the end of...

Read further...

Шифрование и расшифровка паролей UltraVnc (C#)

2
Comments

Добрый день! Возникла необходимость деплоить и настраивать UltraVnc сервер на удаленных машинах. Для этого необходимо было написать шифратор паролей для UltraVnc. Пароли хранятся в файле ultravnc.ini [ultravnc] passwd=<Зашифрованный пароль> passwd2=<Зашифрованный пароль> passwd - пароль с полным доступом passwd2 - пароль с доступом только для чтения Пароль должен быть не больше 8-ми символов. Недостающие символы заполняются null символами ('�') Шифруется пароль алгоритмом DES, с доба...

Read further...

C# аналог Perl Crypt::DES

0
Comments

Доброго времени суток! Довелось мне на днях написать метод генерации зашифрованного пароля для UlrtaVnc. Писать необходимо было на C#. Погуглив, нашел реализации алгоритма шифрования на Perl и Python. Шифруется все алгоритмом DES. На Perl это выглядит так: my $realkey = pack ('H16', "E84AD660C4721AE0"); my $cipher = Crypt::DES->new($realkey); my $password = "test"; my $cryptpass = $cipher->encrypt($password); Но вот с переводом данного кода на C# пришлось пово...

Read further...