VisualStudio has problem when multiple versions of Typescript are installed

You can have several versions of Typescript installed on your machine and each project in Visual Studio can be configured to use different version by specifying that version in .csproj file.

Like this

<TypeScriptToolsVersion>1.6</TypeScriptToolsVersion>
<TypeScriptToolsVersion>1.6</TypeScriptToolsVersion>

But you might still have problems with IntelliSense for some native javascript objects. VisualStudio uses file lib.d.ts  to learn interfaces of window objects, events, etc. This lib.d.ts is updated with each version of typescript you install. When some interface become obsolete, it is removed from lib.d.ts, and VisualStudio then marks usage of such an interface as invalid and refuses to build.

Now you have problem.

You can either manually update the lib.d.ts file yourself, but that is not recommended. It is the default definition of interfaces, so obviously you do not want to mess it up.

Luckily you can specify your own version of lib.d.ts to be used in your specific project by using /// <reference path=”custom/path/to/lib.d.ts” /> in project-specific _reference.ts file.

Now everything should work again 🙂

Additional resources to study

Visual Studio 2015 compiles ALL typescript files when SINGLE file is changed

Which version of TypeScript is installed?

not-sure-if-typescript

 

In defence of literate programming


We tend to write code differently when we know that someone will be reading it, don’t we … [Josh Johnston, X-Team]

The thing is, you should always try to write (and rewrite) your code so that it is as clear as possible. Not only because of your possible code-reviewer, but also because of yoour future self. What may seem obvious to you at the time when you are writing code, might be quite unclear at the time when you read it half a year later. You will spent long time just trying to understand your old code. So, next time you are programming something, do your future self a favour: Write lots of explanatory comments.

Write comments about why something is implemented the way it is, what the context was at the time of developement, perhaps why customer wants it etc. It will not only help you in the future, but by forcing you to slow down and think, you will end up writting better code.

comments

 

As for example you can look at source code of AngularJs. It is very well written and very well commented. It is a pleasure to read such a code.

/**
 * @private
 * @param {*} obj
 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
 *                   String ...)
 */
function isArrayLike(obj) {

  // `null`, `undefined` and `window` are not array-like
  if (obj == null || isWindow(obj)) return false;

  // arrays, strings and jQuery/jqLite objects are array like
  // * jqLite is either the jQuery or jqLite constructor function
  // * we have to check the existance of jqLite first as this method is called
  //   via the forEach method when constructing the jqLite object in the first place
  if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;

  // Support: iOS 8.2 (not reproducible in simulator)
  // "length" in obj used to prevent JIT error (gh-11508)
  var length = "length" in Object(obj) && obj.length;

  // NodeList objects (with `item` method) and
  // other objects with suitable length characteristics are array-like
  return isNumber(length) &&
    (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
}

Now the same code without all those comments. It works the same, that’s for sure, but which one would you to work with?

// same code as above but without comments
function isArrayLike(obj) {
  if (obj == null || isWindow(obj)) return false;
  if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  var length = "length" in Object(obj) && obj.length;
  return isNumber(length) &&
    (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
}

Hledám kancelář

PROSÍM O SDÍLENÍ

Od 1.1.2016 budu pracovat na volné noze a potřebuji si najít nějakou pěknou kancelář. Nechci být celý den zavřený v kanceláři úplně sám, takže bych se rád k někomu připojil nebo našel někoho, kdo se připojí ke mně.

Jsem programátor, takže k práci potřebuji klid na soustředění. Potřebuji také dobré světlo, aby mě nebolely oči a neleskl se monitor. Většinou pracuji ve stoje se sluchátky na uších, takže se nebudeme moc rušit. Ideální by bylo najít někoho s podobnými požadavky na práci: ticho, světlo, příjemný prostor a stabilní rychlý internet.

Lokalita: Liberec nebo velmi blízké okolí

 

ilustrační foto :)
ilustrační foto 🙂

How to set VisualStudio 2015 to always run “as Administrator” in Windows 10

You might have the same problem like me after upgrading to Visual Studio 2015. The project could not be loaded because it depended on IIS and to run IIS it needed administration rights. Solution? Run VS as Administrator. Better still? Make sure that it always runs under administrator rights.

Just follow these simple steps

1) Local Visual Studio in Startup menu

1

 

2) Right click and select “Troubleshoot compatibility”

2

 

 

3) Select “troubleshoot program”3

4) Raise permissions

4

C# Coding conventions

These coding conventions were originally written by my colleagues Filip Kassovic and Michal Třešňák in ST-Software. I have only made slight updates and published it on my blog.

Do not use “var” keyword when not necessary

var response = SomeClass.SomeMethod(input);

Reason

  • we don’t see the type of “response”
  • “Find Usages” or “Find all references” doesn’t find usage of type when using “var”

Exceptions
obviously, you have to use it for anonymous types

var anonymous = new { A = 1, B = 2 };

Do not use complex object initializer

PaymentTransaction transaction = new PaymentTransaction
			{
				Token = statusResponse.RefNo,
				Error = GetError(statusResponse), //avoid method call in initializer
				State = GetState(statusResponse.ResponseCode),
				ProviderResponse = statusResponse.Response,
				Sign = statusResponse.Sign,
				Sign2 = statusResponse.Sign2
			};

Reason

  • it is not possible to debug it.
  • We are not able to determine line with exception. For example, if there was an exception in GetState() method, we wouldn’t know if the exception was in GetError() or in GetState() method etc.
  • And this is problem in logs because in case of an exception, we would get only line number of “PaymentTransaction transaction = new PaymentTransaction” and not “GetState()”.

Exception
Allowed in simple scenarios like this

SomeDto dto = new SomeDto
{
	Id = entity.Id,
	Name = entity.Name,
};

Code Formatting – keep tabs

tabs

Setup formatting like this: Indenting – Smart, Tab – Keep tabs

Reason

  • files are much smaller
  • easier to navigate using keyboard
  • compatible with CoffeeScript

Do not return new objects / method results / query results directly

public static UserRoleDetailDto ToUserRoleDetailDto(UserRole entity)
{
	return new UserRoleDetailDto
	{
		Id = entity.Id,
		Name = entity.Name,
	};
}

//another case
public static List Aaa(UserRoleDetailDto dto)
{
  //not possible to see return value in debugger
  return dto.ExcelReportIds
 .Where(x => x.ToString()
 .StartsWith("1"))
 .ToList();
}

How to write it instead

public static List<Guid> Aaa(UserRoleDetailDto dto)
{
 List<Guid> ret = dto.ExcelReportIds
 .Where(x => x.ToString()
 .StartsWith("1"))
 .ToList();

 //You can set breakpoint here and check the return value
 return ret;
}

Reason
If you return the result right away, then it is not possible to debug it and you can’t see the returning value

Use explicit initialization for Enum

public enum Status {
 Accepted: 0,
 Denied: 1,
 Approved: 2,
 Rejected: 3,
 Submitted: 4,
 SomethingElse: 5
}

Reason
It is hard to match enum values stored in database as int. So always declare it along with numberic value of that enum.

Be careful about FirstOrDefault() method

Reason
When we expect that there should be just 1 matching item, then Single() or SingleOrDefault() should be used. Otherwise it might happen that your DB will accidentally contain duplicated representation of some important items (for example Orders or Bills). FirstOrDefault() has caused us several headaches, which could have been easily avoided if we’ve used SingleOrDefault() in the first place.

 

Have fun 🙂

java

Download files via POST request in AngularJs

There are times when you need to download file but the download is initiated via POST request, because the request contains too much parameters to fit into limited GET request. In my case I needed to generate ZIP file.

First you need to define custom method on your $resource which will handle the download method, like in the example below. Have a look at the transformResponse method. It creates a Blob from the server response (binary representation of the Zip file) and tries to extracts the file name from response headers.

Then you need to define method on controller. User clicks button “Download ZIP”, your controller calls MyResource.download(). That returns a (transformed) promise containing the Blob. Once you have the Blob, you call saveAs to prompt “save file dialog” in browser.

SaveAs method is part of HTML5 spec and a polyfill is available here.

//Written in Typescript

Module.factory("MyResource", ["$resource", ($resource: ng.resource.IResourceService)
      => $resource(FinaDb.apiUrlBase + "FinanceManager".toLowerCase() + "/:Id", { Id: "@Id" },
          {
              //Define custom action on resource
              //Inspired by http://notjoshmiller.com/server-side-pdf-generation-and-angular-resource/
              download: {
                  method: 'POST',
                  url: 'url-of-server-side-method',
                  headers: {
                      accept: 'application/zip' //or whatever you need
                  },
                  responseType: 'arraybuffer',
                  cache: false,
                  transformResponse: (data, headers) => {
                      var zip = null;
                      if (data) {
                          zip = new Blob([data], {
                              type: 'application/zip' //or whatever you need, should match the 'accept headers' above
                          });
                      }

                      //server should sent content-disposition header
                      var fileName: string = getFileNameFromHeader(headers('content-disposition'));
                      var result = {
                          blob: zip,
                          fileName: fileName
                      };

                      return {
                          response: result
                      };
                  }
              }

          })
  ]);
  
  function getFileNameFromHeader(header: string): string {
      if (!header) return null;

      var result: string = header.split(";")[1].trim().split("=")[1];

      return result.replace(/"/g, '');
  }

Now define method on ng controller like that:

//Define method download() in your ng controller

$scope.download = () => {
      //Indicates that download is in progress
      $scope.isDownloading = true;

      //define parameters
      var params = {
          Idies: [] //List of idies of entities of whatever
      };

      return MyResource.download(params).$promise.then((data: any) => {
              //using saveAs.js (part of upcoming HTML5 API, but so far a polyfill)
              var blob = data.response.blob;

              var fileName: string = data.response.fileName || 'document.zip';
              
              //SaveAs is available at saveAs.js from http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js
              (<any>$window).saveAs(blob, fileName);
          })
          .finally(() => {
             $scope.isDownloading = false;
      });
  }

How to write for-loop like code in SQL

I needed to dynamically generate missing items in database. I had a list of Sports and Categories, and I needed to generate items with all combinations of these two entities. But some of them already existed in database, so those should be skipped. My idea was to perform kind of for-each loop iterating over the Sports collection, but written in SQL. In each iteration I would check if given combination already exist in DB and if not, I create it.

SQL Cursor comes to help

If you run into issues with another coding technique and need to get something done quickly, using a cursor may be a viable alternative.  It may take longer to process the data, but the coding time might be much less.  If you have a one time process or nightly processing, this could do the trick

Here is the code (simplified for brevity)

declare @emailBody nvarchar(max) = 'Text of email body'
declare @emailSubject nvarchar(max) = 'text of subject'
declare @sportId uniqueIdentifier 

-- get all Sport Idies
declare sportCursor cursor
	local static read_only forward_only
for
select Id 
from Sports
where ObjectState = 1

-- iterate over Sport Idies
open sportCursor
fetch next from sportCursor into @sportId
while @@fetch_status = 0
begin
  -- Check if entity with given parameters exist
	if not exists (
		select * from EmailTemplates et 
		where et.ObjectState = 1
		and et.SportId = @sportId
		and et.Type = @NfSummaryType -- some other parameter, declaration omitted in this example
	)
	Begin
		print 'creating new email template'
		Insert into EmailTemplates(Id, CreatedDate, Body, [Subject], SportId)
		values (NEWID(), GETDATE(), @emailBody, @emailSubject, @sportId)
	End

	fetch next from sportCursor into @sportId
end

CLOSE sportCursor
DEALLOCATE sportCursor

If you want to know more about SQL Cursor then read here.

C# – How to find overlap of datetime intervals

I needed to count the overlap of the datetime intervals. After some coding I’ve refactored the code to static class and uploaded to Github, so that others can use it too. It might save you some time 🙂

There are currently two methods. One to get the interval overlap and the other to count the interval duration.

Go ahead and check out our company GitHub. The code is pretty straight forward, so no need to explain too much.