Friday, March 15, 2024

AI means everyone can now be a programmer(?)

Is it that easy?

Assuming you are not a developer and want to create an app to take screenshots on macOS.

You started to ask questions to AI and installed developer tools. Now you are ready for development.

  1. Gemini
  2. How to take a screenshot on macos xcode using swift?

    You paste the code to XCode and see an error!

    Ask Gemini to provide another solution.
    The code you provided in swift didn't work. Suggest another swift way to capture a screenshot.

    Gemini gives an apology and suggests another solution.

    Let's see in XCode.

    Can you see a strange code that contains Arabic letters?

    guard let contentFilter = SCC محتوى الشاشة(sharingMode: .none) else { return nil }

    You want to switch to ChatGPT to accomplish this easy task with the same prompt. 👇

  3. ChatGPT
  4. You paste the code provided by ChatGPT. Again, there is a problem in the code!

    context.makeCurrent() didn't work. Is there any other way?

    You pasted this code, and it worked! After a few trials, now think you are a programmer.

    What will you do if you see CGDisplayCreateImage(_:) is deprecated?

    So you keep asking for alternative ways, and you learn that there is a shiny framework named ScreenCaptureKit.

    I recommend trying to ask both Gemini and ChatGPT to take a screenshot using ScreenCaptureKit. I tried, on several attempts, AI suggested wrong code each time.

    Then you will decide how easy programming is!

Tuesday, November 22, 2022

Gitlab with Visual Studio 2022

Gitlab extension is not available for Visual Studio 2022.

VS Marketplace: GitLab Extension for Visual Studio
You can login any of your favorite GitLab servers and start your great job!
The GitLab Extension for Visual Studio provides GitLab integration in Visual Studio 2015/2017/2019.

In VS 2022, I created a new project and added to local git on user interface.

I also created an empty project on gitlab with the same name.

In gitlab project homepage it helps you what to do.


  cd existing_repo

  git remote add origin https://gitlab.com/git_username/project.git

  git branch -M main

  git push -uf origin main

I switched to command line and run commands above.

When you push the project to remote repository git shows a window for authentication.

I selected browser login and git command got credentials from browser.


C:\project>git push -uf origin main
info: please complete authentication in your browser...
Enumerating objects: 1718, done.
Counting objects: 100% (1718/1718), done.
Delta compression using up to 4 threads
Compressing objects: 100% (1688/1688), done.
Writing objects: 100% (1718/1718), 35.76 MiB | 540.00 KiB/s, done.
Total 1718 (delta 470), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (470/470), done.
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
To https://gitlab.com/git_username/project.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://gitlab.com/git_username/project.git'

The problem was VS created a branch named master, but in gitlab branch name was main.

I created a new branch named master on gitlab.

In command line switch to branch named master and push project to master.

C:\projectO>git branch -M master

C:\project>git push -uf origin master
Enumerating objects: 1718, done.
Counting objects: 100% (1718/1718), done.
Delta compression using up to 4 threads
Compressing objects: 100% (1688/1688), done.
Writing objects: 100% (1718/1718), 35.76 MiB | 561.00 KiB/s, done.
Total 1718 (delta 470), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (470/470), done.
remote:
remote: To create a merge request for master, visit:
remote:   https://gitlab.com/git_username/project/-/merge_requests/new?merge_request%5Bsource_branch%5D=master
remote:
To https://gitlab.com/git_username/project.git

You can create a merge request in gitlab to push master branch into main.

Saturday, October 9, 2021

Windows 10 window border change

Problem

Losing title bar when multiple windows overlap, finding drag position becomes harder.

Solution

>Windows > Settings > Colors
Select "Title bars and windows borders".

Windows Activation Issue

If Windows is not activated you can not change color settings.
We can enable window borders by regedit commands.

reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM" /v "ColorPrevalence" /t REG_DWORD /d "1" /f

reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM" /v "AccentColor" /t REG_DWORD /d "7439985" /f

reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM" /v "AccentColorInactive" /t REG_DWORD /d "13882323" /f

Saturday, April 4, 2020

Failed to install Intel HAXM

When installing Android SDK Platform-Tools on Windows you may see following error:

Running Intel® HAXM installer Failed to install Intel HAXM. 
For details, please check the installation log: HAXM installation failed. To install HAXM follow the instructions found at:
https://software.intel.com/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
This computer does not support Intel Virtualization Technology (VT-x)
or it is being exclusively used by Hyper-V.
HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features,
or refer to the Intel HAXM documentation for more information.
I will list 3 different options.

1. Program and Features

Be sure Hyper-V not marked. If installed uncheck it.

2. Command line (CMD)

dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
or
bcdedit /set hypervisorlaunchtype off

3. Device Guard and Credential Guard hardware readiness tool

Download tool, unzip and open powershell window.

First change execution policy.
PS C:\temp\dgreadiness_v3.6> set-executionpolicy remotesigned 
Execution Policy Change The execution policy helps protect you from scripts that you do not trust.
Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170.
Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): a
Run command.
PS C:\temp\dgreadiness_v3.6> .\DG_Readiness_Tool_v3.6.ps1 -Disable 
Do you want to run software from this untrusted publisher?
File C:\temp\dgreadiness_v3.6\DG_Readiness_Tool_v3.6.ps1 is published by CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US and is not trusted on your system. Only run scripts from trusted publishers.
[V] Never run [D] Do not run [R] Run once [A] Always run [?] Help (default is "D"): a
You will see success messages.
Disabling Hyper-V and IOMMU
Disabling Hyper-V and IOMMU successful
Please reboot the machine, for settings to be applied.
After reboot continue to install HAXM.

Monday, March 16, 2020

Dynamic Assembly Loading (C# Reflection)

We will achieve following task with dynamic assembly loading in C#.

using System.Net.Http;
using System;
using System.Linq;

var client = new HttpClient();
client.BaseAddress = new Uri("http://api.open-notify.org/astros.json");
string result = client.GetStringAsync("").Result;


Don't add System.Net.Http dll to your reference list. It will be automatically loaded from GAC.

using System;
using System.Linq;
using System.Reflection;

//We don't have "using System.Net.Http" 

//Load System.Net.Http
string name1 = "System.Net.Http,Version=4.0.0.0," + "Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a";
Assembly a1 = Assembly.Load(name1);

//Create HttpClient instance
Type clientType = a1.GetTypes().Where(t => t.Name.Equals("HttpClient")).Single();
object client = Activator.CreateInstance(clientType);

//Set BaseAddress on client
PropertyInfo propertyBaseAddress = clientType.GetProperties().Where(p => p.Name == "BaseAddress").Single();
Uri url = new Uri("http://api.open-notify.org/astros.json");
propertyBaseAddress.SetValue(client, url);

//Test property value
var BaseAddressValue = propertyBaseAddress.GetValue(client);

//Get HttpResponseMessage Task
var methodGetStringAsync = clientType.GetMethod("GetStringAsync", new Type[] { typeof(Uri) });
var responseTask = methodGetStringAsync.Invoke(client, new string[] { null });

//Get HttpResponseMessage result from Task
var responseType = responseTask.GetType();
PropertyInfo propResponse = responseType.GetProperties().Where(p => p.Name == "Result").Single();

var responseResult = propResponse.GetValue(responseTask);  //This is the string result


Bonus: List your loaded assemblies

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (Assembly a in assemblies)
{
     Console.WriteLine(a.GetName());
}


Output
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Net.Http is displayed here even not referenced in Visual Studio.

Friday, March 13, 2020

Strong Name Signing in .NET

Using a strong name protects your assembly against manipulation.

For example your software using a class named Class1 in ClassLibrary1 namespace.

If you compile a new dll contains ClassLibrary1.Class1 then you can use this dll instead of original one.

This is very basic example but it can be applicable in real life.

To be sure that your software is using your assembly version then you can sign your project.

Microsoft description is:
When a strong-named assembly is created, it contains the simple text name of the assembly, the version number, optional culture information, a digital signature, and the public key that corresponds to the private key used for signing.
Example here shows signing process in Visual Studio. You can use also command line tool (sn.exe).

Coding

Our solution has 2 projects, executable and a class library. Main program is using ClassLibrary1.Class1

using ClassLibrary1;
using System;

namespace strongname
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("strongname loaded");

            Class1 c = new Class1();

            Console.ReadKey();
        }
    }
}


using System;

namespace ClassLibrary1
{
    public class Class1
    {
        public Class1()
        {
            Console.WriteLine("Hello from Class1");
        }
    }
}

Sign

Right click to project in VS and select Properties. In Signing tab check "Sign the assembly" and select "New" in listbox. Enter password for your private key.


This will create a pfx (Personal Information Exchange Format) file in your project folder.

Run

strongname loaded
Hello from Class1

Recompile

If you create a new project with the same namespace, class and functions then you can use the new dll with current executable.

For test change the code and recompile dll in outside of project folder.

csc.exe /t:library /out:ClassLibrary1.dll Class1.cs
Then replace the old ClassLibrary1.dll with the new file.

Result

When you try to run your executable an error will be shown because the new dll has not signed with correct key.

C:\strongname\bin\Debug\strongname.exe

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=77d705841860f240' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at strongname.Program.Main(String[] args)

If you completely remove signing from your projects then your manipulated dll will work.

Tuesday, January 7, 2020

Asp.Net Settings for Hosting

1. Security Exception

Description: The application attempted to perform an operation not allowed by the security policy.To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request failed.

Solution:

<system.web>
   <trust level="Full" />
</system.web>

2. Publish website without roslyn

Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform "Your Web API project name"
In your publish profile settings, uncheck "Allow precompiled site to be updatable". You can find this under Settings > Precompile during publishing > configure.

Remove codedom from web.config.
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>

4. MapPath

  System.Web.Hosting.HostingEnvironment.MapPath("~/log");

4. Restrict file download

Create web.config file in the folder you want to prevent file download for a specific extension.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <security>
            <requestFiltering>
                <fileExtensions applyToWebDAV="false">
                     <add fileExtension=".txt" allowed="false" />
                </fileExtensions>
            </requestFiltering>
        </security>
  </system.webServer>
</configuration>

Thursday, December 19, 2019

AWS Lambda Functions

Create Lambda function

Go to AWS Lambda homepage and login to console.
Press "Create Function" button.
Enter function name.
Select a language (environment) from Runtime dropdown. I will use node.js 8.10.
For the first time you can create a new role for permissions. Select "Create a custom role" from Role dropdown box.
A new page will be shown. Select "Create a new IAM Role" from IMA Role dropdown and then give a name. Press "Allow" button.
This will create a new role and browser will return back to "Create function" page.
Press "Create function" button.
It will redirect you to function page.
Initially the page adds a template code which returns success code and a hello message. We will continue with this code.
 

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

2. AWS CLI to call the function

Download AWS CLI setup to your computer. For Windows download link is here. For other operating systems you can find links at the same page.
After installation go to aws cli folder and run following command to start configuration.
aws configure
We need following info.
AWS Access Key ID [None]: "Your Access Key"
AWS Secret Access Key [None]: "Your Secret Key"
Default region name [None]: 
Default output format [None]: 
To get keys go to AWS console
Click to your name and select "My Security Credentials".
On "Access keys" section click to "Create New Access Key" button to create new keys. You have to save your secret key because it will displayed only once.
Now return back to aws cli console and enter Access Key ID and Secret Access Key.
Enter region name like "us-west-2".
Enter json for default output format.
Now you can run your functions.
We need our function name as a parameter. In lambda function page copy arn.
Run aws command to run function. The lines between "{ }" is the response from our lambda function. You can see hello message inside txt file which we passed as a parameter.
aws lambda invoke --function-name arn:aws:lambda:us-west-2:123456780315:function:FirstLambda "c:\aws.txt"

{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
aws.txt file content
{"statusCode":200,"body":"\"Hello from Lambda!\""}

Friday, September 20, 2019

Upload file to Console Webapi (Owin)

Upload a file to a console based webapi host (owin).

Method 1: MultipartFormDataStreamProvider

 

[HttpPost]
public async Task PostFile()
{
 string root = AppDomain.CurrentDomain.BaseDirectory + "Uploads"; 

 var provider = new MultipartFormDataStreamProvider(root);
 await Request.Content.ReadAsMultipartAsync(provider);
 foreach (var file in provider.FileData)
 {
  var buffer = File.ReadAllBytes(file.LocalFileName);  
 }
 return new HttpResponseMessage() { Content = new StringContent("OK") };
}

Postman Post Sample

Select form-data for Body. Enter key name and select a file for the value.
POST /api/file/PostByteArrayAsync HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Length: 15143
Connection: keep-alive
cache-control: no-cache


Content-Disposition: form-data; name="file"; filename="/C:/Users/oktay/logs.txt


------WebKitFormBoundary7MA4YWxkTrZu0gW--

Method 2: ReadAsByteArrayAsync

This method requires filename in header. Add key/value for "filename".
 

[HttpPost]
public string PostFile()
{
 string fileName = Request.Headers.GetValues("filename").ElementAt(0);

 string root = AppDomain.CurrentDomain.BaseDirectory + "Uploads\\";
 var filePath = root + fileName;

 var fc = Request.Content.ReadAsByteArrayAsync().Result;
 File.WriteAllBytes(filePath, fc);

 return "uploaded";
}

Friday, July 26, 2019

SQL Server Shrink

Problem 

  • SQL Server disk usage is very high. 
  • SQL Server Management Studio is very slow.

Investigation

Windows Event log:
  • Starting Up Database
  • Could Not Allocate Space for Object Name in Database ‘DB’ Because the ‘PRIMARY’ Filegroup is Full
  • CREATE DATABASE or ALTER DATABASE failed because the resulting cumulative database size would exceed your licensed limit of 10240 MB per database.

Check

Size of database files (data and log) may be at maximum limit.

Size Limitation Database Size for Microsoft SQL Server versions
  • Microsoft SQL Server 2000 Desktop - 2 GB
  • Microsoft SQL Server 2005 Express edition has a database size limit to 4GB
  • Microsoft SQL Server 2008 Express edition has a database size limit to 4GB
  • Microsoft SQL Server 2008 R2 Express edition has a database size limit to 10GB
  • Microsoft SQL Server 2012 Express edition has a database size limit to 10GB
  • Microsoft SQL Server 2014 Express edition has a database size limit to 10GB
  • Microsoft SQL Server 2016 Express edition has a database size limit to 10GB

Solution

Shrink data file and log file.

Initial sizes:

  1. Connect SQL Server via SQL Management Studio.

  2. Find database in left pane, right click and select Tasks > Shrink > Files.


  3. Select "Log" under "File type" list. Select "Reorganize pages...". You can enter minimum MB in text box as shown next to it. I entered 1 and completed shrink.


  4. Now you may also want to shrink data file. Repeat 2nd and 3rd steps for "File type: Data".
  5. I entered 1000 and completed shrink.

File sizes after shrink: