TypeScript: Remove duplicate item in array

Posted by Unknown On Friday, July 21, 2017 8 comments

 this.carriers = this.carriers.filter((el, i, a) => i === a.indexOf(el))

Angular2: Form

Posted by Unknown On Wednesday, July 19, 2017 0 comments

             <form (submit)="showReport()">
                 <div class="form-group">
                     <label>Filter </label>
                     <input type="text" name="filter" class="form-control" [(ngModel)]="filter.keyword" />
                 </div>
                 <div class="text-right">
                     <button type="submit" name="search" class="btn btn-primary">Search </button>
                 </div>
             </form>

Angular2: Currency Format

Posted by Unknown On Friday, July 14, 2017 0 comments

Format: {{cost | currency:'USD':true:'1.2-2'}}
Output: $348.64

  • Format: {{currency:currencyCode:symbolDisplay:digitInfo}}
  • CurrencyCode Info: https://en.wikipedia.org/wiki/ISO_4217
  • SymbolDisplay: is a boolean indicating whether to use the currency symbol or code.
        true: use symbol (e.g. $).
        false(default): use code (e.g. USD).
  • DigitInfo Format: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
    •    1 : minIntegerDigits
    •    2 : minFractionDigits
    •    2 : maxFractionDigits

Angular2: Number Format

Posted by Unknown On 0 comments

Format: {{value | number : '1.2-2'}}
output: 250.12

Format: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
1 : minIntegerDigits
2 : minFractionDigits
2 : maxFractionDigits

C#: Generic - Convert any string to any enum type

Posted by Unknown On Tuesday, July 11, 2017 0 comments

Use an extension method to convert from string to enum.


 public static T ToEnum(this string enumString)
 {
    return (T) Enum.Parse(typeof (T), enumString);
 }

//Usage:

 Color colorEnum = "Red".ToEnum<Color>();

TypeScript: Convert string to number

Posted by Unknown On 0 comments

  this.customerid = Number(text);

JavaScript: Base64 encoding and decoding

Posted by Unknown On 0 comments
atob(): Decodes a string of data which has been encoded using base-64 encoding.
btoa(): Creates a base-64 encoded ASCII string from a "string" of binary data.

The "Unicode Problem": In most browsers, calling btoa() on a Unicode string will cause a Character Out Of Range exception. This paragraph shows some solutions.

Solution to unicode

C#: Encoding and Decoding base64

Posted by Unknown On 0 comments

Encoding


  byte[] textAsBytes = System.Text.Encoding.UTF8.GetBytes(text);
  var encodedText = Convert.ToBase64String(plainTextBytes);

Decoding


 var textAsBytes = Convert.FromBase64String(text);
 var decodedText = System.Text.Encoding.UTF8.GetString(textAsBytes);

Visual Studio 2017 keyboard shortcuts

Posted by Unknown On Monday, July 10, 2017 0 comments
This is cool thing you should know.

Visit here for All shortcuts

TypeScript: Clone an object

Posted by Unknown On 0 comments

let newObject = Object.assign({}, currentObject);

Angular 2: Format Date Time MM-dd-yyyy

Posted by Unknown On 0 comments




 Output: 07-09-2017 05:00 PM

TypeScript: Filter out array from another array (not in statement)

Posted by Unknown On Friday, July 7, 2017 0 comments

var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 4];

var arr = arr1.filter(x => { return arr2.indexOf(x) === -1; });


SQL: Detecting fragmentation of Indexes on a database

Posted by Unknown On 0 comments
  • Fragmentation is between 5-30% – it is suggested to perform index reorganization
  • Fragmentation is higher than 30% – it is suggested to perform index rebuild

SELECT dbschemas.[name] as 'Schema', 
dbtables.[name] as 'Table', 
dbindexes.[name] as 'Index',
indexstats.alloc_unit_type_desc,
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID()
ORDER BY indexstats.avg_fragmentation_in_percent desc


Read more on https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-physical-stats-transact-sql

TypeScript: Select fields from Array of Object

Posted by Unknown On Thursday, July 6, 2017 0 comments

var ids = this.products.map((p) => p.id);
var products= this.selectedProducts.map((p) => { p.id, p.name });

TypeScript: search item in array by field

Posted by Unknown On Thursday, June 29, 2017 0 comments
  
  public search(name: string): void {
    if (name.trim().length > 0) {
      this.employees = this.employeeSource.filter(x => x.name.toLowerCase().indexOf(name.trim().toLowerCase()) >= 0);
    }
  }  
  
  

TypeScript: ForEach Sum Field in Items of an Array

Posted by Unknown On 3 comments

  public getTotalWeight(): number {
    var total = 0;
    if (this.items != null && this.items.length > 0) {      
      this.items.forEach(x => total += x.weight);
    }
    return total;
  }  

Angular JS: Page Event Lifecycle

Posted by Unknown On 0 comments

After creating a component/directive by calling its constructor, Angular calls the lifecycle hook methods in the following sequence at specific moments:

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()

More detail

SQL: Check which query cause slowness in your server

Posted by Unknown On 0 comments

Run this script in your management studio as administrator.


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT SPID = er.session_id ,
       DBName = DB_Name(er.database_id) ,
    BlkBy = er.blocking_session_id ,
       ElapsedMS = er.total_elapsed_time ,
       CPU = er.cpu_time ,
       IOReads = er.logical_reads + er.reads ,
       IOWrites = er.writes ,
       Executions = ec.execution_count ,
       CommandType = er.command ,
       ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid) ,
       SQLStatement = SUBSTRING ( qt.text, er.statement_start_offset/2, (CASE WHEN er.statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2 ELSE er.statement_end_offset END - er.statement_start_offset)/2 ) ,
       Status = ses.status ,
       [Login] = ses.login_name ,
       HOST = ses.host_name ,
       
       LastWaitType = er.last_wait_type ,
       StartTime = er.start_time ,
       Protocol = con.net_transport ,
       transaction_isolation = CASE ses.transaction_isolation_level
            WHEN 0 THEN 'Unspecified'
            WHEN 1 THEN 'Read Uncommitted'
            WHEN 2 THEN 'Read Committed'
            WHEN 3 THEN 'Repeatable'
            WHEN 4 THEN 'Serializable'
            WHEN 5 THEN 'Snapshot'
        END ,
        ConnectionWrites = con.num_writes ,
        ConnectionReads = con.num_reads ,
        ClientAddress = con.client_net_address ,
        Authentication = con.auth_scheme
FROM sys.dm_exec_requests er
LEFT JOIN sys.dm_exec_sessions ses ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con ON con.session_id = ses.session_id CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt OUTER APPLY
( SELECT execution_count = MAX(cp.usecounts)
 FROM sys.dm_exec_cached_plans cp
 WHERE cp.plan_handle = er.plan_handle) ec
ORDER BY er.blocking_session_id DESC,
         er.logical_reads + er.reads DESC,
         er.session_id


SQL Server: Loop through all databases in an instance

Posted by Unknown On Thursday, June 15, 2017 1 comments

You need to have sufficient permission to execute this command.


EXECUTE sp_MSForEachDB  'USE ?; select DB_NAME() AS DBName,xmluserid from carriertable where carriername=''LKVL'' and userid IS NOT NULL'

C#: How to get the raw xml returned from a webservice request

Posted by Unknown On 0 comments

How to get the raw xml from a webservice request or response


XmlSerializer xmlSerializer = new XmlSerializer(oResponse.GetType());

using (StringWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, oResponse);
    var xmlText = textWriter.ToString();
}

SQL Server: Reseed a SQL Server identity column to 0

Posted by Unknown On 0 comments

DBCC CHECKIDENT ('table name', RESEED, 0)

C#: o(1) fastest way to sum from 1 to 100000

Posted by Unknown On Friday, June 9, 2017 0 comments

Fast test way to sum from 1 to 100000 by using arithmetic series.


public static int Sum(int value)
{
 var n = value;
 var a1 = 1;
 var an = a1 + (n - 1);
 var sn = n * (a1 + an) / 2;
 return sn;
}

C#: Get Business Working Day

Posted by Unknown On 0 comments

First Method


        public static int GetWorkingDays(DateTime from, DateTime to)
        {
            var workingDay = 1 + (to - from).Days;
            return Enumerable
                .Range(0, workingDay)
                .Select(x => from.AddDays(x))
                .Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
        }

Second Method


        public static double GetWorkingDays(DateTime startD, DateTime endD)
        {
            double workingDay = 1 + ((endD - startD).TotalDays * 5 - (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

            if (endD.DayOfWeek == DayOfWeek.Saturday) workingDay--;
            if (startD.DayOfWeek == DayOfWeek.Sunday) workingDay--;

            return workingDay;
        }

C#: Struct vs Class

Posted by Unknown On Wednesday, June 7, 2017 0 comments
Classes:
  • Can support inheritance
  • lives on the heap
  • Are reference (pointer) types. Value passing around from method to method
  • The reference can be null
  • Have memory overhead per new instance
  • Can have an explicit parameterless constructor
  • Can have destructors
Structs:
  • Cannot support inheritance
  • lives on the stack
  • Are value types
  • Are passed by value: all struct types implicitly inherit from the class System.ValueType. Assignment to a variable of a struct type creates a copy of the value being assigned
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance - unless 'boxed'
  • Cannot have an explicit parameterless constructor
  • Cannot have destructors
Both Classes and Structs:
  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces
When should you use Structs: base on Microsoft MSDN
CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
AVOID defining a struct unless the type has all of the following characteristics:
·         It logically represents a single value, similar to primitive types.
·         It has an instance size under 16 bytes.
·         It is immutable.
·         It will not have to be boxed frequently.

EF: C# Update or Insert if not exist

Posted by Unknown On Tuesday, June 6, 2017 0 comments

If your primary key is auto increment


public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        context.Entry(blog).State = blog.BlogId == 0 ? EntityState.Added : EntityState.Modified;  
        context.SaveChanges(); 
    } 
}

If your primary key is not auto increment


public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        var q = context.Blog.FirstOrDefault(x=>x.BlogId=blog.BlogId);        
        if (q != null)
            context.Entry(q).State = EntityState.Detached;
        context.Entry(blog).State = q == null ?EntityState.Added : EntityState.Modified; 
        context.SaveChanges(); 
    } 
}