How use bit/bit-operator to control object state? - delphi

I want to create light object data-package to pass between client and server applications.
It is a so simple task, that I can control with only 1 byte, so
each bit in a byte will have a different meaning,
Using only the bit
0 = False
1 = True
Itens I need now:
1 - Loaded from database
2 - Persisted
3 - Changed
4 - Marked to Delete
5 -
6 -
7 - Null Value
8 - Read Only
1) How do I use bit operators in Delphi to check each bit value?
2) How do I set the bit Values?
Solution
After all help, Ill use the next Set
TStateType = (
stLoaded = 0, // loaded from persistance
stNative = 2, // value loaded and converted to native type
stPersisted = 3, // saved
stChanged = 4, // object or member changed
stToDelete = 5, // marked to delete
stReadOnly = 6, // read only object, will not allow changes
stNull = 7 // value is null
);
TState = Set of TStateType;
And for stream -> persistance, this will be the record to be used:
TDataPackage = record
Data: TBytes;
TypeInfo: TMetaInfo;
State: Byte;
Instance: TBuffer;
end;
Thank you guys, for all the answers and comments.

I'd really use a set for this. However, I see you really want a byte. Use sets everywhere then typecast to a byte in the end.
This solution will require much less typing, has support for standard delphi operators and really carries no performance penalty as Barry Kelly has pointed out.
procedure Test;
type
TSetValues = (
TSetValue1 = 0,
TSetValue2 = 1,
TSetValue4 = 2,
TSetValue8 = 3,
TSetValue16 = 4,
TSetValue32 = 5,
TSetValue64 = 6,
TSetValue128 = 7
);
TMySet = set of TSetValues;
var
myValue: byte;
mySet: TMySet;
begin
mySet := [TSetValue2, TSetValue16, TSetValue128];
myValue := byte(mySet);
ShowMessage(IntToStr(myValue)); // <-- shows 146
end;

I would use a set for this:
type
TMyDatum = (mdLoaded, mdPersisted, mdChanged, mdMarkedToDelete, ...);
TMyData = set of TMyDatum;
var
Foo: TMyData;
begin
Foo := [mdLoaded, mdChanged];
if (mdPersisted in Foo) then ...
These are implemented as integers, so you can pass them easily. And I find the code much, much more readable than bitwise operators.

This page describes Delphi operators, including bitwise operators.
It sounds like you need to use the and operator. For example:
const
LOADED_FROM_DATABASE = 1;
PERSISTED = 2;
CHANGED = 4;
// etc...
//...
if (bitFlags and LOADED_FROM_DATABASE) <> 0 then
begin
// handle LOADED FROM DATABASE
end;
if (bitFlags and PERSISTED) <> 0 then
begin
// handle PERSISTED
end;
// etc...
In order to set the flags, you can use OR:
bitFlags := LOADED_FROM_DATABASE or PERSISTED or CHANGED;

Related

I can not correctly translate the code from MSDN to Delphi. Section DirectShow Step 6. Add Support for COM

Please help me to translate the code. I don't know C++ well, but I know Delphi syntax well. I want to translate code from MSDN:
Step 6. Add Support for COM.
static WCHAR g_wszName[] = L"My RLE Encoder";
CFactoryTemplate g_Templates[] =
{
{
g_wszName,
&CLSID_RLEFilter,
CRleFilter::CreateInstance,
NULL,
NULL
}
};
and
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);
I realized that the first line is a variable. But when translated, it does not work. Error:
This is a string and you defined it as WCHAR.
Next comes the description of the structure, but I do not know such a form.
The last line is also a variable, but it has a / and two values.
In general, I kind of understood the meaning, but do not understand how to write it.
The code roughly translates to Delphi as follows:
const
g_wszName: PWideChar = 'My RLE Encoder';
var
g_Templates: array[0..0] of CFactoryTemplate;
...
g_Templates[0].m_Name := g_wszName;
g_Templates[0].m_ClsID := #CLSID_RLEFilter;
g_Templates[0].m_lpfnNew := #CRleFilter.CreateInstance;
g_Templates[0].m_lpfnInit := nil;
g_Templates[0].m_pAMovieSetup_Filter := nil;
and
var
g_cTemplates: Integer;
...
//g_cTemplates := SizeOf(g_Templates) div SizeOf(g_Templates[0]);
g_cTemplates := Length(g_Templates);

What is the correct way to copy the dictionary?

I need to check if there has been a change in a certain part of the application and therefore I make "copies" of the data after loading them and then compare them. One part of the comparison function involves checking keys in dictionaries like lDict1.Keys.EqualsTo(lDict2.Keys).
Although the dictionaries do not rely on the order of the elements, I didn't realize that even if I fill two dictionaries with the same data, they won't be created the same and the order of elements may change, so the previous function does not work properly because it relies on the elements order that may not match when using any of the following methods. (I'm not sure why)
var
lDict1, lDict2 : IDictionary<Integer, TObject>;
lKey : Integer;
begin
lDict1 := TCollections.CreateDictionary<Integer, TObject>;
lDict1.Add(5, nil); // Keys.First = 5, Keys.Last = 5
lDict1.Add(6, nil); // Keys.First = 5, Keys.Last = 6
lDict2 := TCollections.CreateDictionary<Integer, TObject>;
lDict2.AddRange(lDict1); // Keys.First = 6, Keys.Last = 5
lDict2.Clear;
for lKey in lDict1.Keys do // Keys.First = 6, Keys.Last = 5
lDict2.Add(lKey, nil);
end;
Is there any way to make an exact copy of the dictionary so I can compare them? One way to work around this problem is to create my own comparison function, but I'd like to avoid that.
function ContainsSameValues<T>(AEnumerable1, AEnumerable2: IEnumerable<T>): Boolean;
var
lValue : T;
begin
Result := AEnumerable1.Count = AEnumerable2.Count;
if Result then
begin
for lValue in AEnumerable1 do
begin
Result := AEnumerable2.Contains(lValue);
if not Result then
Exit;
end;
end;
end;
usage
ContainsSameValues<Integer>(lDict1.Keys, lDict2.Keys);
Checking for equality of a unordered dictionaries is a relatively simple algorithm. I will outline it here. Suppose we have two dictionaries, A and B.
Compare the number of elements of A and B. If this differs, the dictionaries are not equal.
Enumerate each key/value pair k,v in A. If k is not in B, or B[k] is not equal to v, then the dictionaries are not equal.
If you reach the end of the enumeration, then you know that the dictionaries are equal.

Proper implementation of OpenPrinter2 with PRINTER_OPTION_NO_CACHE

I'm modifying some existing code which uses OpenPrinter to instead use OpenPrinter2. It contains one more parameter PPRINTER_OPTIONS which in Delphi is encapsulated as a TPrinterOptions, defined like so:
_PRINTER_OPTIONSW = record
cbSize: Cardinal;
dwFlags: DWORD;
end;
I'm having trouble understanding how to use this struct to encapsulate the flag PRINTER_OPTION_NO_CACHE, and I can't even find that constant in any of the existing VCL/RTL.
var
PD: TPrinterDefaults;
PO: TPrinterOptions;
begin
PO.dwFlags:= ???
if OpenPrinter2(ADevice, #FPrinterHandle, #PD, #PO) then begin
...
I'm not having much luck searching for Delphi implementation of either OpenPrinter2 or TPrinterOptions. How do I make PRINTER_OPTION_NO_CACHE work?
EDIT
Is this correct?
const
PRINTER_OPTION_NO_CACHE = 0;
PRINTER_OPTION_CACHE = 1;
PRINTER_OPTION_CLIENT_CHANGE = 2;
...
PO.dwFlags:= PRINTER_OPTION_NO_CACHE;
The MSDN docs say this:
typedef enum tagPRINTER_OPTION_FLAGS {
PRINTER_OPTION_NO_CACHE,
PRINTER_OPTION_CACHE,
PRINTER_OPTION_CLIENT_CHANGE
} PRINTER_OPTION_FLAGS;
A C enum, as declared here, is really just an int. The first enum value is 0, the next 1, and so on.
But the header file tells a different story, contradicting the documentation. The header file says:
typedef enum _PRINTER_OPTION_FLAGS
{
PRINTER_OPTION_NO_CACHE = 1 << 0,
PRINTER_OPTION_CACHE = 1 << 1,
PRINTER_OPTION_CLIENT_CHANGE = 1 << 2,
PRINTER_OPTION_NO_CLIENT_DATA = 1 << 3,
} PRINTER_OPTION_FLAGS;
So translate to Pascal like this.
const
PRINTER_OPTION_NO_CACHE = 1;
PRINTER_OPTION_CACHE = 2;
PRINTER_OPTION_CLIENT_CHANGE = 4;
PRINTER_OPTION_NO_CLIENT_DATA = 8;
Populate the record like this:
var
Options: TPrinterOptions;
....
Options.cbSize := SizeOf(Options);
Options.dwFlags := PRINTER_OPTION_NO_CACHE;

code ole automation excel error

This code gives me error
ex.Cells [3, 2]. HorizontalAlignment: = xlright;
ex.Cells [row, 1]. NumberFormat: = 'dd / mm / yy, #';
how can I fix this?
thanks
Based on your other questions, you're using late binding (using a Variant) instead of early binding (using the VCL TExcelApplication and other components). This means that the specific types like xlRight are not defined, because you haven't used the type library import that provides them. You'll have to define them yourself:
var
...
NewAlign: OleVariant;
const
xlBottom = $FFFFEFF5;
xlLeft = $FFFFEFDD;
xlRight = $FFFFEFC8;
xlTop = $FFFFEFC0;
xlHAlignCenter = $FFFFEFF4;
xlHAlignCenterAcrossSelection = $00000007;
xlHAlignDistributed = $FFFFEFEB;
xlHAlignFill = $00000005;
xlHAlignGeneral = $00000001;
xlHAlignJustify = $FFFFEFDE;
xlHAlignLeft = $FFFFEFDD;
xlHAlignRight = $FFFFEFC8;
begin
// XLApp is the instance of Excel you set up from your previous
// questions
XLApp.Workbooks[1].Worksheets[1].Range['C1:C5'].NumberFormat := 'dd/mm/yy';
NewAlign := xlHAlignRight;
XLApp.Workbooks[1].Worksheets[1].Range['C1:C5'].HorizontalAlignment := NewAlign;
end;
Assigning dd/mm/yy # makes no sense, because it's either a date format dd/mm/yy or text #, but not both.

Enums vs Const vs Class Const in Delphi programming

I have an integer field in a ClientDataSet and I need to compare to some values, something like this:
I can use const
const
mvValue1 = 1;
mvValue2 = 2;
if ClientDataSet_Field.AsInteger = mvValue1 then
or enums
TMyValues = (mvValue1 = 1, mvValue2 = 2);
if ClientDataSet_Field.AsInteger = Integer(mvValue1) then
or class const
TMyValue = class
const
Value1 = 1;
Value2 = 2;
end;
if ClientDataSet_Field.AsInteger = TMyValues.Value1 then
I like the class const approach but it seems that is not the delphi way, So I want to know what do you think
Declaration:
type
TMyValues = class
type TMyEnum = (myValue1, myValue2, myValue3, myValue4);
const MyStrVals: array [TMyEnum] of string =
('One', 'Two', 'Three', 'Four');
const MyIntVals: array [TMyEnum] of integer =
(1, 2, 3, 4);
end;
Usage:
if ClientDataSet_Field.AsInteger = TMyValues.MyIntVals[myValue1] then
A cast would generally be my last choice.
I wouldn't say that class consts are not the Delphi way. It's just they have been introduced to Delphi quite recently, and a lot of books and articles you'll find on the internet were written before their introduction, and thus you won't see them widely used. Many Delphi developers (I'd say the majority) will have started using Delphi before they were made available, and thus they're not the first thing that one thinks about.
One thing to consider is backwards compatibility - class constants are relatively new to Delphi so if your code has to be sharable with previous versions than they are out.
I typically use enumerated types, with the difference from yours is that my first enumeration is usually an 'undefined' item to represent NULL or 0 in an int field.
TmyValues = (myvUndefined, myvDescription1, myvDescription2)
if ClientDataSet_Field.AsInteger = Ord(myvDescription1) then...
To use a little bit of Jim McKeeth's answer - if you need to display to the user a text viewable version, or if you need to convert their selected text into the enumerated type, then an array comes in handy in conjuction with the type:
const MYVALS: array [TmyValues ] of string = ('', 'Description1', 'Description2');
You can then have utility functions to set/get the enumerated type to/from a string:
Function MyValString(const pMyVal:TmyValues):string;
begin
result := MYVALS[Ord(pMyVal)];
end;
Function StringToMyVal(const pMyVal:String):TMyValues;
var i:Integer;
begin
result := myvUndefined;
for i := Low(MYVALS) to High(MYVALS) do
begin
if SameText(pMyVal, MYVALS[i]) then
begin
result := TMyValues(i);
break;
end;
end;
end;
Continuing on... you can have scatter routine to set a combo/list box:
Procedure SetList(const DestList:TStrings);
begin
DestList.Clear;
for i := Low(MYVALS) to High(MYVALS) do
begin
DestList.Insert(MYVALS[i]);
end;
end;
In code: SetList(Combo1.Items) or SetList(ListBox1.Items)..
Then if you are seeing the pattern here... useful utility functions surrounding your enumeration, then you add everything to it's own class and put this class into it's own unit named MyValueEnumeration or whaterver. You end up with all the code surrounding this enumeration in one place and keep adding the utility functions as you need them. If you keep the unit clean - don't mix in other unrelated functionality then it will stay very handy for all projects related to that enumeration.
You'll see more patterns as time goes and you use the same functionality over and over again and you'll build a better mousetrap again.
When using constants I recommend assigning the type when the data type is a numeric float.
Delphi and other languages will not always evaluate values correctly if the types do not match...
TMyValue = class
const
// will not compare correctly to float values.
Value1 = 1; // true constant can be used to supply any data type value
Value2 = 2; // but should only be compared to similar data type
// will not compare correctly to a single or double.
Value3 = 3.3; // default is extended in debugger
// will not compare correctly to a single or extended.
Value1d : double = Value1; // 1.0
Value2d : double = Value2; // 2.0
end;
Compared float values in if () and while () statements should be compared to values of the same data type, so it is best to define a temporary or global variable of the float type used for any comparison statements (=<>).
When compared to the same float data type this format is more reliable for comparison operators in any programming language, not just in Delphi, but in any programming language where the defined float types vary from variable to constant.
Once you assign a type, Delphi will not allow you to use the variable to feed another constant, so true constants are good to feed any related data type, but not for comparison in loops and if statements, unless they are assigned and compared to integer values.
***Note: Casting a value from one float type to another may alter the stored value from what you entered for comparison purposes, so verify with a unit test that loops when doing this.
It is unfortunate that Delphi doesn't allow an enumeration format like...
TController : Integer = (NoController = 0, ncpod = 1, nextwave = 2);
or enforce the type name for access to the enumeration values.
or allow a class constant to be used as a parameter default in a call like...
function getControllerName( Controller : TController = TController.NoController) : string;
However, a more guarded approach that provides both types of access would be to place the enumeration inside a class.
TController = class
//const
//NoController : Integer = 1;
//ncpod : Integer = 2;
//nextwave : Integer = 3;
type
Option = (NoController = 0, ncpod = 1, nextwave = 2);
public
Class function Name( Controller : Option = NoController) : string; static;
end;
implementation
class function TController.Name( Controller : Option = NoController) : string;
begin
Result := 'CNC';
if (Controller = Option.nextwave) then
Result := Result + ' Piranha'
else if (Controller = Option.ncpod) then
Result := Result + ' Shark';
Result := Result + ' Control Panel';
end;
This approach will effectively isolate the values, provide the static approach and allow access to the values using a for () loop.
The access to the values from a floating function would be like this...
using TControllerUnit;
function getName( Controller : TController.Option = TController.Option.NoController) : string;
implementation
function getName( Controller : TController.Option = TController.Option.NoController) : string;
begin
Result := 'CNC';
if (Controller = TController.Option.nextwave) then
Result := Result + ' Piranha'
else if (Controller = TController.Option.ncpod) then
Result := Result + ' Shark';
Result := Result + ' Control Panel';
end;
so many options! :-) i prefer enums and routinely use them as you describe. one of the parts i like is that i can use them with a "for" loop. i do use class constants as well but prefer enums (even private enums) depending on what i'm trying to achieve.
TMyType=class
private const // d2007 & later i think
iMaxItems=1; // d2007 & later i think
private type // d2007 & later i think
TMyValues = (mvValue1 = 1, mvValue2 = 2); // d2007 & later i think
private
public
end;
An option you haven't thought of is to use a lookup table in the database and then you can check against the string in the database.
eg.
Select value, Description from tbl_values inner join tbl_lookup_values where tbl_values.Value = tbl_lookup_values.value
if ClientDataSet_Field.AsString = 'ValueIwant' then

Resources