Wednesday, December 22, 2021

c# - How to quickly get count of the char in string

The fastest way in c# (counts the commas here):
string s = "Added on Monday, December 20, 2021 2:19:21 PM";
int count = note.Location.Count( x => x == ',' );
Output:
2

c# - How to make generic unique list with GroupBy()

This code make unique book name list + ensures sorting of the list.
private List notes = new List();
...
List uniqueBooks = new List();

uniqueBooks = 
  notes.GroupBy( x => x.BookName ).Select( g => new Note { BookName = g.Key } ).ToList();
uniqueBooks.Sort( (x, y ) => x.BookName.CompareTo( y.BookName ) );

c# - How to convert string into datetime with mask

DateTime dt;                      
bool b = DateTime.TryParseExact( "December 20, 2021", "MMMM d, yyyy", 
                                 new System.Globalization.CultureInfo("en-US"), 
                                 DateTimeStyles.None, out dt );
if ( b ) Console.WriteLine( dt.Year );
Output:
2021
if you have some problem with conversion, try reversal order at first for checking (=>compare if your string is same as output here):
Console.WriteLine( 
DateTime.Now.ToString( "MMMM d, yyyy", new System.Globalization.CultureInfo("en-US") ) );

Thursday, December 16, 2021

D365 - How to prevent warning "BPERRORLABELISTEXT"

A very quick way is to change the quotation marks to apostrophes.
info( "xxx" ) -> info( 'xxx' );
The solution for this warning:

Tuesday, December 14, 2021

D365 - How to solve warning "[BPUnusedStrFmtArgument]:The placeholder '%1' to strFmt is not used in the format string."

Old migrated code from AX 2012:
warning( strFmt( "@cieb:cieb4", _sParamName ) );
shows this warning (in label is this value "Attention - parameter %1 not found."): BP Rule: [BPUnusedStrFmtArgument]:The placeholder '%1' to strFmt is not used in the format string.

 For this warning removing add literalStr() for label string validation.
warning( strFmt( literalStr("@cieb:cieb4"), _sParamName ) );

Thursday, November 18, 2021

JAVASCRIPT - How to sort an array

// ancending order
    
var numbers = [ 10, 12, 5, 7.5, 7 ];
numbers.sort( ( a, b ) => a - b );
numbers.forEach( item => {
  document.write( item + "
" ); }); document.write( "
" ); // descending order numbers.sort( ( a, b ) => b - a ); numbers.forEach( item => { document.write( item + "
" ); });
Output:
5
7
7.5
10
12

12
10
7.5
7
5

Tuesday, November 9, 2021

JAVASCRIPT - How to split string into parts

var s = "This;is;a;text";
var vars = s.split( ";" );
vars.forEach( element => {
  document.write( element + "
" ); } );
Output:
This
is
a
text

Friday, November 5, 2021

JAVASCRIPT - How to make an action 5 seconds after page loading

This code in HEAD section:
<script>
setTimeout( LoadingProc, 5000 );
    
function LoadingProc() {
  alert( "5 seconds gone -> loading procedure." );
}
</script>

Thursday, November 4, 2021

JAVASCRIPT - How to work with classes and instances

Base class:
class Shape {
   
  desc = "";

  constructor( _desc ) {
    this.desc = _desc;
  }

  get2Desc() {
    return this.desc + this.desc;
  }

}
Instance of class and calling class method:
b.addEventListener( 'click', function () {    
      
  const myShape = new Shape( "this is a desc" );
  console.log( myShape.get2Desc() );
  
}
Output:
this is a descthis is a desc

Wednesday, November 3, 2021

HTML - How to make a different color for blank textbox

<style>
  .validated:invalid {
    background: #FAC3C9;
  }

  .validated:valid {
    background: #BDF0A8;
   }
</style>

<form action="action.php">
  <input required name="name1" class="validated" type="text" />
</form>

JAVASCRIPT - getElementById() vs querySelector()

Different methods for same task - find the item by its ID.
var progressBar = document.getElementById( "progress" );
var progressBar = document.querySelector( "#progress" );
var progressBar = document.querySelector( "[id=progress]" );

Tuesday, November 2, 2021

HTML - Some new HTML5 input fields

<div class="form" width="100px">
  <input name="e1" type="date" />
  <input name="e2" type="color" />
  <input name="e3" type="datetime-local" />
  <input name="e4" type="email" />
  <input name="e5" type="month" />
  <input name="e6" type="week" />
  <input name="e7" type="file" />
</div>
Output:

Monday, September 6, 2021

.NET - How to install pre-release tool through terminal

Specify --version parameter.
dotnet tool install -g dotnet-ef --version 6.0.0-preview.7.21378.4
Output:

Monday, June 21, 2021

AX - How to disable AOS validation for table update

ValidateWrite() causes in this case dialog, this is how to disable its calling.
AssetTable assetTable;
    
new SkipAOSValidationPermission().assert();
    
ttsBegin;
       
while
  select forUpdate * from assetTable
  where
  ( assetTable.AssetId == "13487" ) || (  assetTable.AssetId == "13488" )
  {        
         
    assetTable.AcquisitionDate_W = str2Date( "1/6/2021", 123 );
    assetTable.update();        
            
  }

ttsCommit;
  
CodeAccessPermission::revertAssert();

Friday, June 18, 2021

DELPHI - How to open file in Windows Explorer (default opening)

Shellapi unit.
ShellExecute( Handle,
              'OPEN',
              PChar('explorer.exe'),
              PChar('/select, "' + path + '"'),
              nil,
              SW_NORMAL
             ) ;

Thursday, May 27, 2021

C# - How parse double from string with specific char for decimal delimiter

If in your culture is used comma char (",") as decimal delimiter, it could appears problem, when double stored in string is delimited with classic decimal point ("."). 

 In this situation you must specify that decimal point as used delimiter. 

 So, if you have this string value "135.009995"; for right parsing you must define this code:
var currentCulture = System.Globalization.CultureInfo.InstalledUICulture;
var numberFormat = (System.Globalization.NumberFormatInfo) currentCulture.NumberFormat.Clone(); 
numberFormat.NumberDecimalSeparator = ".";

double value = 0;
bool b = Double.TryParse ( values[1], System.Globalization.NumberStyles.Any, 
                           numberFormat, out value ); 
if ( b ) el.Open = value;
Now, value contains good double value:

Wednesday, March 17, 2021

C# - How to draw image with Gamma or Threshold effect

var rectDest = new Rectangle( 0, 0, this.m_bitmap_source.Width, this.m_bitmap_source.Height );
using ( var graphics = Graphics.FromImage( this.m_bitmap_dest ) ) using ( var attr = new ImageAttributes() ) { attr.SetGamma( 0.2f ); graphics.DrawImage( this.m_bitmap_source, rectDest, 0, 0, this.m_bitmap_source.Width, this.m_bitmap_source.Height, GraphicsUnit.Pixel, attr ); }
You can use Threshold effect too (replace row with Gamma):
attr.SetThreshold( 0.4f );

Friday, March 5, 2021

C# - How to initialize List items in new statement

One possibility:
image.Normalize( new List() { new Rectangle( 100, 100, 300, 100 ) }  );
Another possibility with setting accessible properties by name:
image.Normalize( new List()
{ 
  new Rectangle() { X=100, Y=100, Width=300, Height=100 }, 
  new Rectangle() { X=200, Y=250, Width=200, Height=50 }
}  
);

Monday, March 1, 2021

C# - How to check installed .NET SDK

With this command tool dotnet.exe you can list for example installed .NET SDK.
Tip: If you want make .NET 5 app, create .NET CORE x project and then you can change it into .NET 5 (Feb 2021).

Friday, January 29, 2021

office (vba) - How to load data from text file into excel

If you have this text file with two columns, first with key, second with value:
osc;value
476;56
113;102
272;32.5
This VBA macro code enables to load data, check key comparing with first A column, if key is equal (exactly, if starts with key), then fill value into column R.
Sub Import()
  
  Dim file As String
  Dim counter As Integer
  Dim arr() As String
  Dim key As String
  Dim rngFound As Range
  Dim sheet As Worksheet
  Dim cell As Object
  
  file = Application.GetOpenFilename("Data files (*.txt),*.txt", Title:="Select file")
  
  If file = "False" Then Exit Sub
  
  ' Open file for reading
  
  Set sheet = ActiveSheet
  counter = 1
  
  Open file For Input As #1
  Do Until EOF(1)
    Line Input #1, textline
    
    ' Header - omit it
    If counter <> 1 Then
    
        arr = Split(textline, ";")
                
        ' Find row key value
        For Each cell In sheet.UsedRange.Rows
          
          key = sheet.Cells(cell.Row, "A").Value
                    
          If key <> "" Then
            If key Like arr(0) + "*" Then                
                
                sheet.Cells(cell.Row, "R") = arr(1)
                
            End If
          End If
                    
        Next cell
       
        ' MsgBox (arr(0) + "=" + arr(1))
    End If
        
    counter = counter + 1
  Loop
  Close #1
  
  MsgBox ("Hotovo")
  
End Sub
Output:

Tuesday, January 26, 2021

AX - How to set conditionally grid font type to bold

..on DataSource override displayOption() method:
public void displayOption(Common _record, FormRowDisplayOption _options)
{
    DM_ProductivityDuplicate dm_productivityDuplicate1;
    real iPercent;

    dm_productivityDuplicate1 = _record;

    if ( dm_productivityDuplicate1.cieb_duplicate == NoYes::Yes ) _options.fontBold( true );

    super( _record, _options );
}