adsense

Tuesday, December 17, 2024

Code analysis with CodeQL

 CodeQL is a set of software tools that work together to perform a specific task or series of tasks.  This includes various tools for tasks such as compiling, linking , debugging, code analysis and Testing.

Read more on CodeQL here.


Cheers,

Samitha

Sunday, November 24, 2024

Increase EF Core Efficiency: with Bulk Updates

 ExecuteUpdate was introduced in EF Core 6.0 to improve data manipulation capabilities. 

To demonstrate the use of ExecuteUpdate,  let's consider examples below. 


using (var context = new DbContext())


var items= context.Items.ToList();

foreach (var item in items)

{

    item .Name = "XXX";

    item .LastUpdateDateTime = DateTime.UtcNow;

}

context.SaveChanges();


The first example uses the traditional approach of iterating over a list of items and updating each one.


context.Items.ExecuteUpdate(i => i.SetProperty(p => p.Name, "XXX")

                                 .SetProperty(g => p.LastUpdateDateTime, DateTime.UtcNow))


The second example uses ExecuteUpdate.


When consider a bulk update, EFCore will generate the following query for each line. As a result for 1000 lines, 1000 SQL queries will be executed.

 --Sigle query for bulk updates

UPDATE "Items" AS "i"

SET "LastUpdateDateTime" = rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now'), '0'), '.'),

    "Name" = 'XXX'

 The ExecuteUpdate method translates the update operation into a single SQ query executing without loading entities into memory. This results in significant performance gains, particularly noticeable in large-scale operations.

You can read more about ExecuteUpdate here.

Regards,

Samitha

:

Sunday, November 10, 2024

EF Core AsSplitQuery

 AsSplitQuery will perform separate queries instead of complex joins when returning data from multiple tables. 

When using a single query result with data from multiple tables,  there is a probability of   “cartesian explosion” of duplicate data across many columns and rows.


e.g

  var result =dbContext.Student.Where(s=> s.Id == id)

      .Include(x => x.Books)

      .ThenInclude(x => x.Overdues)

      .AsSplitQuery();


Cheers,

Samitha

Monday, October 14, 2024

Assign an empty string if the value is null in Linq

 If you ever wanted to assign an empty string to a value returned from a Linq query, use ?? (null-coalescing operator) to return Empty string in case of null


var qry= from row in context.Table

select new {  FieldValue = (field.Value ?? string.Empty) };


Cheers,

Samitha

Friday, September 13, 2024

C # 8 More concise Switch

 In C# 8.0, the Switch statements has become more powerful with patterns. All the  cases have turned into expressions and become more readable. 

Following code illustrates basic usage of new switch.

var action= 1;


var result = operation switch

{

    1 => "Action 1",

    2 => "Action 2",

    3 => "Action 3",

    4 => "Action 4",

    _ => "No Action  performed"

};


Console.WriteLine(result );


More information can be found here.

Chaeers,

Samitha

Sunday, September 8, 2024

EF .Net Core AsNoTracking

EF .Net Core retrieves entities from the database with racking enabled, meaning any changes made to the entity are observed and can be automatically saved back to the database.

This automatic monitory feature is not optimal when it comes to read only operations (SELECT statements). To get more information on Tracking Vs Non Tracking queries read following Microsoft article.

As an optimization for read-only queries we can AsNoTracking as shown below. Adding this will stop E EF Core tracking the results, returning in improved performance as EF Core doesn't manage the state of the entity.

var books= dbContext.Books

    .AsNoTracking()

    .ToList();

 

Cheers,

Samitha

Sunday, August 18, 2024

Enumerable Check empty

 When working with Enumerable in .Net, there is always a possibility of returning an empty Enumurable if no match is found. Consider the following code.

private IEnumarable<Book> GetBook(string name)

{

   if (string.IsNullOrEmpty(name))

     return Enumerable.Empty<Book>();


  return _dbContext.Book.Where(b => b.Name.ToLower().Contains(name)); 

}

In the above piece of code  Enumerable.Empty method is used to check the null name and return an empty book rather than returning null which can cause runtime exception if  the name is not  supplied. This is considered as defensive code practice.


Cheers,

Samitha

Sunday, July 21, 2024

: The imported project Microsoft.TextTemplating.targets" was not found

 When building Visual studio you might encounter the error MSB4019: The imported project Microsoft.TextTemplating.targets" was not found.


To fix this error

  • Open the csproj in editor
  • Find following 
        <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v16.0\TextTemplating\Microsoft.TextTemplating.targets" />

  • Change it to following and save
"$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TextTemplating\Microsoft.TextTemplating.targets"

  • Reload the project and build

Cheers,
Samitha

Saturday, June 29, 2024

Entityframework Extensions

Entityframework Extensions  can be used to  improve your performance dramatically.


You can  perform: following operations easily.

  • BulkSaveChanges
  • BulkInsert
  • BulkUpdate
  • BulkDelete
  • BulkMerge 

Read more at https://entityframework-extensions.net/

Cheers,

Samitha

Sunday, June 9, 2024

Serilog Sinks

Serilog Sinks are the way instruct Serilog to store your logs. The most frequently used  sinks are the File and Console .

When you are doing development it is advisable to try the Debug sink to see your log statements in the Visual Studio Debug window without  having to open a log file.

Here are some of the available sinks.

NameDestinationPackage
Amazon CloudWatchAmazonCloudWatchSerilog.Sinks.AwsCloudWatch
NuGet Version
Amazon DynamoDBDynamoDBSerilog.Sinks.DynamoDB
NuGet Version
Amazon KinesisAmazonKinesisSerilog.Sinks.AmazonKinesis
NuGet Version
Amazon S3AmazonS3Serilog.Sinks.AmazonS3
NuGet Version
AMQPAMQPSerilog.Sinks.AMQP.Batching
NuGet Version
Apache SkywalkingSkywalkingSerilog.Sinks.Skywalking
NuGet Version
Application InsightsApplicationInsightsSerilog.Sinks.ApplicationInsights
NuGet Version
Async WrapperAsyncSerilog.Sinks.Async
NuGet Version
Azure AnalyticsAzureAnalyticsSerilog.Sinks.AzureAnalytics
NuGet Version
Azure App ServiceAzureAppSerilog.Sinks.AzureApp
NuGet Version
Azure Blob StorageAzureBlobStorageSerilog.Sinks.AzureBlobStorage
NuGet Version
Azure CosmosDBAzureCosmosDBSerilog.Sinks.AzureCosmosDB
NuGet Version
Azure CosmosDBalternativeAzCosmosDBSerilog.Sinks.AzCosmosDB
NuGet Version
Azure Data ExplorerAzureDataExplorerSerilog.Sinks.AzureDataExplorer
NuGet Version
Azure DocumentDBAzureDocumentDBSerilog.Sinks.AzureDocumentDB
NuGet Version
Azure Event GridEventGridSerilog.Sinks.EventGrid
NuGet Version
Azure Event HubsAzureEventHubSerilog.Sinks.AzureEventHub
NuGet Version
Azure Queue StorageAzureQueueStorageSerilog.Sinks.AzureQueueStoragev2
NuGet Version
Azure Table StorageAzureTableStorageSerilog.Sinks.AzureTableStorage
NuGet Version
Azure Web Jobs*TraceWriterSerilog.Sinks.AzureWebJobsTraceWriter
NuGet Version
CouchBaseCouchbaseSerilog.Sinks.Couchbase
NuGet Version
CouchDBCouchDBSerilog.Sinks.CouchDB
NuGet Version
ConsoleConsoleSerilog.Sinks.Console
NuGet Version
Colored ConsoleColoredConsoleSerilog.Sinks.ColoredConsole
NuGet Version
DataDogDatadogSerilog.Sinks.DataDog
NuGet Version
DataDog LogsDatadogLogsSerilog.Sinks.Datadog.Logs
NuGet Version
DebugDebugSerilog.Sinks.Debug
NuGet Version
DynatraceDynatraceSerilog.Sinks.Dynatrace
NuGet Version
ElasticsearchElasticsearchSerilog.Sinks.Elasticsearch
NuGet Version
elmah.ioElmahIoSerilog.Sinks.ElmahIo
NuGet Version
EmailEmailSerilog.Sinks.Email
NuGet Version
Email PickUpEmailPickupSerilog.Sinks.EmailPickup
NuGet Version
Excel-DNAExcelDnaLogDisplaySerilog.Sinks.ExcelDnaLogDisplay
NuGet Version
ExceptionlessExceptionlessSerilog.Sinks.Exceptionless
NuGet Version
FileFileSerilog.Sinks.File
NuGet Version
FluentDFluentd
GlimpseGlimpseSerilog.Sinks.Glimpse
NuGet Version
Google Cloud PubSubGoogleCloudPubSubSerilog.Sinks.GoogleCloudPubSub
NuGet Version
Google Cloud Stack DriverGoogleCloudLoggingSerilog.Sinks.GoogleCloudLogging
NuGet Version
GrayLogGraylogSerilog.Sinks.Graylog
NuGet Version
HumioHumioSerilog.Sinks.Humio
NuGet Version
HTTPHttpSerilog.Sinks.Http
NuGet Version
In-memory/assertionsInMemorySerilog.Sinks.InMemory
NuGet Version
LiteDBLiteDBSerilog.Sinks.LiteDB
NuGet Version
Literate ConsoleLiterateConsoleSerilog.Sinks.Literate
NuGet Version
Log4NetLog4NetSerilog.Sinks.Log4Net
NuGet Version
LogDNALogDNASerilog.Sinks.LogDNA
NuGet Version
LogEntriesLogEntriesSerilog.Sinks.LogEntries
NuGet Version
LogglyLogglySerilog.Sinks.Loggly
NuGet Version
Loggly (Bulk API)LogglySerilog.LogglyBulk
NuGet Version
LogifyLogifyAlertLogify.Alert.Serilog
NuGet Version
Logmatic.ioLogmaticSerilog.Sinks.Logmatic
NuGet Version
LoggrLoggrSerilog.Sinks.Loggr
NuGet Version
MariaDBMariaDBSerilog.Sinks.MariaDB
NuGet Version
MartenMartenSerilog.Sinks.Marten
NuGet Version
MEL ILoggerILoggerSerilog.Sinks.ILogger
NuGetVersion
Microsoft TeamsMicrosoftTeamsSerilog.Sinks.MicrosoftTeams
NuGet Version
Microsoft TeamsalternativeMicrosoftTeamsSerilog.Sinks.MicrosoftTeams.Alternative
NuGet Version
MongoDBMongoDBSerilog.Sinks.MongoDB
NuGet Version
NatsNatsSerilog.Sinks.Nats
NuGet Version
NewRelicNewRelic
NetworkTCP or UDPSerilog.Sinks.Network
NuGet Version
NLogNLogSerilog.Sinks.NLog
NuGet Version
NotepadNotepadSerilog.Sinks.Notepad
NuGet Version
ObservableObserversSerilog.Sinks.Observable
NuGet Version
OrientDBOrientDBSerilog.Sinks.OrientDB
NuGet Version
Period BatchingSerilog.Sinks.PeriodicBatching
NuGet Version
PostgreSQLPostgreSQLSerilog.Sinks.PostgreSQL
NuGet Version
PostgreSQLalternativePostgreSQLSerilog.Sinks.Postgresql.Alternative
NuGet Version
RabbitMQRabbitMQSerilog.Sinks.RabbitMQ
NuGet Version
RavenDBRavenDBSerilog.Sinks.RavenDB
NuGet Version
RayGunRaygunSerilog.Sinks.Raygun
NuGet Version
RethinkDBRethinkDBSerilog.Sinks.RethinkDB
NuGet Version
RichTextBox.WpfRichTextBoxSerilog.Sinks.RichTextBox.Wpf
NuGet Version
RollbarRollbarSerilog.Sinks.RollbarCom
NuGet Version
Rolling FileRollingFileSerilog.Sinks.RollingFile
NuGet Version
Rolling FilealternativeRollingFileAlternateSerilog.Sinks.RollingFileAlternate
NuGet Version
ScalyrScalyrSerilog.Sinks.Scalyr
NuGet Version
SentrySentrySerilog.Sinks.Sentry
NuGet Version
SeqSeqSerilog.Sinks.Seq
NuGet Version
SignalRSignalRSerilog.Sinks.SignalR
NuGet Version
SlackSlackSerilog.Sinks.SlackClient
NuGet Version
SQLiteSQLiteSerilog.Sinks.SQLite
NuGet Version
SplunkEventCollectorSerilog.Sinks.Splunk
NuGet Version
SQL ServerMSSqlServerSerilog.Sinks.MSSqlServer
NuGet Version
StackifyStackifySerilog.Sinks.Stackify
NuGet Version
Sumo LogicSumoLogicSerilog.Sinks.SumoLogic
NuGet Version
Sumo Logic (by Sumo Logic)SumoLogicSumoLogic.Logging.Serilog
NuGet Version
Syslog (RFC5424)SyslogSerilog.Sinks.SyslogServer
NuGet Version
Syslog (RFC5424RFC3164)UdpSyslogTcpSyslogLocalSyslogSerilog.Sinks.SyslogMessages
NuGet Version
TelegramTelegramSerilog.Sinks.Telegram
NuGet Version
TelegramalternativeTelegramSerilog.Sinks.Telegram.Alternative
NuGet Version
TestCorrelatorTestCorrelatorSerilog.Sinks.TestCorrelator
NuGet Version
Text WriterTextWriterSerilog.Sinks.TextWriter
NuGet Version
TraceTraceSerilog.Sinks.Trace
NuGet Version
UDPUdpSerilog.Sinks.UDP
NuGet Version
Unity3DUnity3DSerilog.Sinks.Unity3D
OpenUPM Version
Windows Event LogEventLogSerilog.Sinks.EventLog
NuGet Version
XamarinNSLog AndroidLogSerilog.Sinks.Xamarin
NuGet Version
XSocketsXSocketsSerilog.Sinks.XSockets
NuGet Version
YouTrackYouTrackSerilog.Sinks.YouTrack

Cheers,
Samitha