Posts

Showing posts from June, 2021

C# Yield

Image
When building a method that returns IEnumerable, you can use the yield keyword to return results one at a time, rather than returning a full collection. This is useful if your collection would be very large, or if you want results as fast as you can rather than waiting. View code on GitHub

View Job History in SQL Server

create procedure util . ViewJobHistory ( @ExecutionDate date = null , @JobName sysname = null ) as begin declare @executionDateInt int ; set @executionDateInt = year ( @ExecutionDate ) * 10000 + month ( @ExecutionDate ) * 100 + day ( @ExecutionDate ) ; select JobName , JobSuccess , RunDateFormatted + ' ' + left ( RunTimePadded , 2 ) + ':' + substring ( RunTimePadded , 3 , 2 ) + ':' + right ( RunTimePadded , 2 ) [ RunDateTime ] , DurationSeconds + ( 60 * DurationMinutes ) + ( 60 * 60 * DurationHours ) [ TotalDurationSeconds ] from ( select sj . name [ JobName ] , case sjh . run_status when 1 then 'Success' else 'FAIL' end [ JobSuccess ] , left ( cast ( sjh . run_date as varchar ( 8 )

Shrink image with ImageMagick

@ ECHO OFF SETLOCAL FOR / R %%G IN ( *.jpg ) DO CALL :process "%%G" GOTO :end :process SET _inname = %1 SET _outname = %_inname:~0,-5%_1024.jpg" identify - format %%w %_inname% > width.txt identify - format %%h %_inname% > height.txt set / p width = < width.txt set / p height = < height.txt DEL width.txt DEL height.txt ECHO Processing %_inname% ... if %width% gtr %height% call :landscape %_inname% %_outname% if %height% geq %width% call :portrait %_inname% %_outname%      rem convert %_inname% %_inname% EXIT / B :landscape convert %_inname% - resize 1024x - quality 90 %_outname% EXIT / B :portrait convert %_inname% - resize x1024 - quality 90 %_outname% EXIT / B :end

SQL Server Flatten and Unflatten

Assuming you have a table type named SingleColumnText which contains (obviously) a single column of text, named [TextValue]: create function util . Flatten ( @input util . SingleColumnText readonly , @delimiter nvarchar ( max ) ) returns nvarchar ( max ) as begin declare @result nvarchar ( max ) ; select @result = coalesce ( @result + @delimiter , '' ) + TextValue from @input order by PK ; return @result ; end ; go create function util . Unflatten ( @input nvarchar ( max ) , @delimiter nchar ( 1 ) ) returns table as return ( select row_number ( ) over ( order by n ) - 1 [ Idx ] , substring ( @input , n , charindex ( @delimiter , @input + @delimiter , n ) - n ) [ TextValue ] from util . Numbers where n < = len ( @input ) and substring ( @delimiter + @input , n , 1 ) = @delimiter ) ; go

Add timestamp to photo using ImageMagick

rem dptnt.com/2009/04/how-to-add-date-time-stamp-to-jpeg-photos-using-free-software/ @ ECHO OFF SETLOCAL FOR / R %%G IN ( *.jpg ) DO CALL :process "%%G" GOTO :end :process SET _inname = %1 identify - format %%w %_inname% > dttmpfile set / p width = < dttmpfile Set / a pointsize = %width% / 50 rem echo ZZ >> dttempfile DEL dttmpfile ECHO Processing %_inname% ... convert %_inname% - gravity SouthEast - font Arial - pointsize %pointsize% - fill orange - annotate +%pointsize%+%pointsize% "%%[exif:DateTimeOriginal]" %_inname% EXIT / B :end

Type-safe JSON result in ASP.NET MVC

public abstract class BaseController : Controller { protected internal JsonResult < T > Json < T > ( T data ) { return Json ( data , null /* contentType */ , null /* contentEncoding */ , JsonRequestBehavior . DenyGet ) ; } protected internal JsonResult < T > Json < T > ( T data , string contentType ) { return Json ( data , contentType , null /* contentEncoding */ , JsonRequestBehavior . DenyGet ) ; } protected internal virtual JsonResult < T > Json < T > ( T data , string contentType , Encoding contentEncoding ) { return Json ( data , contentType , contentEncoding , JsonRequestBehavior . DenyGet ) ; } protected internal JsonResult < T > Json < T > ( T data , JsonRequestBehavior behavior ) { return Json ( data , null /* contentType */ , null /* contentEncoding */ , behavior ) ; } protected internal JsonResult &

Replace alert with SweetAlert

SweetAlert is a nice simple solution for displaying alert messages. Here’s the basic way to replace the built-in alert, so you don’t have to use the custom swal function: < link href = "/styles/sweetalert.css" rel = "stylesheet" type = "text/css" > < style type="text/css"> . sweet-alert h2 { font-size : 21 px ; font-weight : 500 ; line-height : 23.1 px ; } </ style > <!-- SweetAlert does not work in IE8 or prior --> <!--[ if gt IE 8 | ! IE ]> <!-->    <script src="/scripts/sweetalert.min.js" type="text/javascript"></script>    <script type="text/javascript">        window.alert = function () {            if (arguments == null) {                swal(" ");            } else if (typeof arguments[0] === "number") {                swal(arguments[0].toString());            } else {                swal(argumen

Queue and Stack in javascript

Using basic array functions, you can treat an array as a queue (first in first out) or a stack (last in first out): To act as a queue, use the shift function: while ( arr . length ) { let val = arr . shift ( ) ; console . log ( val ) ; } To act as a stack, use the pop function: while ( arr . length ) { let val = arr . pop ( ) ; console . log ( val ) ; }

Read/write large blob to SQL Server from C#

Rather than try to make it happen in one big command, here’s breaking it out into many commands. Whether or not you use the transaction is up to you and your use case – you could always have a “Completed” column and only set that to true after success, if you wanted to skip a transaction. First, insert a record, leaving the blob column as an empty byte array, making sure you have access to the primary key of the record you just inserted: using var conn = new SqlConnection ( _config . GetConnectionString ( " MyDB " ) ) ; await conn . OpenAsync ( ) . ConfigureAwait ( false ) ; using var tran = ( SqlTransaction ) await conn . BeginTransactionAsync ( ) ; int fileID ; using ( var comm = conn . CreateCommand ( ) ) { comm . Transaction = tran ; comm . CommandText = @"         insert dbo.Files (FileName, FileContents)         values (@FileName, 0x);         select scope_identity();      " ; comm . Parameters . AddWithValue ( " @

Handlebars in NodeJS

" use strict " ; ( function ( ) { const handlebars = require ( " handlebars " ) ; const source = " {{title}} \n " + " Hello {{person.name}}, I see that you are {{person.age}} years old. \n " + " You have the following cars: \n " + " {{#each cars}} \n " + " {{year}} {{make}} {{model}} {{#if color}}(Color={{color}}){{/if}} \n " + " {{/each}} \n " ; const template = handlebars . compile ( source ) ; const data = { title : " My Data Object " , person : { name : " Billy " , age : 34 } , cars : [ { year : 2015 , make : " Ford " , model : " Mustang " , color : " Red " } , { year : 2014 , make : " Chevy " , model : " Corvette " } , { year : 2013 , make : " Dodge

AJAX in Angular

Regular GET/POST $http ( { method : " POST " , url : " someUrl " , headers : { " Content-Type " : " application/json; charset=utf-8 " } , data : JSON . stringify ( { name : " John Doe " } ) } ) . then ( function ( response ) { console . log ( " Successful response: " + response ) ; } , function ( response ) { console . log ( " Error response: " + response ) ; } ) ; JSONP (in a factory) // Make sure you include it in DI: app.factory("myFactory", function ($http, $sce) { factory . getSomething = function ( callback ) { const URL = " http://something.../?param=someval&param2=otherval " ; var url = $sce . trustAsResourceUrl ( URL ) ; $http . jsonp ( url , { jsonpCallbackParam : " callback " } ) . then ( function ( response ) { console . log ( " Successful re

.NET Console Application Dependency Injection

Image
When working with console applications, you need to manually define your service provider and scopes, but other than that, it functions as you are used to with ASP.NET. Make sure you're choosing the proper lifecycle for your dependencies - Singleton, Transient, or Scoped. View code on GitHub

Is Development in Razor View

I find myself needing to know if I'm in development from inside a Razor view. In the C# code, you can generally use the #DEBUG preprocessor directive , but it’s not quite so easy in Razor. I've used an extension method on HtmlHelper to kind of cheat, but the “correct” way seems to be to inject the host environment and call the IsDevelopment method: @using Microsoft . Extensions . Hosting @inject Microsoft . AspNetCore . Hosting . IWebHostEnvironment HostEnvironment @if (HostEnvironment . IsDevelopment()) { < link rel = "stylesheet" href = "~/css/site.css" asp-append-version = "true" > } else { < link rel = "stylesheet" href = "~/css/site.min.css" asp-append-version = "true" /> } @if (HostEnvironment . IsDevelopment()) { < script src = "~/js/bundle.js" asp-append-version = "true" > </ script > } else { < script src = "~/js/bundle.mi

JSONP with jQuery and ASP.NET

JSONP allows you to execute something similar to AJAX, across domains without worrying about whether the request is across domains, or any special CORS configuration. It’s not generally a huge deal to set up CORS, but JSONP is guaranteed to work in all browsers and servers without any special handling. function go ( ) { jQuery . ajax ( { // url: "/Home/DoSomething", // Regular MVC // url: "/Handler1.ashx", // WebForms data : { xyz : " World " } , dataType : " jsonp " , type : " get " } ) . done ( function ( result ) { console . log ( result ) ; } ) ; } // Regular MVC - no special filters, return types, etc. public ActionResult DoSomething ( string xyz ) { Response . ContentType = " application/json " ; var foo = new { FirstName = " John " , LastName = " Doe " , Message = " Hello " + xyz }

jQuery noConflict

If you need to inject a specific version of jQuery into a webpage that may or may not already have a different version of jQuery, or if you specifically need two different versions loaded, then you can use jQuery.noConflict. You might use this if you’re building a custom control that gets injected into a page, where you want to make sure your stuff works as intended, but you don’t want to accidentally upgrade or downgrade the main page’s jQuery. This sample will show how to load jQuery 1.8.3 into a page which may or may not already have a different version loaded. var _jq183 ; function load183 ( ) { if ( typeof window . jQuery === " function " && window . jQuery . fn && window . jQuery . fn . jquery === " 1.8.3 " ) { _jq183 = window . jQuery ; return ; } if ( typeof window . jQuery === ' undefined ' || ! window . jQuery . fn || ( window . jQuery . fn . jquery !== " 1.8.3 "

jQuery Filter by Data

jQuery won’t let you search using a regular selector for data attributes if those data attributes were added using the data function: jQuery ( " #something " ) . data ( " somekey " , " someval " ) ; jQuery ( " #something[data-somekey=someval] " ) ; // does not find it Instead, define a new function: jQuery . fn . filterByData = function ( prop , val ) { return this . filter ( function ( ) { return jQuery ( this ) . data ( prop ) == val ; } ) ; } ; jQuery ( " #something " ) . filterByData ( " somekey " , " someval " ) ; // finds it StackOverflow question: http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value Stackoverflow answer: http://stackoverflow.com/a/15651670/111266