Posts

Showing posts from January, 2021

Javascript Async Await

Image
JavaScript gives you lots of different ways to run code asynchronously. Originally callbacks were the only way to go. Now you've got RxJS Observables, Promises, and the newest "async" and "await" keywords, which actually are just syntactic sugar for Promises. Learn more here . View code on GitHub

Send Email with MailKit in .NET

Image
Using MailKit to send email in .NET. The old way with SmtpClient, which was much simpler, is now deprecated in favor of this. For a more thorough example with proper dependency injection and ASP.NET configuration, see this link . View code in GitHub

Mustache with JavaScript in Browser

Image
Mustache is a nice and simple templating engine that can be used just about anywhere. It's not as powerful as others like Handlebars, but its simplicity means there's less to screw up. Learn more about Mustache Learn more about Mustache.js View code on GitHub

Custom Bootstrap

Image
If you use Bootstrap out of the box, you're stuck with the default color scheme, unless you write a bunch of CSS to override it. Here are the basic steps for using Bootstrap's source and choosing your own colors. Depending on what kind of web application you're building - ASP.NET, Angular, etc. - the compilation steps will be different, but the general idea is the same. Bootstrap Starter Template Bootstrap Theming View code on GitHub

C# Using Statements

Image
The new syntax for "using" with C# makes it much easier to nest using blocks together. If you're keeping your methods nice and short in the first place, then you'll probably be able to use this just about everywhere. View code on GitHub

.NET Guid Formats

Image
GUIDs can be a quick (but not secure) way to generate random values in .NET. You can use them in UNIQUEIDENTIFIER columns in SQL Server or the equivalent data type in other database systems. The framework gives you a few formatting options, depending on what you need it for. See the documentation for more about the format strings. Or read more than you ever could possibly want to know about GUID/UUID at Wikipedia. View code on GitHub

.NET Tuples

Image
The new way of writing tuples in C# is much nicer than the old Tuple class. Learn more with the Microsoft docs View code in GitHub

.NET XML Writer

Image
XmlWriter is an easy way to generate XML when you need it. If you're building something more complex, like something for an API, you probably want to go with serialization instead. Otherwise, this is pretty easy to build XML how you want it top to bottom. View code on GitHub

Loops vs HashSets

Image
When looking up data in memory from a large collection, a HashSet or Dictionary is much, much faster than looping through an ordinary collection. This example uses strings - if you run the same code but treat them as GUIDs, the numbers improve quite a bit, but the difference between array and HashSet is still tremendous. View code on GitHub

SQL Server Table Valued Parameters with .NET

Image
private static SqlDataRecord CreatePersonRecord ( int id , string name ) { var metaData = new [ ] { new SqlMetaData ( " Id " , SqlDbType . Int ) , new SqlMetaData ( " Name " , SqlDbType . VarChar , 50 ) } ; var record = new SqlDataRecord ( metaData ) ; record . SetInt32 ( 0 , id ) ; record . SetString ( 1 , name ) ; return record ; } private SqlDataRecord [ ] GetPersonRecords ( ) { retun new [ ] { CreatePersonRecord ( 1 , " John Doe " ) , CreatePersonRecord ( 2 , " Jane Doe " ) } ; } using ( var conn = new SqlConnection ( cs ) ) { conn . Open ( ) ; using ( var comm = conn . CreateCommand ( ) ) { comm . CommandText = " dbo.TestPerson " ; comm . CommandType = CommandType . StoredProcedure ; var peopleParmsValue = GetPersonRecords ( ) ; if ( ! peopleParmsValue . Any ( ) ...

Drop SQL Server Database

Image
 If you're working locally, building a new app from scratch, you might be in a position where you want to wipe the database and start clean – but SQL Server may block you if you've got any open connections or any other issues blocking you. This should set you as the only user of the database, which will clear the way for dropping it without ever getting an error: use master ; go if exists ( select 1 from sys . databases where name = 'SomeDatabase' ) begin alter database SomeDatabase set single_user with rollback immediate ; drop database SomeDatabase ; end ; go View code on GitHub

.NET Passwords

Image
Consider using Identity , Google , domain authentication , or some other solution for authentication, rather than building your own username/password database. But, if you are doing it anyway, here's some code to get you started: View code on GitHub

Razor Pages AJAX

Image
Razor Pages is a fantastic alternative to ASP.NET MVC. Here's one reason - CSRF protection is included by default. That's great news, but it means that you can't execute AJAX posts as easily. Fortunately, it's still not difficult to do a post. Here's how. View code on GitHub

Left Join in Entity Framework

Image
If you need a left join in Entity Framework, you have a couple options. First, if you’re using a real foreign key that just happens to be nullable, then you can use the regular navigation properties. But if you’re doing a left join manually, or with other factors, then you need to do things just a little differently: Suppose we have the following database: create table dbo . Foods ( FoodID int not null identity primary key , FoodName varchar ( 100 ) not null ) ; go insert dbo . Foods ( FoodName ) values ( 'Pizza' ) , ( 'Chicken' ) , ( 'Potatoes' ) , ( 'Broccoli' ) ; go create table dbo . People ( PersonID int not null identity primary key , FirstName varchar ( 100 ) not null , FavoriteFoodID int null , constraint FK_Person_FavoriteFoodID foreign key ( FavoriteFoodID ) references dbo . Foods ( FoodID ) ) ; go insert dbo . People ( FirstName , FavoriteFoodID ) values ( 'John' , 1 ) , ...

HTML Line Breaks With CSS

Image
If you have text on the server that may have line breaks, you may have gone through a series of steps to get it to display properly. First, if you weren't really thinking about it, you just dump the output to the screen. ASP.NET and others HTML encode it, so you generally don't have to worry about any kind of script injection. But the line breaks aren't handled properly. < div id = output > @message </ div > *@ Next thing to try, replacing line breaks with a BR tag. Of course, since it's encoded, the HTML shows up as text, and that's no good. < div id = output > @( message . Replace("\r\n", " < br > ").Replace("\n", " < br > ").Replace("\r", " < br > ") ) </ div > Ok, now you need to use Html.Raw, but you can't do it on the whole string because that will put the dangerous raw text into the page. So you have to encode the message, after replacin...

Simplify XML Serialization

Image
The default XML serialization method in .NET gives you a lot of junk that you may not need. A few simple lines will remove that and give you a simple XML representation. View code on GitHub

SQL Reseed Identity

Image
If you need to manually insert a value into an identity column, but you don't want to interrupt the current identity sequence, you can reseed the value. If you go with a positive value, make sure you pick something higher than you'll ever hit, to avoid an ID collision. Or you can pick a negative number instead. This also gives you the advantage of picking a smaller meaningful number, and easy recognition that this ID is special. Also, if you go negative, you don't need to even both with reseeding the identity. View Code on GitHub

Array.map

Image
Definition [ ] . map ( function ( currVal , idx , arr ) { } [ , thisArg ] ) ; Sample Code // Simple var arr = [ " a " , " b " , " c " ] ; var helloArr = arr . map ( function ( x ) { return " Hello " + x ; } ) ; helloArr . forEach ( console . log ) ; // Using thisArg var item = { sum : 0 } ; var newArray = [ 1 , 2 , 3 ] . map ( function ( x ) { this . sum += x ; return x * 10 ; } , item ) ; console . log ( item . sum ) ; // 6 console . log ( newArray ) ; // [10,20,30] Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Polyfill if ( ! Array . prototype . map ) { Array . prototype . map = function ( callback /*, thisArg*/ ) { var T , A , k ; if ( this == null ) { throw new TypeError ( ' this is null or not defined ' ) ; } var O = Object ( this ) ; var len = O . length >>...