#StackBounty: #c# #winforms #scrollable What's the use of HScroll/VScroll in ScrollableControl?

Bounty: 50

The ScrollableControl class has 2 protected boolean properties: HScroll and VScroll.

As the document says:

Gets or sets a value indicating whether the horizontal scroll bar is visible.

And

AutoScroll maintains the visibility of the scrollbars automatically. Therefore, setting the HScroll or VScroll properties to true have no effect when AutoScroll is enabled.

So I use them like this, but the scrollbar isn’t showed:

class MyScrollableControl : ScrollableControl {
    public MyScrollableControl() {
        this.AutoScroll = false;
        this.HScroll = true;
    }
}

If I use the following code, it works:

this.HorizontalScroll.Visible = true;

When I put them torgether, the scrollbar is still invisible, and the values of HScroll and HorizontalScroll.Visible keep False.

this.AutoScroll = false;
this.HScroll = true;
this.HorizontalScroll.Visible = true;

So what is the real use of HScroll and VScroll ?


Get this bounty!!!

#StackBounty: #c# #.net #quickbooks QBO/.NET SDK [Quickbooks Online] – How to remove empty invoice line item?

Bounty: 100

I have a new issue with quickbooks invoice. Upon creation of an invoice I get all items I added plus one extra line item in my invoice.

How do I filter, remove, prevent this line from appearing?

Here is what I have tried.

   //Find Item
            var itemQueryService = new QueryService<Item>(qboContextoAuth);
            Item item = itemQueryService.ExecuteIdsQuery("Select * From Item StartPosition 1 MaxResults 1").FirstOrDefault();

 int idx = 0;

            var lines = new List<Line>();

            foreach (var orderItem in orderItems)
            {

                //Line
                Line invoiceLine = new Line();
                //Line Description
                invoiceLine.Description = itemRepository.Get(i => i.ItemID == orderItem.ItemID).First().FullDescription;
                //Line Amount
                invoiceLine.Amount = orderItem.Price * orderItem.Quantity;
                invoiceLine.AmountSpecified = true;
                //Line Detail Type
                invoiceLine.DetailType = LineDetailTypeEnum.SalesItemLineDetail;
                invoiceLine.DetailTypeSpecified = true;
                //Line Sales Item Line Detail


                SalesItemLineDetail lineSalesItemLineDetail = new SalesItemLineDetail();


                //Line Sales Item Line Detail - ItemRef
                lineSalesItemLineDetail.ItemRef = new ReferenceType()
                {
                    name = itemRepository.Get(i => i.ItemID == orderItem.ItemID).First().FullDescription,
                    Value = item.Id
                };
                //Line Sales Item Line Detail - UnitPrice
                lineSalesItemLineDetail.AnyIntuitObject = orderItem.Price;//33m;
                lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;
                //Line Sales Item Line Detail - Qty
                lineSalesItemLineDetail.Qty = orderItem.Quantity;//10;
                lineSalesItemLineDetail.QtySpecified = true;
                //Line Sales Item Line Detail - TaxCodeRef
                //For US companies, this can be 'TAX' or 'NON

                /* lineSalesItemLineDetail.TaxCodeRef = new ReferenceType()
                 {
                     Value = "TAX"
                 };*/
                //Line Sales Item Line Detail - ServiceDate 
                lineSalesItemLineDetail.ServiceDate = DateTime.Now.Date;
                lineSalesItemLineDetail.ServiceDateSpecified = true;
                //Assign Sales Item Line Detail to Line Item
                invoiceLine.AnyIntuitObject = lineSalesItemLineDetail;
                //Assign Line Item to Invoice
                //invoice.Line = new Line[] { invoiceLine };
                lines.Add(invoiceLine);

                //TxnTaxDetail
                /*TxnTaxDetail txnTaxDetail = new TxnTaxDetail();
                txnTaxDetail.TxnTaxCodeRef = new ReferenceType()
                {
                    name = stateTaxCode.Name,
                    Value = stateTaxCode.Id
                };
                Line taxLine = new Line();
                taxLine.DetailType = LineDetailTypeEnum.TaxLineDetail;
                TaxLineDetail taxLineDetail = new TaxLineDetail();
                //Assigning the fist Tax Rate in this Tax Code
                taxLineDetail.TaxRateRef = stateTaxCode.SalesTaxRateList.TaxRateDetail[0].TaxRateRef;
                taxLine.AnyIntuitObject = taxLineDetail;
                txnTaxDetail.TaxLine = new Line[] { taxLine };
                invoice.TxnTaxDetail = txnTaxDetail;
                */
                idx++;
            }

Removal Code

  Item item2 = itemQueryService.ExecuteIdsQuery("Select * From Item StartPosition 2 MaxResults 1").FirstOrDefault();
        //Line Sales Item Line Detail - ItemRef
        SalesItemLineDetail lineDetail = new SalesItemLineDetail();
        Line removeLine = new Line();

        lineDetail.ItemRef = new ReferenceType()
        {
            Value = item2.Id
        };
        removeLine.AnyIntuitObject = lineDetail;

        lines.RemoveAt(1);

Related question:

Quickbooks Online Accounting – How to add multiple line items in an invoice?


Get this bounty!!!

#StackBounty: #performance #c #linked-list #console #windows Interactive console application to edit a sorted list

Bounty: 50

I am reading a book that has some difficult vocabulary and I, in order to understand the book thoroughly, decided to collect and lookup those words am not acquainted with, spend sometime learning them, and re-read the book.

I have created an interactive console application specifically for this purpose. The program’s main objectives are:

  • Open a file for reading and writing
  • Load data from file into linked list, if any, and sort them alphabetically.
  • Accept input from user, and search through the list for matches to display on screen.
  • If right key, is pressed, discard input. If Return key is pressed, save input to file, and if Escape key is pressed, cleanup and terminate program.

The key of interactivity is to show the user whether he added a word to the list or not, to avoid duplicates.

However, I have noticed that my implementation is hefty on the CPU, because when I run it, after short time, the fans become noisy, which make it hard for me to read and concentrate. Please advise on how can I optimize it and what improvements can be made.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <Windows.h>

struct G_list {
    char word[100];
    struct G_list *ptr;
};

typedef struct G_list G_list;

void add_and_sort(const char *str, G_list **head);
void free_list(G_list *head);

int cmp_at_begn(char *str, const char *substr);
void traverse_list(char *str, G_list *head);
void ClearScreen(void *hConsole);

int main(void)
{
    /* open file for reading and writing */
    const char filename[] = "Book.txt";
    FILE *fp = fopen(filename, "a+");
    if (!fp) {
        perror(filename);
        return 1;
    }

    /* ... */
    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    const size_t len = strlen(alphabet);

    /* allocate memory */
    G_list **wlist = (G_list **)malloc(sizeof(G_list *) * len);
    for (size_t i = 0; i < len; i++) {
        wlist[i] = (G_list *)malloc(sizeof(G_list));
        wlist[i]->ptr = NULL;
        wlist[i]->word[0] = 0;
    }

    /* load data from file */
    int c;
    char load[100];
    while (fgets(load, sizeof(load), fp)) {
        load[strcspn(load, "n")] = 0;
        c = *load - 'a';
        if (c < 0 || c >= len) {
            continue;
        }
        add_and_sort(load, wlist + c);
    }

    /* recieve input and display data */
    int index = 0;
    char buf[100] = { 0 };
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    while (1) {
        // if backspace, delete character and traverse list
        if (GetAsyncKeyState(VK_BACK) == -32767) {
            if (index) {
                buf[--index] = '';
                ClearScreen(hStdout);
                printf("%sn............n", buf);
                if (index) {
                    traverse_list(buf, wlist[*buf - 'a']);
                }
            }
        }
        // if right-arrow key, discard input
        else if (GetAsyncKeyState(VK_RIGHT) == -32767) {
            index = 0;
            *buf = '';
            ClearScreen(hStdout);
            continue;
        }
        // if Enter, save to file
        else if (GetAsyncKeyState(VK_RETURN) == -32767) {
            if ((*buf - 'a') < 0 || (*buf - 'a') >= len) {
                continue;
            }
            add_and_sort(buf, &wlist[*buf - 'a']);
            fprintf(fp, "%sn", buf);
            index = 0;
            *buf = '';
            ClearScreen(hStdout);
            continue;
        }
        // if escape, terminate the program
        else if (GetAsyncKeyState(VK_ESCAPE) == -32767) {
            break;
        }
        // accept alphabet-input and display matches if any
        for (short i = 'A'; i <= 'Z'; i++) {
            if (GetAsyncKeyState(i) == -32767) {
                buf[index++] = (char)(i + 32);
                buf[index] = '';
                ClearScreen(hStdout);
                printf("%sn............n", buf);
                traverse_list(buf, wlist[*buf - 'a']);
            }
        }
    }

    /* release memory */
    fclose(fp);
    for (size_t i = 0; i < len; i++) {
        free_list(wlist[i]);
    }
    free(wlist);
}

void add_and_sort(const char *str, G_list **head)
{
    /* create node */
    G_list *node = (G_list *)malloc(sizeof(G_list));

    /* initialize node members */
    strcpy(node->word, str);
    node->ptr = NULL;

    /* ... */
    if ((*head)->word[0] == '') {
        *head = node;
        return;
    }
    else {
        while (1) {
            if (strcmp(str, (*head)->word) < 0) {
                G_list *tmp = *head;
                *head = node;
                node->ptr = tmp;
                break;
            }
            else {
                head = &((*head)->ptr);
                if (!*head) {
                    *head = node;
                    (*head)->ptr = NULL;
                    break;
                }
            }
        }
    }
}

void free_list(G_list *head)
{
    G_list *tmp;
    while (head) {
        tmp = head;
        head = head->ptr;
        free(tmp);
    }
}

// compare at beginning of line
int cmp_at_begn(char *str,
    const char *substr)
{
    if (!*str || !*substr) {
        return (*str == *substr);
    }
    else {
        while (*str && *substr) {
            if (*str++ != *substr++) {
                return 0;
            }
        }
    }
    return !(*substr);
}

void ClearScreen(void *hConsole)
{
    COORD coordScreen = { 0, 0 };    // home for the cursor 
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    // Get the number of character cells in the current buffer. 
    if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
    {
        return;
    }
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    // Fill the entire screen with blanks.
    if (!FillConsoleOutputCharacter(hConsole,        // Handle to console screen buffer 
        (TCHAR) ' ',     // Character to write to the buffer
        dwConSize,       // Number of cells to write 
        coordScreen,     // Coordinates of first cell 
        &cCharsWritten))// Receive number of characters written
    {
        return;
    }
    // Get the current text attribute.
    if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
    {
        return;
    }
    // Set the buffer's attributes accordingly.
    if (!FillConsoleOutputAttribute(hConsole,         // Handle to console screen buffer 
        csbi.wAttributes, // Character attributes to use
        dwConSize,        // Number of cells to set attribute 
        coordScreen,      // Coordinates of first cell 
        &cCharsWritten)) // Receive number of characters written
    {
        return;
    }
    // Put the cursor at its home coordinates.
    SetConsoleCursorPosition(hConsole, coordScreen);
}

void traverse_list(char *str, G_list *head)
{
    int v = 0;
    while (head) {
        if (cmp_at_begn(head->word, str)) {
            puts(head->word);
            v = 1;
        }
        else {
            if (v) break;
        }
        head = head->ptr;
    }
}


Get this bounty!!!

#StackBounty: #c #http #video-streaming #bare-metal How to create a video stream from a series of bitmaps and send it over IP network?

Bounty: 250

I have a bare-metal application running on a tiny 16 bit microcontroller (ST10) with 10BASE-T Ethernet (CS8900) and a Tcp/IP implementation based upon the EasyWeb project.

The application’s main job is to control a led matrix display for public traffic passenger information. It generates display information with about about 41 fps and configurable display size of e.g. 160 × 32 pixel, 1 bit color depth (each led can be just either on or off).

Example:

enter image description here

There is a tiny webserver implemented, which provides the respective frame buffer content (equals to led matrix display content) as PNG or BMP for download. So I can receive snapshots by e.g.:

wget http://$IP/content.png

or

wget http://$IP/content.bmp

or put appropriate html code into the controller’s index.html to view that in a web browser.
I also could write html / javascript code to update that picture periodically, e.g. each second so that the user can see changes of the display content.

Now for the next step, I want to provide the display content as some kind of video stream and then put appropriate html code to my index.html or just open that “streaming URI” with e.g. vlc.

As my framebuffer bitmaps are built uncompressed, I expect a constant bitrate.

I’m not sure what’s the best way to start with this.

(1) Which video format is the most easy to generate if I already have a PNG for each frame (but I have that PNG only for a couple of milliseconds and cannot buffer it for a longer time)?

Note that my target system is very resource restricted in both memory and computing power.

(2) Which way for distribution over IP?

I already have some tcp sockets open for listening on port 80. I could stream the video over HTTP (after received) by using chunked tranfer encoding (each frame as an own chunk).
(Maybe HTTP Live Streaming doing like this?)

I’d also read about thinks like SCTP, RTP and RTSP but it looks like more work to implement this on my target. And as there is also the potential firewall drawback, I think I prefer HTTP for transport.

Please note, that the application is coded in plain C, without operating system or powerful libraries. All stuff is coded from the scratch, even the web server and PNG generation.

Edit 2017-09-14, tryout with APNG

As suggested by Nominal Animal, I gave a try with using APNG.

I’d extend my code to produce appropriate fcTL and fdAT chunks for each frame and provide that bla.apng with HTTP Content-Type image/apng.

After downloading those bla.apng it looks useful when e.g. opening in firefox or chrome (but not in
konqueror,
vlc,
dragon player,
gwenview).

Trying to stream that apng works nicely but only with firefox.
Chrome wants first to download the file completely.

So APNG might be a solution, but with the disadvantage that it currently only works with firefox.


Get this bounty!!!

#StackBounty: #performance #c #linked-list #windows Interactive console application

Bounty: 50

I am reading a book that has some difficult vocabulary and I, in order to understand the book thoroughly, decided to collect and lookup those words am not acquainted with, spend sometime learning them, and re-read the book.

I have created an interactive console application specifically for this purpose. The program’s main objectives are:

  • Open a file for reading and writing
  • Load data from file into linked list, if any, and sort them alphabetically.
  • Accept input from user, and search through the list for matches to display on screen.
  • If right key, is pressed, discard input. If Return key is pressed, save input to file, and if Escape key is pressed, cleanup and terminate program.

The key of interactivity is to show the user whether he added a word to the list or not, to avoid duplicates.

However, I have noticed that my implementation is hefty on the CPU, because when I run it, after short time, the fans become noisy, which make it hard for me to read and concentrate. Please advise on how can I optimize it and what improvements can be made.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <Windows.h>

struct G_list {
    char word[100];
    struct G_list *ptr;
};

typedef struct G_list G_list;

void add_and_sort(const char *str, G_list **head);
void free_list(G_list *head);

int cmp_at_begn(char *str, const char *substr);
void traverse_list(char *str, G_list *head);
void ClearScreen(void *hConsole);

int main(void)
{
    /* open file for reading and writing */
    const char filename[] = "Book.txt";
    FILE *fp = fopen(filename, "a+");
    if (!fp) {
        perror(filename);
        return 1;
    }

    /* ... */
    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    const size_t len = strlen(alphabet);

    /* allocate memory */
    G_list **wlist = (G_list **)malloc(sizeof(G_list *) * len);
    for (size_t i = 0; i < len; i++) {
        wlist[i] = (G_list *)malloc(sizeof(G_list));
        wlist[i]->ptr = NULL;
        wlist[i]->word[0] = 0;
    }

    /* load data from file */
    int c;
    char load[100];
    while (fgets(load, sizeof(load), fp)) {
        load[strcspn(load, "n")] = 0;
        c = *load - 'a';
        if (c < 0 || c >= len) {
            continue;
        }
        add_and_sort(load, wlist + c);
    }

    /* recieve input and display data */
    int index = 0;
    char buf[100] = { 0 };
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    while (1) {
        // if backspace, delete character and traverse list
        if (GetAsyncKeyState(VK_BACK) == -32767) {
            if (index) {
                buf[--index] = '';
                ClearScreen(hStdout);
                printf("%sn............n", buf);
                if (index) {
                    traverse_list(buf, wlist[*buf - 'a']);
                }
            }
        }
        // if right-arrow key, discard input
        else if (GetAsyncKeyState(VK_RIGHT) == -32767) {
            index = 0;
            *buf = '';
            ClearScreen(hStdout);
            continue;
        }
        // if Enter, save to file
        else if (GetAsyncKeyState(VK_RETURN) == -32767) {
            if ((*buf - 'a') < 0 || (*buf - 'a') >= len) {
                continue;
            }
            add_and_sort(buf, &wlist[*buf - 'a']);
            fprintf(fp, "%sn", buf);
            index = 0;
            *buf = '';
            ClearScreen(hStdout);
            continue;
        }
        // if escape, terminate the program
        else if (GetAsyncKeyState(VK_ESCAPE) == -32767) {
            break;
        }
        // accept alphabet-input and display matches if any
        for (short i = 'A'; i <= 'Z'; i++) {
            if (GetAsyncKeyState(i) == -32767) {
                buf[index++] = (char)(i + 32);
                buf[index] = '';
                ClearScreen(hStdout);
                printf("%sn............n", buf);
                traverse_list(buf, wlist[*buf - 'a']);
            }
        }
    }

    /* release memory */
    fclose(fp);
    for (size_t i = 0; i < len; i++) {
        free_list(wlist[i]);
    }
    free(wlist);
}

void add_and_sort(const char *str, G_list **head)
{
    /* create node */
    G_list *node = (G_list *)malloc(sizeof(G_list));

    /* initialize node members */
    strcpy(node->word, str);
    node->ptr = NULL;

    /* ... */
    if ((*head)->word[0] == '') {
        *head = node;
        return;
    }
    else {
        while (1) {
            if (strcmp(str, (*head)->word) < 0) {
                G_list *tmp = *head;
                *head = node;
                node->ptr = tmp;
                break;
            }
            else {
                head = &((*head)->ptr);
                if (!*head) {
                    *head = node;
                    (*head)->ptr = NULL;
                    break;
                }
            }
        }
    }
}

void free_list(G_list *head)
{
    G_list *tmp;
    while (head) {
        tmp = head;
        head = head->ptr;
        free(tmp);
    }
}

// compare at beginning of line
int cmp_at_begn(char *str,
    const char *substr)
{
    if (!*str || !*substr) {
        return (*str == *substr);
    }
    else {
        while (*str && *substr) {
            if (*str++ != *substr++) {
                return 0;
            }
        }
    }
    return !(*substr);
}

void ClearScreen(void *hConsole)
{
    COORD coordScreen = { 0, 0 };    // home for the cursor 
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    // Get the number of character cells in the current buffer. 
    if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
    {
        return;
    }
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    // Fill the entire screen with blanks.
    if (!FillConsoleOutputCharacter(hConsole,        // Handle to console screen buffer 
        (TCHAR) ' ',     // Character to write to the buffer
        dwConSize,       // Number of cells to write 
        coordScreen,     // Coordinates of first cell 
        &cCharsWritten))// Receive number of characters written
    {
        return;
    }
    // Get the current text attribute.
    if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
    {
        return;
    }
    // Set the buffer's attributes accordingly.
    if (!FillConsoleOutputAttribute(hConsole,         // Handle to console screen buffer 
        csbi.wAttributes, // Character attributes to use
        dwConSize,        // Number of cells to set attribute 
        coordScreen,      // Coordinates of first cell 
        &cCharsWritten)) // Receive number of characters written
    {
        return;
    }
    // Put the cursor at its home coordinates.
    SetConsoleCursorPosition(hConsole, coordScreen);
}

void traverse_list(char *str, G_list *head)
{
    int v = 0;
    while (head) {
        if (cmp_at_begn(head->word, str)) {
            puts(head->word);
            v = 1;
        }
        else {
            if (v) break;
        }
        head = head->ptr;
    }
}


Get this bounty!!!

#StackBounty: #c# #validation #asp.net-mvc #exception Validation for a CQS system that throws an exception

Bounty: 50

I’ve been reading that exceptions should only be for something “exceptional” and not used to control the flow of a program. However, with a CQS implementation, this seems impossible unless I start hacking up the implementation to deal with it. I wanted to show how I implemented this to see if this is something really bad or not. I’m using decorators so commands cannot return anything (other than Task for async), so a ValidationResult is out of the question. Let me know!

This example will use ASP.NET MVC

Controller: (api)

[Route(ApiConstants.ROOT_API_URL_VERSION_1 + "DigimonWorld2Admin/Digimon/Create")]
public class CreateCommandController : MetalKidApiControllerBase
{
    private readonly IMediator _mediator;

    public CreateCommandController(IMediator mediator) => _mediator = mediator;

    [HttpPost]
    public async Task Post([FromBody]CreateCommand command) => 
        await _mediator.ExecuteAsync(command);
}

CommandExceptionDecorator is first in the chain:

public class CommandHandlerExceptionDecorator<TCommand> : ICommandHandler<TCommand> where TCommand : ICommand
{
    private readonly ICommandHandler<TCommand> _commandHandler;
    private readonly ILogger _logger;
    private readonly IUserContext _userContext;

    public CommandHandlerExceptionDecorator(ICommandHandler<TCommand> commandHandler, ILogger logger,
        IUserContext userContext)
    {
        Guard.IsNotNull(commandHandler, nameof(commandHandler));
        Guard.IsNotNull(logger, nameof(logger));

        _commandHandler = commandHandler;
        _logger = logger;
        _userContext = userContext;
    }

    public async Task ExecuteAsync(TCommand command, CancellationToken token = default(CancellationToken))
    {
        try
        {
            await _commandHandler.ExecuteAsync(command, token).ConfigureAwait(false);
        }
        catch (BrokenRuleException)
        {
            throw; // Let caller catch this directly
        }
        catch (UserFriendlyException ex)
        {
            await _logger.LogAsync(new LogEntry(LogTypeEnum.Error, _userContext,
                "Friendly exception with command: " + typeof(TCommand).FullName, ex, command)).ConfigureAwait(false);
            throw; // Let caller catch this directly
        }
        catch (NoPermissionException ex)
        {
            await _logger.LogAsync(new LogEntry(LogTypeEnum.Error, _userContext,
                "No Permission exception with command: " + typeof(TCommand).FullName, ex, command)).ConfigureAwait(false);
            throw new UserFriendlyException(CommonResource.Error_NoPermission); // Rethrow with a specific message
        }
        catch (ConcurrencyException ex)
        {
            await _logger.LogAsync(new LogEntry(LogTypeEnum.Error, _userContext,
                "Concurrency error with command: " + typeof(TCommand).FullName, ex, command)).ConfigureAwait(false);
            throw new UserFriendlyException(CommonResource.Error_Concurrency); // Rethrow with a specific message
        }
        catch (Exception ex)
        {
            await _logger.LogAsync(new LogEntry(LogTypeEnum.Error, _userContext,
                "Error with command: " + typeof(TCommand).FullName, ex, command)).ConfigureAwait(false);
            throw new UserFriendlyException(CommonResource.Error_Generic); // Rethrow with a specific message
        }
    }
}

Validation Decorator:

public class CommandHandlerValidatorDecorator<TCommand> : ICommandHandler<TCommand> where TCommand : ICommand
{
    private readonly ICommandHandler<TCommand> _commandHandler;
    private readonly IEnumerable<ICommandValidator<TCommand>> _validators;

    public CommandHandlerValidatorDecorator(
        ICommandHandler<TCommand> commandHandler,
        ICollection<ICommandValidator<TCommand>> validators)
    {
        Guard.IsNotNull(commandHandler, nameof(commandHandler));
        Guard.IsNotNull(validators, nameof(validators));

        _commandHandler = commandHandler;
        _validators = validators;
    }

    public async Task ExecuteAsync(TCommand command, CancellationToken token = default(CancellationToken))
    {
        var brokenRules = (await Task.WhenAll(_validators.AsParallel()
                .Select(a => a.ValidateCommandAsync(command, token)))
            .ConfigureAwait(false)).SelectMany(a => a).ToList();

        if (brokenRules.Any())
        {
            throw new BrokenRuleException(brokenRules);
        }

        await _commandHandler.ExecuteAsync(command, token).ConfigureAwait(false);
    }
}

Other decorators exist but aren’t important for this question.

Example of a Command Handler Validator: (Each rule is run on its own thread under the covers)

public class CreateCommandValidator : CommandValidatorBase<CreateCommand>
{
    private readonly IDigimonWorld2ContextFactory _contextFactory;

    public CreateCommandValidator(IDigimonWorld2ContextFactory contextFactory)
    {
        _contextFactory = contextFactory;
    }

    protected override void CreateRules(CancellationToken token = default(CancellationToken))
    {
        AddRule(() => Validate.If(string.IsNullOrEmpty(Command.Name))
            ?.CreateRequiredBrokenRule(DigimonResources.Digipedia_CreateCommnad_Name, nameof(Command.Name)));
        AddRule(() => Validate.If(Command.DigimonTypeId == 0)
            ?.CreateRequiredBrokenRule(DigimonResources.Digipedia_CreateCommnad_DigimonTypeId,
                nameof(Command.DigimonTypeId)));
        AddRule(() => Validate.If(Command.RankId == 0)
            ?.CreateRequiredBrokenRule(DigimonResources.Digipedia_CreateCommnad_RankId, nameof(Command.RankId)));

        AddRule(async () =>
        {
            using (var context = _contextFactory.Create(false))
            {
                return Validate.If(
                        !string.IsNullOrEmpty(Command.Name) &&
                        await context.Digimons
                            .AnyAsync(a => a.Name == Command.Name, token)
                            .ConfigureAwait(false))
                    ?.CreateAlreadyInUseBrokenRule(DigimonResources.Digipedia_CreateCommnad_Name, Command.Name,
                        nameof(Command.Name));
            }
        });
    }
}

Actual Command Handler:

public class CreateCommandValidatorHandler : ICommandHandler<CreateCommand>
{
    private const int ExpectedChangesCount = 1;

    private readonly IDigimonWorld2ContextFactory _contextFactory;
    private readonly IMapper<CreateCommand, DigimonEntity> _mapper;

    public CreateCommandValidatorHandler(
        IDigimonWorld2ContextFactory contextFactory, 
        IMapper<CreateCommand, DigimonEntity> mapper)
    {
        _contextFactory = contextFactory;
        _mapper = mapper;
    }

    public async Task ExecuteAsync(CreateCommand command, CancellationToken token = default(CancellationToken))
    {
        using (var context = _contextFactory.Create())
        {
            var entity = _mapper.Map(command);
            context.Digimons.Add(entity);
            await context.SaveChangesAsync(ExpectedChangesCount, token).ConfigureAwait(false);
        }
    }
}

When an exception is thrown for broken validation rules, the normal flow is broken. Each step assumes that the previous step succeeded. This makes the code very clean as we don’t care about failures during the actual implementation. All commands end up going through this same logic so we only have to write it once. At the very top of MVC, I handle the BrokenRuleException like this: (I do AJAX calls, not full page posts)

internal static class ErrorConfiguration
{
    public static void Configure(
        IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IConfigurationRoot configuration)
    {
        loggerFactory.AddConsole(configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                var error = context.Features.Get<IExceptionHandlerFeature>()?.Error;

                context.Response.StatusCode = GetErrorStatus(error);
                context.Response.ContentType = "application/json";

                var message = GetErrorData(error);
                await context.Response.WriteAsync(message, Encoding.UTF8);
            });
        });
    }

    private static string GetErrorData(Exception ex)
    {
        if (ex is BrokenRuleException brokenRules)
        {
            return JsonConvert.SerializeObject(new
            {
                BrokenRules = brokenRules.BrokenRules
            });
        }

        if (ex is UserFriendlyException userFriendly)
        {
            return JsonConvert.SerializeObject(new
            {
                Message = userFriendly.Message
            });
        }

        return JsonConvert.SerializeObject(new
        {
            Message = MetalKid.Common.CommonResource.Error_Generic
        });
    }

    private static int GetErrorStatus(Exception ex)
    {
        if (ex is BrokenRuleException || ex is UserFriendlyException)
        {
            return (int)HttpStatusCode.BadRequest;
        }
        return (int)HttpStatusCode.InternalServerError;
    }
}

BrokenRule class has the message and a relation field. This relation allows the UI to tie a message to something on the page (i.e. a , or form label, etc.) to display the message in the correct location

public class BrokenRule
{      
    public string RuleMessage { get; set; }
    public string Relation { get; set; }

    public BrokenRule() { }

    public BrokenRule(string ruleMessage, string relation = "")
    {
        Guard.IsNotNullOrWhiteSpace(ruleMessage, nameof(ruleMessage));

        RuleMessage = ruleMessage;
        Relation = relation;
    }
}

If I don’t do it like this, the controller would have to call a validation class first, look at the results, and then return it as a 400 with the correct response. Most likely, you would have to call a helper class to convert it correctly. However, then the controller would end up looking like this or something similar:

[Route(ApiConstants.ROOT_API_URL_VERSION_1 + "DigimonWorld2Admin/Digimon/Create")]
public class CreateCommandController : MetalKidApiControllerBase
{
    private readonly IMediator _mediator;
    private readonly ICreateCommandValidator _validator;

    public CreateCommandController(IMediator mediator, ICreateCommandValidator validator) 
    {
        _mediator = mediator;
        _validator = validator
    }

    [HttpPost]
    public async Task Post([FromBody]CreateCommand command)
    {
        var validationResult = _validator.Validate(command);
        if (validationResult.Errors.Count > 0) 
        {
           return ValidationHelper.Response(validationResult);
        }
        return await _mediator.ExecuteAsync(command);
    }
}

This validation check would need to be repeated on every single command. If it was forgotten, there would be big consequences. With the exception style, the code remains compact and developers don’t have to worry about adding that redundant code everytime.

I would really love to get everyones feedback. Thanks!

* Edit *
Another possible option would be to have another “mediator” for the response itself that could run validation directly first and then continue on:

[Route(ApiConstants.ROOT_API_URL_VERSION_1 + "DigimonWorld2Admin/Digimon/Create")]
public class CreateCommandController : MetalKidApiControllerBase
{
    private readonly IResultMediator _mediator;

    public CreateCommandController(IResultMediator mediator) => _mediator = mediator;

    [HttpPost]
    public async Task<IHttpAction> Post([FromBody]CreateCommand command) => 
        await _mediator.ExecuteAsync(command);
}

Inside this new ResultMediator class, it would look up the CommandValidator and if there were any validation errors it would simply return BadRequest(new { BrokenRules = brokenRules}) and call it good. Is this something that each UI will just have to create and handle? If there is an exception during this call, however, we’d have to handle that in this mediator directly. Thoughts?


Get this bounty!!!

#StackBounty: #c# #asp.net #xml #usps Passing USPS eVSCertifyRequest error as MasterMID not found in database

Bounty: 50

Using eVSCertifyRequest to create the USPS label and I am passing parameter as follows:

https://secure.shippingapis.com/ShippingAPI.dll?API=eVSCertify&XML=<eVSCertifyRequest USERID="XXXXXXXX">
<Option>1</Option>
<Revision></Revision>
<ImageParameters>
    <ImageParameter>4X6LABEL</ImageParameter>
</ImageParameters>
<FromName>Mitesh Jain</FromName>
<FromFirm>Mitesh Jain</FromFirm>
<FromAddress1>52 NORMANDY RD</FromAddress1>
<FromAddress2>QWE</FromAddress2>
<FromCity>MARLTON</FromCity>
<FromState>NJ</FromState>
<FromZip5>08053</FromZip5>
<FromZip4>0805</FromZip4>
<FromPhone>1234567890</FromPhone>
<POZipCode></POZipCode>
<AllowNonCleansedOriginAddr>false</AllowNonCleansedOriginAddr>
<ToName>JRC,LLC</ToName>
<ToFirm>JRC,LLC</ToFirm>
<ToAddress1>110 South 8th Street</ToAddress1>
<ToAddress2>Suite 104</ToAddress2>
<ToCity>Philadelphia</ToCity>
<ToState>PA</ToState>
<ToZip5>15001</ToZip5>
<ToZip4>1500</ToZip4>
<ToPhone>0123456789</ToPhone>
<POBox></POBox>
<AllowNonCleansedDestAddr>false</AllowNonCleansedDestAddr>
<WeightInOunces>1</WeightInOunces>
<ServiceType>PRIORITY</ServiceType>
<Container>FLAT RATE ENVELOPE</Container>
<Width></Width>
<Length></Length>
<Height></Height>
<Machinable></Machinable>
<ProcessingCategory></ProcessingCategory>
<PriceOptions></PriceOptions>
<InsuredAmount></InsuredAmount>
<AddressServiceRequested></AddressServiceRequested>
<ExpressMailOptions>
    <DeliveryOption></DeliveryOption>
    <WaiverOfSignature></WaiverOfSignature>
</ExpressMailOptions>
<ShipDate></ShipDate>
<CustomerRefNo></CustomerRefNo>
<ExtraServices>
    <ExtraService></ExtraService>
</ExtraServices>
<HoldForPickup></HoldForPickup>
<OpenDistribute></OpenDistribute>
<PermitNumber></PermitNumber>
<PermitZIPCode></PermitZIPCode>
<PermitHolderName></PermitHolderName>
<CRID></CRID>
<MID>847654321</MID>
<SenderName></SenderName>
<SenderEMail></SenderEMail>
<RecipientName></RecipientName>
<RecipientEMail></RecipientEMail>
<ReceiptOption></ReceiptOption>
<ImageType>PDF</ImageType>
<HoldForManifest>Y</HoldForManifest>
<NineDigitRoutingZip>false</NineDigitRoutingZip>
<Content>
    <ContentType>HAZMAT</ContentType>
</Content>

But I am getting error as below

 <?xml version="1.0" encoding="UTF-8"?>
<Error>
<Number>-2147221102</Number>  
<Source>clsEVS:GetAPIRegistrationInfo</Source>
<Description>MasterMID not found in database.  </Description>

What else I need to pass or what I am missing in this? I had taken the reference from path https://www.usps.com/business/web-tools-apis/evs-label-api.htm#_Toc487532684.


Get this bounty!!!

#StackBounty: #c# #expression #filtering #dynamic-programming Polymorphic Model Bindable Expression Trees Resolver

Bounty: 50

I’m trying to figure out a way to structure my data so that it is model bindable. My Issue is that I have to create a query filter which can represent multiple expressions in data.

For example:

x => (x.someProperty == true && x.someOtherProperty == false) || x.UserId == 2

x => (x.someProperty && x.anotherProperty) || (x.userId == 3 && x.userIsActive)

I’ve created this structure which represents all of the expressions fine my Issue is how can I make this so it’s property Model Bindable

public enum FilterCondition
{
    Equals,
}

public enum ExpressionCombine
{
    And = 0,
    Or
}

public interface IFilterResolver<T>
{
    Expression<Func<T, bool>> ResolveExpression();
}

public class QueryTreeNode<T> : IFilterResolver<T>
{
    public string PropertyName { get; set; }
    public FilterCondition FilterCondition { get; set; }
    public string Value { get; set; }
    public bool isNegated { get; set; }

    public Expression<Func<T, bool>> ResolveExpression()
    {
        return this.BuildSimpleFilter();
    }
}

//TODO: rename this class
public class QueryTreeBranch<T> : IFilterResolver<T>
{
    public QueryTreeBranch(IFilterResolver<T> left, IFilterResolver<T> right, ExpressionCombine combinor)
    {
        this.Left = left;
        this.Right = right;
        this.Combinor = combinor;
    }

    public IFilterResolver<T> Left { get; set; }
    public IFilterResolver<T> Right { get; set; }
    public ExpressionCombine Combinor { get; set; }

    public Expression<Func<T, bool>> ResolveExpression()
    {
        var leftExpression = Left.ResolveExpression();
        var rightExpression = Right.ResolveExpression();

        return leftExpression.Combine(rightExpression, Combinor);
    }
}

My left an right members just need to be able to be resolved to an IResolvable, but the model binder only binds to concrete types. I know I can write a custom model binder but I’d prefer to just have a structure that works.

I know I can pass json as a solutions but as a requirement I can’t

Is there a way I can refine this structure so that it can still represent all simple expression while being Model Bindable? or is there an easy way I can apply this structure so that it works with the model binder?

EDIT
Just in case anyone is wondering, my expression builder has a whitelist of member expressions that it it filters on. The dynamic filtering work I just looking for a way to bind this structure naturally so that my Controller can take in a QueryTreeBranch or take in a structure which accurately represent the same data.

public class FilterController
{
     [HttpGet]
     [ReadRoute("")]
     public Entity[]  GetList(QueryTreeBranch<Entity> queryRoot)
     {
         //queryRoot no bind :/
     }
}

Currently the IFilterResolver has 2 implementations which need to be chosen dynamically based on the data passed

I’m looking for a solution closest to out of the box WebApi / MVC framework. Preferable one that does NOT require me to adapt the input to another structure in order generate my expression


Get this bounty!!!

#StackBounty: #c# #wpf How to compile WPF program with command line?

Bounty: 50

I need to compile simple WPF application, which I have written using Visual Studio, with the command line C# compiler (i.e csc.exe).

Problem is the error CS0103 — the compiler says that there is no InitializeComponent() method in my program. But that’s wrong, because I add System.Xaml.dll. Does anybody know how to solve this?


Get this bounty!!!

#StackBounty: #windows #linux #c++ #ide #game-development Which IDE to use for C++ game development on windows and on Linux?

Bounty: 50

I am a java developer and I want to learn game programming in C++. I have been using Eclipse, Intellij(recently) for java development.

Please suggest which IDE is best for C++ development.
There are many out there like Visual Studio, CLion, Eclipse, etc.
Which one to use (Not based on ease of use but the best/rich for long run) ?

Also as I have heard that Linux environment is best to C++ developers, please suggest the best IDE for windows and Linux both.

Thanks !


Get this bounty!!!