Kill process holding a port / listening on port

Using Command Prompt (cmd.exe) execute the following:

netstat -aon |find "[port]"

ex.
netstat -aon |find "8080"

find the processi listening on the selected port an kill it

taskkill /f /pid [port]

ex.
taskkill /f /pid 13708

The following message confirms the action:
SUCCESS: The process with PID [port] has been terminated.

Case insensitive filtering of OData service in SAPUI5

Filtering JSON model is case insensitive, but for OData models this is not the case. OData service filtering is case sensitive by design. In order to achieve case insensitive searching or filtering we can use the good old way of lowering the filter string and the string we search in.

var oFilter = new Filter(
     "tolower(LastName)",
     FilterOperator.Contains,
     "'" + filterString.toLowerCase().replace("'","''") + "'"
     );

When we use a search string like "O'donnell" this translates into:

$filter=substringof(%27o%27%27donnell%27, tolower(FirstName))

As per OData specification the text we search in can be lowered using tolower():
tolower(FirstName) 


The searched text has to be lowered as well using the javascript function toLowerCase(). In addition it is surrounded by quotes to ensure it is a string when added to the odata filter. And finally to avoid problems if the search string contains quotes we have to escape them by replacing with two quotes.

Happy coding!

How to keep HTML table rows undivided by page breaks when printing HTML into PDF?

When printing large HTML tables it happens that a row gets wrongly divided between two pages. In order to solve this we can instruct the printer to keep the row on only one of the pages by adding CSS style to the table row.:

When page-break-inside property is set to avoid the  page-break should be avoided inside a HTML element, in this case table row. Of course ti can be applied to other elements like pre, blockquote, etc.
tr{
     page-break-inside:avoid;
     page-break-after:auto
}


Javascript delete property vs. nullifying it?

Let's start with a simple object:
var person = {
   firstName: 'John',
   middleName: 'D.',
   lastName: 'Doe'
}

The most common way to get rid of a property value is to nullify it or make it undefined.
Ex.
person.middleName = null;
or
person.middleName = undefined;

var person = {
   firstName: 'John',
   middleName: null,
   lastName: 'Doe'
}


Other way is to just delete it.

The delete operator does a different job by removing the whole property, returning true or false to indicate the success of the operation. In fact the deletion does not do anything related to freeing memory or releasing resources. It is just removing the property so it no longer appears in the object skeleton.
Ex.
delete  person.middleName;

This will result into
var person = {
   firstName: 'John',
   lastName: 'Doe'
}
Obviously deleting a property may help in cases when you need to enumerate the object properties and property must not appear any more. 

Deleting an array element is a different thing. The deleted element gets undefined, but the actual array length is not changing. The actual usage difference between using 'undefined' or delete operator appears to be in object properties. 

What is ECMAScript and ES6, ES7, etc.?

ECMA is an association for standardizing information and communication systems. ECMA standardizes JavaScript under the name of ECMAScript.
In a nutshell ECMAScript is a standard while JavaScript is the implementation of this standard. 

All name like ES1, ES2, ES3, ES4, ES5, ES6, ES7, etc., are abbreviations of the ECMAScript version.
ES6 was issued in 2015 and also called ES2015. As of 2015, all new versions of ES are supposed to be named by the year - ES2016 (ES7), ES2018 (ES8), etc.

ES.next is the abbreviation of all upcoming, not standardized yet versions.

The ECMA standard is supported by browsers. The following table provide extensive information about the browser support, feature by feature:
https://kangax.github.io/compat-table/es6/

In order to provide better browser support, tools like Babel can help you use latest JavaScript features into older browsers. Babel is a JavaScript compiler, more precisely said - a transpiler, that allows developers to program using ES6 feature converted to a Javascript code that current browsers can process. React (ReactJS) is a great example of Babel usage.

How to redirect permanently to a different domain with ASP.NET?

The redirect forwards the users and respectively the search engine to a new url. The redirections can be achieved in various ways. Commonly used are the HTTP status codes "301 Moved Permanently" and "302 Moved Temporarily".

In regards to the SEO (Search Engine Optimization) it is recommended to use status code 301 to inform the search engine that the previous url will not longer be in use. This url forwarding can be implemented within Global.asax as follows:


protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
      string url = HttpContext.Current.Request.Url.OriginalString.ToLower();
      if(url.Contains("old-domain.com"))
      {       
        Response.StatusCode = 301;
        Response.AddHeader("Location",
            url.Replace("old-domain.com", "new-domain.com"));       
        Response.End();
      }
}

A quick guide how to write safe SQL scripts

This is quite trivial but I am going to provide few common examples how to ensure safe multiple run of sql server scripts. Of course we have to check if the script has already been executed to avoid errors or duplication.

SQL TABLE
Check if a table exists before its creation:
IF (NOT EXISTS
(SELECT * FROM INFORMATION_SCHEMA.TABLES
         WHERE TABLE_SCHEMA = N'SchemaName'
          AND  TABLE_NAME = N'TableName'))
BEGIN
    --Run table creation script
END

SQL TABLE COLUMN
Check if a column exists before adding it:
IF NOT EXISTS(
    SELECT * FROM sys.columns WHERE Name = N'ColumnName'
    AND Object_ID = Object_ID(N'TableName'))
BEGIN
    --Run column definition script
END

SQL VIEW
Check if a view exists and remove it in order to safely create the one:
IF EXISTS(select * FROM sys.views where name = N'ViewName')
BEGIN
   DROP VIEW ViewName
END 
 
go 
CREATE VIEW ViewName ....

SQL STORED PROCEDURE
Check if a stored procedure exists and remove it

IF EXISTS (SELECT * FROM sys.objects
           WHERE object_id = OBJECT_ID(N'ProcName')
           AND type IN ( N'P', N'PC' ) )
BEGIN
   DROP PROCEDURE dbo.[ProcName]
END
go
CREATE PROCEDURE ...

SQL FUNCTION
Check if a function exists and remove it
IF EXISTS (SELECT * FROM sys.objects
           WHERE object_id = OBJECT_ID(N'[dbo].[FuncName]')
           AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
BEGIN
  DROP FUNCTION [dbo].[FuncName]
END
go
CREATE FUNCTION...

SQL TABLE INDEX
Check if an index exists and remove it

IF EXISTS (SELECT * FROM sys.indexes
           WHERE name='IndexName'
           AND object_id = OBJECT_ID('TableName'))
BEGIN
   --DROP INDEX ...
END

SQL DATA ENTRY
Check whether data has already been updated.
IF NOT EXISTS (SELECT * FROM SampleTable WHERE )
BEGIN
  INSERT INTO SampleTable...
END

IF EXISTS (SELECT * FROM SampleTable WHERE )
BEGIN
  UPDATE SampleTable SET .... WHERE
END



How to check if JavaScript function exists?

Checking if function exists differs from the regular object checking. In order to ensure a function exists you can use typeof operator for the verification.

if (typeof myFunctionName === 'function') {
     myFunctionName();
}

Rebuild SQL database indexes

In this article I will not be going through the matter of indexes.The purpose of the post is to provide a quick reference to a manually triggered re-indexing process. What is important to be understood is the fill-factor for every particular index. The fill-factor value defines the percentage of space in every index page to be filled with data and respectively defines the space left as free space for future growth.

Here is the recommended fill-factor values based on the reads-writes balance:
Tables with low number of updates
- ex. 100:1 read to write ratio: 100% fill-factor
Tables with high  number of updates 
- read to write ratio less than 1 (more writes than read) : 50%-70% fill-factor
Tables with average number of updates - 80%-90% fill-factor

DECLARE @from int
DECLARE @to int
DECLARE @fillFactor int
SET @from=1
SET @to=10000
SET @fillFactor=90
DECLARE @dateFrom datetime
DECLARE @table varchar(255)
DECLARE TableCursor CURSOR FOR
SELECT table_name from(
SELECT  ROW_NUMBER() OVER (ORDER BY table_name) AS [SortNum], table_name FROM information_schema.tables
WHERE table_type = 'base table')
AS t1 WHERE sortnum>=@from and sortnum<=@to
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY SET @dateFrom = getdate()
DBCC DBREINDEX(@table,' ',@fillFactor)
print 'Table ['+@table+'] indexed for: '+ CAST( DATEDIFF ( ms , @dateFrom , getDate() ) as nvarchar(10)) + ' ms'
END TRY
BEGIN CATCH
print 'Number of errors: '+CAST(ISNULL( ERROR_NUMBER(),'') as nvarchar)
print 'Error: '+ISNULL(ERROR_MESSAGE(),'')
END CATCH

FETCH NEXT FROM TableCursor INTO @table
END
CLOSE TableCursor
DEALLOCATE TableCursor

Change Collation of a Mirrored Databse


If you have already tried this directly you have probably seen messages like the action is not available on databases involved in mirroring or database unable to be locked and so on.

So first you have to the database from the mirror session, then do the necessary change actions and restore the mirror session. Ex,

ALTER DATABASE SET PARTNER OFF
ALTER DATABASE SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE COLLATE SQL_Latin1_General_CP1_CI_AS

On the mirrored database:
RESTORE DATABASE WITH RECOVERY


Error Messages:

  • The database could not be exclusively locked to perform the operation. 
  • The operation cannot be performed on database it is involved in a database mirroring session or an availability group 

Windows God Mode

What is that?

This is your windows command center with a lot of configurable setting to control your windows.
It is simple to be the Windows God by simply creating a new folder named

GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}

Here we go. The folder contains a lot of options making you the master of your computer.



Cheers!


Speed up Visual Studio in few easy steps

1. Delete C:\Users\[username]\AppData\Local\Microsoft\WebSiteCache content
2. Delete C:\Users\[username]\AppData\Local\Temp\Temporary ASP.NET Files content
3. Uncheck Tools -> Options -> Debugging -> Edit and Continue -> Enable Edit and Continue
4. Uncheck Tools -> Options -> Environment -> Use hardware graphics acceleration if available

Easy way to write messages in javascript console without firebug

Very simple solution w/o any prerequisites. No need to install anything like firebug or javascript library to log activities.

function writeLog(log) {
    setTimeout(function() { throw new Error(log); }, 0);
}

The javascript exceptions are automatically caught in the console, thus forcing an error writes into the console. In order to not brake any js execution use setTimeout to run the error into another thread.

The Fastest Bitcoin Exchange MCXNow is Back

The fastest and maybe the most reliable bitcoin exchange MCXNow has been reopened. Just for a few days it got all its users back and even more - it gained thousands of new users. Earn from trading and get interest for all deposited money. Additionally shares could be bought to increase your revenue by receiving dividents every 3 hours.

Happy trading!

How to move windows between monitors with Windows 7

I had this problem for some time. I use multiple monitors and my video settings are set always like that, even when I do not really need all monitors and use only the primary one. It is very often to lose a window of an application on another monitor seeing its icon on the taskbar of my primary screen. Restore, cascade, show stacked commands are just useless in this case as they only rearrange the windows of the main monitor. But there is a way to fix that by a few key shortcuts.

Win+Shift+Left - moves window to the left monitor
Win+Shift+Right - moves window to the right monitor
and maybe Up and Down to move to the upper or lower monitor - I do not have monitors above and below so I couldnt test these.

Win+Left - adheres the window to the left half of the screen. Continuous clicking causes moving the window to another monitor.
Win+Right - adheres the window on the right half of the screen. Continuous clicking causes moving the window to another monitor.
Win+Up - maximizes the window
Win+Down - Minimizes and restores if maximized