Code Optimization

Interesting things about software development and code optimization

Performance Profiler Could not load type System.Threading.Interlocked

If you run into this issue trying to profiling your code with Visual Studio Performance Profiler and getting this error:

Unhandled exception. System.TypeLoadException: Could not load type System.Threading.Interlocked

This is because of you enabled the checkbox under the CPU Usage > Collect call counts (.Net Only)







Just disable it and it should start working again.


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Microsoft Phone Link app hangs on the "hold on while we get your device ready" screen

Hi friends,


Seems you have the similar issue, opening the Phone Link app just hangs on the first screen saying "hold on while we get your device ready" and spinning endless here.

Also, it may say something different but still you can not continue and start using it, i think these steps will help you solving this issue.


First step - go to Settings > Accounts > Email & accounts

Second step - scroll down to the "Accounts used by other apps" section and find there you microsoft account

Third step - change its "Sign in options" from "Microsoft apps can sign me in" to "Apps need to ask me to use this account"


Now try to open the Phone Link app. It should start asking you about your microsoft account and continue through whole process.



Happy Phone Link use! ))))


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Power of .Net and Windows Update

Hello friends,


Let me first describe all issues I had at once :)

Visual Studio
unknown error  .../Roaming/Microsoft/Visual Studio/ActivityLog.xml
Could not locate appropriate CLR version. Try rebooting, reinstalling.
Failure calling VsHookCLRLoading.

MS SQL
Failed to initialize the Common Language Runtime (CLR) v4.0.30319 with HRESULT 0x80004005. You may fix the problem and try again later.

PowerShell
(unfortunately I didn't capture exact error but Terminal just started and showed error like 0x........)


What was that? In my case it was just windows update installed :)


after some googling I have found solution from microsoft and in my case this one line resolved all issues:


dism /online /enable-feature /featurename:netfx3 /all


if you have WCF then you may need these two as well:


dism /online /enable-feature /featurename:WCF-HTTP-Activation
dism /online /enable-feature /featurename:WCF-NonHTTP-Activation



Thank you and good luck :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



WPF System.Windows.Media.Fonts.SystemFontFamilies does not see all system fonts installed

Hello friends,


Today i would like to share one case i have faced with - WPF application that uses

 System.Windows.Media.Fonts.SystemFontFamilies can't see a font I have just installed but Word and other applications were able to see it immediately.

I did try Font Cache and Font Cache 3.0.0 and font cach data clearing but with no luck.


The only way to bring an installed font to my WPF application was to switch the projetc's target .Net version from 3.5 

to 4.8


Don't know if its my case only or common issue in .Net 3.5 but hope it will help someone at some time


Thank you ;)




1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Format a string to set comma delimited for every thousand

Hello friends,


as the title reads here is the easy way to put comma for every thousand in your string:

String mileage = "1234567";
String newMileage = mileage;
for (int i = 1; i <= (mileage.length) / 3; i++) {
    if (newMileage.length - (i * 3) - (i - 1) > 0) {
        newMileage = newMileage.substring(
                    0, newMileage.length - (i * 3) - (i - 1)) +
                    "," +
                    newMileage.substring(newMileage.length - (i * 3) - (i - 1));
     }
}

the output will be like that:

123
1,234
1,234,567
...


Thank you and see you :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



USB 3.0 - 3.2 and SSD speed or what the hell is going on here (en)

Hi friends!


You have just bought a leptop or PC that supports USB 3.0-3.2 (blue color of USB ) and an External Drive case with USB 3.0-3.2 for your external SSD and decided that you would taste the speed, power and all other benefits of the latest technologies?


You have just plugged-in your external SSD and started copying files from/to your PC/laptop and enjoying of the process thinking that 50MBytes per second is the maximum of all of that?


But just do a simple calculations in your head or just think/google about that USB 3.0-3.2 and SSD - supports  more than 500 MBytes per second or 10 times faster or should take 6 minutes instead of 1 hour (60 min)?


What? What is wrong?! - you would say


Main issue is in that that Windows (oh wily) turn all these benefits by default in favor to non-safe device ejecting so you would just pull it out and forget about it :)


Yeah-yeah, so you would just pull it out without the "Safely Remove hardware and Eject media"


So would can you do? - there is a way! If you are an advanced user (or just like to get into troubles all the time ;) ) and really want to get most of the all latest technologies along be able to respond for all your doings - then just enable this option (see the screenshot) via Device Properties.


Pay Attention! from now you should always use the "Safely Remove hardware and Eject media"! or you will find yourself with lost or corrupted data.




Thank you for reading :) 

you owe me just a 5 bitcoins - but what the knowledge and I saved you a lot of time! ;)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



USB 3.0 - 3.2 and SSD speed or what the hell is going on here

Привет друзья!


вы купили ноутбук или компьютер с поддержкой USB 3.0-3.2 (синего цвета разъем USB ) и карман с поддержкой USB 3.0-3.2 для внешнего SSD диска и решили что теперь то вы насладитесь скоростью, мощью и всеми преимуществами новых технологий?


подключили внешнее устройство и начали копировать файлы с компьютера/ноутбука на диск или обратно и наслаждаетесь процессом думая что 50МБ в секунду это максимум что позволяет технология и это то что вы ожидали?


а как на счет элементарных расчетов в голове или того что USB 3.0-3.2 и SSD - это минимум >500 МБ в секунду или в 10 раз быстрее или вместо 1 часа всего 6 минут?


как так? что такое?! - скажите вы,


проблема в том что Windows (вот хитрюги) по умолчанию отключает все эти преимущества в пользу небезопасного извлечения устройства тоесть без использования "безопасное извлечение устройства" иконки в вашей панели задач :)


да-да, чтоб вы могли просто выдернуть внешнее устройство из USB без всяких там "безопасных извлечений"


так что же делать? - выход есть! если вы продвинутый пользователь (или просто любите попадать в неприятные ситуации) и реально хотите ощутить всю мощь технологий и при

этом готовы отвечать за свои поступки - тогда включите эту опцию (см. скриншот) через свойства устройства.


но не забудьте! теперь вам нужно извлекать внешнее устройство только через "безопасное извлечение устройства"!




спасибо за внмание :) с вас всего каких-то 5 биткоинов - но зато какой ноледж и куча сэкономленного времени! ;)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



MS SQL Batch or Bulk UPDATE and all around EF

Dear friends,


Thank you for comming and here I will show you how to make a huge bulk UPDATE in database from your C# code using Entity Framework.

My issue was about calculation prices for +50K products and then updating these product prices all at once.

Before this optimization SQL Update took more than 60 seconds ( using different approaches and of course you even should not think to do it with EF update/save method at all). After implementation of this approach we get less than 10 seconds for updating +50K products (of course it depends on hosting and environment you use). So what is that?


Table-Valued Parameters

yes, may be you have heard about it but have not understand it enough to use or just have not believed that it would really help you.


So everything is really easy - you create table, put all data you need for your update - it is +50K rows and pass it to your stored procedure that knows how to use it, here is an example:

- create table and columns

                            DataTable tblUpdate = new DataTable();
                            tblUpdate.Columns.Add("Id", typeof(int));               
                            tblUpdate.Columns.Add("DeliveryDateId", typeof(int));   
                            tblUpdate.Columns.Add("OldPrice", typeof(decimal));     
                            tblUpdate.Columns.Add("Price", typeof(decimal));        
                            tblUpdate.Columns.Add("ProductCost", typeof(decimal));  
                            tblUpdate.Columns.Add("AdditionalShippingCharge", typeof(decimal)); 
                            tblUpdate.Columns.Add("DisableBuyButton", typeof(bool));
                            tblUpdate.Columns.Add("Published", typeof(bool));       
                            tblUpdate.Columns.Add("AdminComment", typeof(string));  
                            tblUpdate.Columns.Add("UpdatedOnUtc", typeof(DateTime));

- add rows

...
                            object[] row = new object[10];                            
                            ...
                            ...
                            tblUpdate.Rows.Add(row);
                            ...

- now it is time to push it to SQL

                            var dataSettings = Core.Data.DataSettingsManager.LoadSettings();

                            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(dataSettings.DataConnectionString))
                            {
                                conn.Open();
                                
                                //check if table-valued type is already exists
                                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
@"IF TYPE_ID(N'TargetUDT') IS NULL CREATE TYPE [TargetUDT] AS TABLE
(
Id int not null,
DeliveryDateId int not null,
OldPrice decimal(18,4) not null,
Price decimal(18,4) not null,
ProductCost decimal(18,4) not null,
AdditionalShippingCharge decimal(18,4) not null,
DisableBuyButton bit not null,
Published bit not null,
AdminComment nvarchar(max) null,
UpdatedOnUtc datetime not null
);", conn))
                                {
                                    cmd.CommandType = CommandType.Text;
                                    cmd.ExecuteNonQuery();
                                }

//create or update stored procedure using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand( @"CREATE OR ALTER PROCEDURE usp_UpdateAllProdPrices (@tvpUpdateProducts [TargetUDT] READONLY) AS BEGIN UPDATE dbo.Product SET Product.DeliveryDateId = ec.DeliveryDateId, Product.OldPrice = ec.OldPrice, Product.Price = ec.Price, Product.ProductCost = ec.ProductCost, Product.AdditionalShippingCharge = ec.AdditionalShippingCharge, Product.DisableBuyButton = ec.DisableBuyButton, Product.Published = ec.Published, Product.AdminComment = ec.AdminComment, Product.UpdatedOnUtc = ec.UpdatedOnUtc FROM @tvpUpdateProducts AS ec INNER JOIN dbo.Product ON dbo.Product.Id = ec.Id END", conn)) { cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } //run the stored procedure and pass the all data as table-valued parameter using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand( @"usp_UpdateAllProdPrices", conn)) { System.Data.SqlClient.SqlParameter tvpParam = cmd.Parameters.AddWithValue("@tvpUpdateProducts", tblUpdate); tvpParam.SqlDbType = SqlDbType.Structured; tvpParam.TypeName = "[TargetUDT]"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.ExecuteNonQuery(); } conn.Close(); }


That's it guys enjoy your super-fast bulk update :)




Thank you and see you :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Unable to find vcvarsall.bat or not found

Dear User,


If you re-installed your Visual Studio or updated it to a new version then you may loose the vcvarsall.bat file and here are quick steps to restore it:

1. Run the Visual Studio Installer

2. See the screenshot below to find the package you need

3. Click install/modify




After installed you will find it there (depending on a drive you installed your Visual Studio):

D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build



Thank you and see you ;)



1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



The Kotlin Language Client server crashed 5 times in the last 3 minutes. The server will not be restarted.

Hello friends,


seems like you have faced the same issue like me ;)


What I can say is that I was not able to fully solve this issue but I solved it partially at least.

So if you see this error in the Visual Studio Code:

The Kotlin Language Client server crashed 5 times in the last 3 minutes. The server will not be restarted.

then you have Kotlin extension installed and while updating it you hit this issue.


To be able to work, build and debug my app i did the following:

- uninstall the Kotlin extension


yes - not just disable but uninstall it and now you can continue working with Flutter & Dart


please note, even you have Kotlin Language extension that is more similar to the error the real problem is in the Kotlin extension itself.


If I will find out further steps to resolve it completely I will update this post.


Thank you and see you soon! :)



1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y