Others

Бг Съпорт

Published by:

Съпорта си е трудно перо във всеки бизнес ама колко да е труден толкова. Прилагам комуникацията ми с host.bg за проблем, който имах с един сайт който хоствам там. Не го поствам тук, за да им се подигравам на очевидно лошия сървис ами по-скоро за забавление:

Запитване от: xxxxxx на 9 Jun 2015 в 11:05
Здравейте,

губят ми се файлове и информация (снимки, новини) които съм качвал през админски панел в сайта и за съжаление дори с бекъпи не мога да ги възстановя. От друга страна по папките виждам разни xml файлове които са скриптове. Затова искам да погледна логове на кой какво е качвал и трил в сайта, но не намирам такива. Файловете пак казвам са качвани през админски панел, а не фтп клиент. Лога за хостинг активност също ми е празен.

Поздрави,
Ивайло Пашов
========================================
Отговор от: xxxxxxxx на 9 Jun 2015 в 11:35
Здравейте,

Моля проверете сега.

С уважение,
xxxxxxxx
Техническа поддръжка
Host.bg
=========================================
Запитване от: на 9 Jun 2015 в 11:55
Здравейте,

не намирам нищо – къде трябва да видя.

Искам да видя логове кой какво е качвал и трил в която и да е папка за последния месец? Има ли такива?
=========================================
Отговор от: xxxxxxxx на 9 Jun 2015 в 13:26
Здравейте,

Всичките налични логове може да видите през контролния панел на адрес admin.host.bg

Пишете ни, ако имате нужда от още нещо.

С уважение,
xxxxxxxx
Техническа поддръжка
Host.bg
==========================================
Запитване от: на 9 Jun 2015 в 14:11
Вижте:

1. Питам за конкретни логове – кой е трил или добавял файлове в моя сайт. На кое казвате всички налични не знам. Трябват ми тези за които питах.
2. admin.host.bg е сайт с доста фунционалности – да ми кажете че логовете са някъде там е като да ми кажете всичката налична информация е в гугъл.

Моля бъдете конкретен по въпросите които питам или ще трябва да ескалирам тикета.

Поздрави
===========================================
Отговор от: xxxxxxxx на 9 Jun 2015 в 14:31
Здравейте,

Може да видите вашия FTP лог през Контролен Панел > Лог на FTP достъпа. Прегледахме логовете, но забелязваме че няма налични логове за вашия акаунт.

С уважение,
xxxxxxxx
Техническа поддръжка
Host.bg
============================================
Запитване от: на 9 Jun 2015 в 22:05
Здравейте,

ако видите първото ми съобщение от 9 Jun 2015 в 11:05 ще видите че там пише

“Затова искам да погледна логове на кой какво е качвал и трил в сайта, но не намирам такива. Файловете пак казвам са качвани през админски панел а не фтп клиент”

при което ми отговаряте с
“Всичките налични логове може да видите през контролния панел на адрес admin.host.bg” и след това
“Може да видите вашия FTP лог през Контролен Панел > Лог на FTP достъпа”

Аз трудно мога да си представя по- неизчерпателен и неточен отговор – искам да ми дадете контакт на Вашия супервайзор.

.NET

app_offline.htm

Published by:

app_offline.htm is an old feature of ASP.NET that i recently found and find quite useful. If you put an app_offline.htm file in the root of your .net hosted site (yeah, simple as that), ASP.NET will shut down your site unload it form the app domain and stop serving any incoming requests. Instead it will start serving the content of the app_offline.htm file. That comes quite handy of your site is “Under Construction” or you make any major changes.

markup

app_offline

site

.NET Coding

smg-alumni.com is live

Published by:

Just released one of my projects live – the portal for Sofia High School of Mathematics’ alumni . I developped that as an open source projects and it can be found on github. The project is built for Sofia High School of Mathematics but can be used for any other school or university with minimal effort for customization.

Technological stack is MSSQL on the server side with Entity Framework as ORM, ASP.NET Web Api on the back-end and AngularJS on the front-end. The portal is feature rich and features user, amdin and super admin functionality. Superadmin may edit system settings and assign roles through the ui. Admin creates news, fundraising campaigns, resets user passwords and verifies registered users (this may be used or not). On the user part, there is a section for news, fundraising campaigns, search (by year and class division so far) , forum and account management. Most pages are available for not logged in users, except the search, the account management and in the cases when you want to create content in the forum.

Account management features account edit, forgot password and change password.

The solution is a perfect fit for shared hosting – recurring services are implemented as jobs instead of windows services. This particular site runs on shared ASP.NET hosting from ICN for about 50E per year, which is quite a deal in my opinion. Special thanks to SMG’s Director – Mr. Stoyanov for covering the first year’s expenses.

I believe that every school/uni needs alumni network site where alumni can keep in touch, help themselves, help current students and also help the school or uni.

Feel free to fork the repository and use the project freely wherever you want. If you need any assistance don’t hesitate to PM me.

.NET Coding

A really good pdf library for .net

Published by:

If you are into Web apps development you will probably face at least once the problem to export web content to pdf. And if it is the first time you face that problem, things get scary. You usually face a few options:

– commercial and expensive library
– the almighty wkhtmltopdf tool (built on top of WebKit rendering engine) but you have to run the executable from your .net app which makes deployment more complex
– a .net wrapper library of the wkhtmltopdf tool

The third one is definitely the winning option as the tool is really powerful and free. Which wrapper though? Some of them don’t work in some cases and docs are poor. After an extensive research i found this one called NReco PDF Generator for .NET to be the best and render everything you might need (html of course, but also svg, custom fonts etc.) in one liner. The library is free but for 30$ you can get some support and code samples and for 100$ you can get all future updates plus component’s source if you want. As i said it works perfect outside of the box and chances are you wont need samples and support unless you render something very special. It the most basic scenario, you need only

var converter = new HtmlToPdfConverter();
var result = converter.GeneratePdf(html);

where html is… right, your html that you want to export. If you need any customization you may find useful to use:

converter.PageFooterHtml="your html as string goes here"

or

converter.PageHeaderHtml="your html as string goes here"

If you want some more granular control you may use :

converter.CustomWkHtmlPageArgs

property which takes native to the wkhtmltopdf tool arguments as a string so if you need page numbers in the footer you may type in:

converter.CustomWkHtmlPageArgs ="--footer-right [page]/[topage] --footer-font-size 8";

I saved the best for last – it is available through NuGet and has no dependencies so installation is one-click away and makes a deployment as consistent as it can get. So to wrap up , good job guys for that library. It is very rare to find something free to work so well outside of the box.

.NET

Manage your passwords

Published by:

In modern world one of the huge challenges – at least for me is managing my passwords for the various sites that i use.

The challenge is further enhanced by:

– your passwords need to be super strong so that they withstand hackers. Passwords are usually stored as hashes and not strings on the server so hackers use brute force guessing mechanisms to get you password as a string if those passwords get stolen. So using password as RgGZ5DOynJ5*dd*TsrAXEz will make them reluctant to crack it as for the same time they will crack 1000 passwords as password123.
– you need to change your passwords often enough so that be secured (i use 2-3 months time-intervals)
– you need to use unique password for every site you use. One of the biggest mistakes in terms of security is to make up a super strong password, use it all over the place and not change it for years.

So, either you have to have a very smart way to make up and remember passwords or you need to use a tool. I have decided for myself to use the second. But i couldn’t come up with a free tool that i could trust enough so i decided to make up one for myself.

Here is how it looks:

passwordtool1

passwordtool

This is a simple winforms app and uses the built in System.Security.Cryptography methods to leverage the asymmetric cryptography method of encryption.

With this simple app you can:

– Generate public/private key pairs
– Generate random password for you
– Encrypt passwords as string with the public key
– Decrypt encrypted passwords in string format with the private key

So you may generate strong password and keep their encrypted representation in a simple .txt file if you want to and decrypt them when needed with the private key:

encrypted password

You don’t really need to worry about that txt as everything in it is encrypted and if passwords are strong enough, it will require huge amount of effort to brute force crack them. That does not mean that you have to be negligible though. The single thing that you have to worry about is the PRIVATE KEY – that is the single most vulnerable point here so keep that the best way you can. If you thing that the private key has been compromised, just create another pair public-private key and run your passwords through those.

You can find the source of the app here -> https://bitbucket.org/ivopashov/cryptoapp and build it for yourself. If you are out of the .NET world drop me a pm and i will send you the exe.

Disclaimer – i haven’t refactored the code so please don’t be that critical on the source quality 🙂

Coding javaScript

Input validation in Angular

Published by:

Validation is one of the main issues that developers have to deal with when handling user input in forms. The premise is that all user data coming in may be corrupt and some users may have bad intentions so validate inputs on the client and on the server side.
Maybe for this reason, angular (1.3+) provides a pretty powerful validation api through the all famous ngModel directive and its controller. By adding our custom directive to the input and requiring ngModel we can have a grip over the ngModel Controller which provides the validation api. So we start with something like:

disclaimer- should be only start-date in the markup. My syntax highlighter adds the =”” so ignore those.

So far so good- we have a form with an input where we will require the user to type in a date in a specific format within a specified date range and we will validate if that date is available for reservation on the server. So we bind te input to reservationStartDate and put in our custom directive – startDate.

Next thing, lets create the directive itself:

.directive('startDate',function(constVars,dateParserService,$http){ 
	return {
        restrict: 'A',
        require: ['ngModel'],
        link: link
    };

    function link(scope, element, attr, ctrls) {
        var ngModelController = ctrls[0];
    }

})

So far we don’t do anything but the important takeaway here is the require: [‘ngModel’] line when declaring our directive which says – “Hey let me use the ngModel Controller here”. Assume that in constVars we hold a date regex and dateParserService is custom logic that we created for parsing dates from strings. All the validation will happen in the link function of our directive and the required ngModel Controller is passed in the link function through the fourth argument (ctrls). In this case we will use the following methods for validation:

$parsers – that is a collection of functions where we sanitize input from user before handing it to the $validators. Every parser function passes the sanitized value to the next one. If we ever return undefined, the pipeline doesn’t reach the $validators.

$validators – name is pretty exemplary here – these are collection of functions where we apply validation logic.

$asyncValidators – same as above but we typically use these for server, api or whatever long running operations validation. They start not one after the other but simultaneously and deal with promises rather than values. If all resolve the value than validation passes, if one rejects it – validation fails. Let’s get to some specific example.

First of all, we want to check if the manually input value is in the format that we want the user to use and we will use regex – so we will put that in the $parsers:

function link(scope, element, attr, ctrls) {
        ngModelController.$parsers.unshift(function (viewValue) {
                var date;
                if (angular.isString(viewValue)) {
                    if (!constVars.dateFormatRegex.test(viewValue)) return undefined;
                    else {
                        date = dateParserService.parse(viewValue, "dd-MM-yyyy");
                        if (isNaN(date)) {
                            return undefined;
                        }else{
		            return date;
			}
                    }
                }
        });
}

I we can parse it we pass the parsed Date object down the pipeline, if not – return undefined, which stops the value propagation down the pipeline and sets myForm.reservationStartDate.$error.parse = true.
If we parsed the user input to date we want to validate if the user entered a date in a correct date interval (we don’t want dates before today for a reservation). We will put that into $validators:

		ngModelController.$validators.afterToday=function (modelValue,viewValue) {
			var today=new Date();
			if(today < modelValue){
				return true;
			}
			return false;	
        };

So after the date has been parsed it will be passed to the afterToday for business rule validation. Let's go a little further and add an asyncValidator. We will validate the date for availabiliy on the server:

ngModelController.$asyncValidators.isDateAvailable=function (modelValue) {
    return $http.post('api/date/available',modelValue).then(function(success){                       
        //yeah, went through                      
    },function(error){
        // no availability
    })
};

As i said, async validators (you may have many of those) will start running simultaneously and input will be validated only if all resolve the promise. You may give the user indication that something is loading by:

Checking Value on the server....

So that is the main validation pipeline of the ngModelController - $parsers-> $validators & $asyncValidators. There is one more hook that you can use - $viewChangeListeners which is again array of functions. It does not take args or return anything - these functions are used usually for additional $watches on the model instead of some validation logic. What is provided more in the api are methods to change the input state as $setPristine(),$setDirty(), $setTouched(), $setUntouched(). Those are self-explanatory so i wont elaborate on them.

By default the view value gets passed down the validation pipeline on every change (ie keystroke) which might be not necessary. You may want to validate the input on blur event only. So that is very easily configurable - you only need to decorate your input markup with ng-model-option:{updateOn:'blur'}

You can clone the source for this example and some more on https://github.com/ivopashov/angular-presentation It is in app->ngModelExample

.NET Coding

Dynamic objects in C#

Published by:

I know that it is not what strongly typed language is supposed to support but sometimes we need to add properties on the fly as in JavaScript. Here are two alternative ways to do that:

One way is to use the ExpandoObject that is being shipped in System.Dynamic. We can add properties (of any type) on the fly and to consume them afterwards. Consider the following example:

        dynamic dynamicObject = new ExpandoObject();
        dynamicObject.myCat = cat;
        dynamicObject.myCar = car;
        dynamicObject.justAString = "I am just a string";
        dynamicObject.justAnInteger = 42;

If we try to consume a property that is not present we get an exception. No need to say that you have to say good bye to intellisense.

The second way is to implement a class with an indexer and an underlying dictionary as the data store. You can add properties on the fly with a slightly different syntaxis. Consider the following example:

public class ViewBag
{
    public ViewBag()
    {
        dict = new Dictionary();
    }

    private Dictionary dict;

    public object this[string index]
	{
		get 
        {
            object val=null;
            dict.TryGetValue(index,out val);
            return val;
        }
		set 
        {
            if (dict.ContainsKey(index))
            {
                throw new Exception();
            }
            else
            {
                dict.Add(index,value);
            }
        }
}

and that is how we add properties

        var viewBag = new ViewBag();
        viewBag["mycar"] = car;
        viewBag["myCat"] = cat;
        viewBag["justAString"] = "I am just a string";
        viewBag["justAnInteger"] = 42;

I have named it viewBag purposefully because the actual MVC ViewBag is built this way.

I must admit that it is mainly border scenarios where you might need those but you never know.

Others

Is everything made yet?

Published by:

Sometimes i hear people saying that there is not much room for innovation as pretty much everything is being invented already in one form or another. Bad excuse.

I’ve been a bitcoin believer for quite a while now. Bitcoin in my opinion is THE innovation of the first decade of the 21-st century. However, is the bitcoin idea radically new? Not at all. If you take a look at Satoshi Nakamoto’s (a pseudonym for the bitcoin founder(s)) paper that introduced the bitcoin protocol in 2008 to the world, you will see that the references are at least 10 years old. Further, if you visit the first reference (very understandable and short read), you will see that bitcoin was conceived at least in year 1998. The ideas that bitcoin consists of as cryptography, distributed networks and so on, date further back.

The reason i am saying this is that you don’t have to invent the wheel to be an inventor. You can:
– apply an old idea in practice
– combine old ideas in an ingenious way
– make an old thing better
– market a good idea in an innovative way
– see an innovative application of an idea or a thing
– make more with less

and so on…

I am sure the list can go forever. What is hard is to believe that everyone can be an inventor and adopt that state of mind.

.NET Coding

Construct Dynamic Filters with C#

Published by:

Filtering data with C# is pretty straight-forward when using LINQ – you get results with one-liners as

var result=cars.Where(a=>a.carMake=="Fiat" && a.speed>100);

However, we know the filtering properties (carMake and speed) and the filtering conditions (equals with carMake and greater than with speed) in advance. The more interesting case, however, is when we don’t know the filtering properties, their number and the filtering criteria in advance but have to construct them in real time. Consider the case when you have data objects with many properties and allow the user on the front end to filter it according to his/her needs. In this case Dynamic Expression Construction comes to rescue.
LINQ extension methods work with predicates (or anonymous functions). Fortunately, C# provides very powerful api to build Expression trees, which can be compiled to predicates in runtime and passed to the LINQ extension methods afterwards.
Let’s see an example. Suppose that we have a list of cars and we want to filter them dynamically for whatever purpose – here is our Car object

 
public class Car
    {
        public string Model { get; set; }
        public string Make { get; set; }
        public string CountryOfOrigin { get; set; }
        public string CountryOfProduction { get; set; }

        public int MaxMilesPerHour { get; set; }
        public int NumberOfSeats { get; set; }
        public int MilesPerGallon { get; set; }
        public double WeightInKg { get; set; }

        public decimal BasePrice { get; set; }
        public decimal FullPrice { get; set; }
    }

With 10 properties, we can filter a collection of cars in many possible ways.
Next we need a class that would represent a filter – so we need a property name for comparison, value to be compared to and operation (equal, less than etc). Let’s call it ExpressionFilter

public class ExpressionFilter
    {
        public string PropertyName { get; set; }
        public object Value { get; set; }
        public Comparison Comparison{ get; set; }
    }

Comparison is nothing more than a enum with possible operations

public enum Comparison
    {
        Equal,
        LessThan,
        LessThanOrEqual,
        GreaterThan,
        GreaterThanOrEqual,
        NotEqual,
        Contains, //for strings
        StartsWith, //for strings
        EndsWith //for strings
    }

Next comes the real thing – we need a class which can take a list of ExpressionFilters, do its thing and return an Expression tree composed of these filters, which we can use as a parameter in any LINQ extension method after compiling it. Let’s have a class that constructs And expression trees. We will call it ConstructAndExpressionTree

 
public static Expression<Func<T, bool>> ConstructAndExpressionTree<T&gt(List<ExpressionFilter> filters)
        {
            if (filters.Count == 0)
                return null;

            ParameterExpression param = Expression.Parameter(typeof(T), "t");
            Expression exp = null;

            if (filters.Count == 1)
            {
                exp = ExpressionRetriever.GetExpression<T>(param, filters[0]);
            }
            else
            {
                exp = ExpressionRetriever.GetExpression<T>(param, filters[0]);
                for (int i = 1; i < filters.Count; i++)
                {
                    exp = Expression.And(exp, ExpressionRetriever.GetExpression<T>(param, filters[i]));
                }
            }

            return Expression.Lambda<Func<T, bool>>(exp, param);
        }

The class is generic so it can be used with any type. The code is pretty straight-forward -> we start with the ParameterExpression which is the t=> part of the predicate. Then we iterate through the filters and start building the actual expression called exp here. You probably notice that we use a helper method ExpressionRetriever.GetExpression to construct the separate expressions (like a.speed>100), which we stick with Or binary operator aferwards. Here is the code of ExpressionRetriever.GetExpression:

public static class ExpressionRetriever
    {
        private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");
        private static MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
        private static MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });

        public static Expression GetExpression<T>(ParameterExpression param, ExpressionFilter filter)
        {
            MemberExpression member = Expression.Property(param, filter.PropertyName);
            ConstantExpression constant = Expression.Constant(filter.Value);
            switch (filter.Comparison)
            {
                case Comparison.Equal:
                    return Expression.Equal(member, constant);
                case Comparison.GreaterThan:
                    return Expression.GreaterThan(member, constant);
                case Comparison.GreaterThanOrEqual:
                    return Expression.GreaterThanOrEqual(member, constant);
                case Comparison.LessThan:
                    return Expression.LessThan(member, constant);
                case Comparison.LessThanOrEqual:
                    return Expression.LessThanOrEqual(member, constant);
                case Comparison.NotEqual:
                    return Expression.NotEqual(member, constant);
                case Comparison.Contains:
                    return Expression.Call(member, containsMethod, constant);
                case Comparison.StartsWith:
                    return Expression.Call(member, startsWithMethod, constant);
                case Comparison.EndsWith:
                    return Expression.Call(member, endsWithMethod, constant);
                default:
                    return null;
            }
        }
    }

Expression class provides methods for the standard operations as equal, not equal, less than etc. but notice also the last three cases where we use Expression.Call to call the string methods Contains, StartsWith and EndsWith. Here lies a big potential for extension as you can use whatever methods you like defined on any type. You only should get their MethodInfo through reflection.
So sticking it all together (i skip the part where i populate the cars collection):

      static void Main(string[] args)
        {
            var filters = new List<ExpressionFilter> 
            { 
                new ExpressionFilter
                {
                    PropertyName="CountryOfOrigin",
                    Comparison=Comparison.StartsWith,
                    Value="Fr"
                },
                new ExpressionFilter
                {
                    PropertyName="MaxMilesPerHour",
                    Comparison=Comparison.GreaterThanOrEqual,
                    Value=190
                }
            };

            var expressionTree= ExpressionBuilderHelper.ExpressionBuilder.ConstructAndExpressionTree<Car>(filters);
            var anonymousFunc = expressionTree.Compile();
            var result = cars.Where(anonymousFunc);
        }

You can see that the result is a car that has MaxMilesPerHour>190 and CountryOfOrigin that starts with ‘Fr’
result