#StackBounty: #c# #.net #visual-studio #visual-studio-2015 #visual-studio-2017 How to allow for multiple types deployment?

Bounty: 500

In my search for the meaning of life, I stumbled upon a blog post that mentioned that your deployment strategy is not your architecture, it is simply an implementation detail, and as such we need to design for allowing different deployment patterns, whether you want to deploy your system to 1 node or multi-node, or another type of structure.

Do the latest versions of Visual Studio provide some kind of flexibility (besides azure) to be able to deploy services in a variety of strategies?

For example, let’s say I have a solution

    Acme Solution
    --Acme Startup Proj
    --Acme Service A.csproj
    --Acme Service B.csproj
    --Acme Service C.csproj

I want to be able to deploy this entire solution as 1 solution, or I would like to be able to deploy 3 separate binaries, one for each microservice.

AcmeServiceA.exe
AcmeServiceb.exe
AcmeServicec.exe

What does Visual Studio give you in terms of flexibility of deployment configuration?


Get this bounty!!!

#StackBounty: #library #software-development #c++ #c #memory-management slab/arena memory management/allocation library

Bounty: 50

I’m interested in a library for managing allocation and de-allocation of memory within an abstract slab. That is, a library which doesn’t malloc(), but initially gets a contiguous range of addresses (maybe I’ve malloc()ed for it, or maybe it’s managing space on some remote device), but takes allocation and de-allocation requests and returns regions within the slab.

Requirements:

  • Gratis
  • Free and Open Source
  • Has some documentation
  • The allocation mechanism cannot use the slab/arena to store any state (counters, pointers etc.); it can use the default allocator (e.g. malloc()/new) or a second slab for that.

Preferences:

  • C or C++ bindings
  • Written in modern C++
  • Supports prospective/time-based allocation (“I need X bytes between abstract time point t_1 and abstract time point t_2”; this allows for over-allocation over all time units, as long as there is no over-allocation at an individual time unit.)
  • Supports specifying alignment requirements
  • Supports resizing better than allocating a new segment and deallocating the old one
  • Actively maintained


Get this bounty!!!

#StackBounty: #c# #android #visual-studio #mono #xamarin.android Pinging IP or HOSTNAME with Xamarin not working as expected

Bounty: 50

I’m trying this code and it returns always TTL Expired even if the ip or hostname is unreachable , timeout or any other diferrent problem :

using System.Net.NetworkInformation;

PingReply Reply = await pingo.SendPingAsync(text_ip.Text, 4000, buffer, options);
        Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
        switch (Reply.Status)
        {
            case IPStatus.Success:

                Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
                break;

            case IPStatus.TimedOut:

                Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
                break;

            case IPStatus.TimeExceeded:

                Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
                break;

            case IPStatus.DestinationHostUnreachable:


               Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
                break;

            case IPStatus.DestinationNetworkUnreachable:

                Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
                break;

            case IPStatus.DestinationUnreachable:

                Toast.MakeText(Activity, Reply.Status.ToString(), ToastLength.Long).Show();
                break;
        }

I found a bug at https://github.com/mono/mono/blob/master/mcs/class/System/System.Net.NetworkInformation/Ping.cs (line 339)
That calls the system ping command and checks the exit code:

if (!ping.WaitForExit (timeout) || (ping.HasExited && ping.ExitCode == 2))
    status = IPStatus.TimedOut;
else if (ping.ExitCode == 0)
    status = IPStatus.Success;
else if (ping.ExitCode == 1)
    status = IPStatus.TtlExpired;

So TTL expired is set when there was no timeout, no error or success (exit code 2 or 0), and the exit code was 1.

If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.

So a return value of 1 indicates that no response has been received (for various reasons) and the Mono implementation sets the TTL expired status in this case. I would expect that a time out status would be returned in such cases. But it seems that the timeout detection of the Mono implementation is not triggered here (e.g. because the ping command exits upon on it’s own timeout before).

So there is other possible solutions:

To treat a TTL expired as host not alive (but this will then ignore real TTL expired detections)

Anyway can somebody show another way to do this with a example of Ping request with exec from Java.Lang.Process and to get from the reply time, info , statistics or other values ?


Get this bounty!!!

#StackBounty: #c# #.net #asp.net-mvc #asp.net-mvc-4 User.Identity.Name returns guid

Bounty: 50

For some (obscure) reason my MVC 4 application returns a guid when I run:

var name = User.Identity.Name;

I have also tested this in a brand new MVC 4 application and this is new behavior to me. When I look up the documentation on IIdentity it states (as I remembered) that Identity.Name should

Gets the name of the current user.

Why is it returning a guid in my case?

From the web.config

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

More relevant information:
The application is also deployed on another machine, talking to the same database. We use the value of “User.Identity.Name” in that database and when it’s not there for a user (new user) we add a new user with that guid.

Now, what is strange: when you switch applications (from localhost to the one deployed on T) you need to log in again. The User.Identity.Name will then be set to a new guid.

(with the starter default application we don’t talk to the DB of course, but the same thing happens; User.Identity.Name returns a guid)


Get this bounty!!!

#StackBounty: #c# #thread-safety Throttling class

Bounty: 100

The idea of this class is that several threads are sending data over a network and each thread are sharing the same instance of this class and before sending N bytes over the network each thread is calling ThrottledWait(n).

My worry is that each thread might run on different core and get different value for DateTime.UtcNow.Ticks. I am not 100% sure it’s thread-safe.

Also calling Thread.Sleep(ts) might sleep for longer than asked for and might cause traffic to not be smooth because of aliasing so we might want to do a thread.sleep() for less than the calculated amount and waste the remaining time checking DateTime.UtcNow.Ticks in a busy loop.

public class Throttler
{
    // Use this constant as average rate to disable throttling
    public const long NoLimit = -1;
    // Number of consumed tokens
    private long _consumedTokens;
    // timestamp of last refill time
    private long _lastRefillTime;
    // ticks per period
    private long _periodTicks;

    private double _averageRate;

    public long BurstSize
    {
        get;
        set;
    }

    public long AverageRate
    {
        get { return (long)_averageRate; }
        set { _averageRate = value; }
    }

    public TimeSpan Period
    {
        get
        {
            return new TimeSpan(_periodTicks);
        }
        set
        {
            _periodTicks = value.Ticks;
        }
    }
    public Throttler()
    {
        BurstSize = 1;
        AverageRate = NoLimit;
        Period = TimeSpan.FromSeconds(1);
    }

    /// <summary>
    /// Create a Throttler
    /// ex: To throttle to 1024 byte per seconds with burst of 200 byte use
    /// new Throttler(1024,TimeSpan.FromSeconds(1), 200);
    /// </summary>
    /// <param name="averageRate">The number of tokens to add to the bucket every interval. </param>
    /// <param name="period">Timespan of on interval.</param>
    /// <param name="burstSize"></param>
    public Throttler(long averageRate, TimeSpan period, long burstSize = 1)
    {
        BurstSize = burstSize;
        AverageRate = averageRate;
        Period = period;
    }

    public bool TryThrottledWait(long amount)
    {
        if (BurstSize <= 0 || _averageRate <= 0)
        { // Instead of throwing exception, we just let all the traffic go
            return true;
        }
        RefillToken();
        return ConsumeToken(amount);
    }

    private bool ConsumeToken(long amount)
    {
        while (true)
        {
            long currentLevel = System.Threading.Volatile.Read(ref _consumedTokens);
            if (currentLevel + amount > BurstSize)
            {
                return false; // not enough space for amount token
            }

            if (Interlocked.CompareExchange(ref _consumedTokens, currentLevel + amount, currentLevel) == currentLevel)
            {
                return true;
            }
        }
    }

    public void ThrottledWait(long amount)
    {
        while (true) {
            if (TryThrottledWait(amount))
            {
                break;
            }

            long refillTime = System.Threading.Volatile.Read(ref _lastRefillTime);
            long nextRefillTime = (long) (refillTime + (_periodTicks / _averageRate));
            long currentTimeTicks = DateTime.UtcNow.Ticks;
            long sleepTicks = Math.Max(nextRefillTime - currentTimeTicks, 0);
            TimeSpan ts = new TimeSpan(sleepTicks);
            Thread.Sleep(ts);
        } 
    }

    /// <summary>
    /// Compute elapsed time using DateTime.UtcNow.Ticks and refil token using _periodTicks and _averageRate
    /// </summary>
    private void RefillToken()
    {
        long currentTimeTicks = DateTime.UtcNow.Ticks;
        // Last refill time in  ticks unit
        long refillTime = System.Threading.Volatile.Read(ref _lastRefillTime);
        // Time delta in ticks unit
        long TicksDelta = currentTimeTicks - refillTime;
        long newTokens = (long)(TicksDelta * _averageRate / _periodTicks);
        if (newTokens > 0)
        {
            long newRefillTime = refillTime == 0
                ? currentTimeTicks
                : refillTime + (long)(newTokens * _periodTicks / _averageRate);

            if (Interlocked.CompareExchange(ref _lastRefillTime, newRefillTime, refillTime) == refillTime)
            {
                // Loop until we succeed in refilling "newTokens" tokens
                while (true)
                {
                    long currentLevel = System.Threading.Volatile.Read(ref _consumedTokens);
                    long adjustedLevel = (long)Math.Min(currentLevel, BurstSize); // In case burstSize decreased
                    long newLevel = (long) Math.Max(0, adjustedLevel - newTokens);
                    if (Interlocked.CompareExchange(ref _consumedTokens, newLevel, currentLevel) == currentLevel)
                    {
                        return;
                    }
                }
            }
        }
    }
}


Get this bounty!!!

#StackBounty: #c #function #cross-platform Check if a system implements a function

Bounty: 50

I’m creating a cross-system application. It uses, for example, the function itoa, which is implemented on some systems but not all. If I simply provide my own itoa implementation:

header.h:115:13: error: conflicting types for 'itoa'
 extern void itoa(int, char[]);

In file included from header.h:2:0,
                 from file.c:2:0,
c:pathtomingwincludestdlib.h:631:40: note: previous declaration of 'itoa' was here
 _CRTIMP __cdecl __MINGW_NOTHROW  char* itoa (int, char*, int);

I know I can check if macros are predefined and define them if not:

#ifndef _SOME_MACRO
#define _SOME_MACRO 45
#endif

Is there a way to check if a C function is pre-implemented, and if not, implement it? Or to simply un-implement a function?


Get this bounty!!!

#StackBounty: #c# #entity-framework #entity-framework-6 Entity Framework 6 custom many-to-many child with implicit insert and delete

Bounty: 50

I have parent object (LoanApplication) with a child (LoanApplicationQualificationTypes) that is a custom many-to-many table. The reason I have a custom is that it has two audit columns that need to be populated (ModifiedBy, ModifiedDate).

To get the children that were added or removed from the child collection to be persisted in the database correctly, I had to explicitly handle.

Below is the code (simplified by removing other properties that were germane to the question).

Parent (part of many-to-many):

[Serializable]
[Table("LoanApplication")]
public class LoanApplication : BaseDomainModelWithId, ILoanApplication
{
    [Key]
    [Column("LoanApplicationId")]
    public override int? Id { get; set; }

    [ForeignKey("LoanApplicationId")]
    public virtual ICollection<LoanApplicationQualificationTypes> LoanApplicationQualificationTypes { get; set; }

    IReadOnlyCollection<ILoanApplicationQualificationTypes> ILoanApplication.LoanApplicationQualificationTypes
    {
        get
        {
            var loanApplicationQualificationTypes = new List<ILoanApplicationQualificationTypes>();

            if (LoanApplicationQualificationTypes == null) return loanApplicationQualificationTypes;

            loanApplicationQualificationTypes.AddRange(LoanApplicationQualificationTypes);

            return loanApplicationQualificationTypes.AsReadOnly();
        }
        set
        {
            foreach (var item in value)
            {
                LoanApplicationQualificationTypes.Add((LoanApplicationQualificationTypes)item);
            }
        }
    }

    public LoanApplication() : base()
    {
        LoanApplicationQualificationTypes = new List<LoanApplicationQualificationTypes>();
    }

}

public interface ILoanApplication : IDomainModel, ILoanApplicationBase, IKeyIntId
{
    IReadOnlyCollection<ILoanApplicationQualificationTypes> LoanApplicationQualificationTypes { get; set; }
}

Object part of many-to-many:

[Serializable]
[Table("QualificationType")]
public class QualificationType : IQualificationType
{
    [Key]
    [Column("QualificationTypeId")]
    public override int? Id { get; set; }

    [Required]
    public string TypeName { get; set; }

    [Required]
    public bool IsActive { get; set; }

    public virtual string ModifiedBy { get; set; }

    public virtual DateTimeOffset? ModifiedDate { get; set; }

    public QualificationType() : { }
}

Custom Many-to-Many:

[Serializable]
[Table("LoanApplicationQualificationTypes")]
public class LoanApplicationQualificationTypes : ILoanApplicationQualificationTypes
{
    [Key]
    [Column(Order = 1)]
    public int? LoanApplicationId { get; set; }

    [ForeignKey("LoanApplicationId")]
    public virtual LoanApplication LoanApplication { get; set; }

    ILoanApplication ILoanApplicationQualificationTypes.LoanApplication
    {
        get
        {
            return this.LoanApplication;
        }
        set
        {
            this.LoanApplication = (LoanApplication)value;
        }
    }

    [Required]
    [Key]
    [Column(Order = 2)]
    public int QualificationTypeId { get; set; }

    [ForeignKey("QualificationTypeId")]
    public virtual QualificationType QualificationType { get; set; }

    IQualificationType ILoanApplicationQualificationTypes.QualificationType
    {
        get
        {
            return this.QualificationType;
        }
        set
        {
            this.QualificationType = (QualificationType)value;
        }
    }

    public virtual string ModifiedBy { get; set; }

    public virtual DateTimeOffset? ModifiedDate { get; set; }

    public LoanApplicationQualificationTypes() { }
}

Update method in LoanApplication Repository:

public bool Update(ILoanApplication entity)
{
    using (var db = new MainContext())
    {
        entity.ModifiedDate = DateTime.UtcNow;
        entity.ModifiedBy  = UserOrProcessName;

        // Add / Remove LoanApplicationQualificationTypes and populate audit columns
        if (entity.LoanApplicationQualificationTypes?.Count > 0)
        {
            var existingItems = db.LoanApplicationQualificationTypes.Where(q => q.LoanApplicationId == entity.Id.Value).ToList();
            var newItems = entity.LoanApplicationQualificationTypes.Where(q => existingItems.All(e => e.QualificationTypeId != q.QualificationTypeId));
            var deletedItems = existingItems.Where(q => entity.LoanApplicationQualificationTypes.All(e => e.QualificationTypeId != q.QualificationTypeId));

            foreach (var newItem in newItems)
            {
                newItem.ModifiedBy = UserOrProcessName;
                newItem.ModifiedDate = DateTime.UtcNow;

                db.LoanApplicationQualificationTypes.Add((LoanApplicationQualificationTypes)newItem);
            }

            foreach (var deletedItem in deletedItems)
            {
                db.LoanApplicationQualificationTypes.Remove((LoanApplicationQualificationTypes)deletedItem);
            }

            // Need to clear to avoid duplicate objects
            ((LoanApplication)entity).LoanApplicationQualificationTypes.Clear();
        }

        db.Entry(entity).State = EntityState.Modified;
        db.SaveChanges();
    }

    return true;
}

Is there a way implement the Update without the explicitly handling adds/updates?


Get this bounty!!!

#StackBounty: #c# #image #bitmap #gpgpu #cudafy.net C# Bitmap GetPixel(), SetPixel() in GPU

Bounty: 50

I am using Cudafy as c# wrapper
I need to get colour info InputBitmap0.GetPixel(x, y) of a bitmap and make an new bitmap for output .

I need the following work to be done in GPU.

IN CPU

OutputBitmap.SetPixel(object_point_x, object_point_y, InputBitmap0.GetPixel(x, y));

In short:

How to GetPixel() for each pixel point of the input Bitmap, SetPixel() for each pixel point of the outputbitmap Bitmap in GPU.


Get this bounty!!!

#StackBounty: #c++ #performance #sorting #quick-sort Fast quicksort implementation

Bounty: 50

Just for learning purposes i wrote an implementation of quicksort algorithm.

I made some modifications to the algorithm to make it faster, that are:

  • two pivots setted to the boundaries of the middle partition(<, =, >), to avoid having two other variables counting the equal elements

  • the partitioning method checks first the presence of less(in left partition) or greater(in right partition) than pivot elements, if both are present, rather than moving the pivot twice, it just swaps them; if not behaves normally.

I benchmarked it a bit and compared the performance to std::sort; my algorithm, with random elements is faster than the STD one when there are more than 10000000, otherwise, with less elements std::sort is faster by some milliseconds(see below for actual benchmark results)

I would prefer some performance-related tips rather than design ones.

#include <algorithm>

template<class iterator>
void quickSort(iterator begin, iterator end)
{
    if (end - begin > 1)
    {
        auto lpivot = begin + (end - begin) / 2;
        auto rpivot = lpivot;

        auto pValue = *lpivot;

        auto left_it = lpivot - 1;
        auto right_it = rpivot + 1;

        auto lValue = *left_it;
        auto rValue = *right_it;

        bool isGreater = false;
        bool isLess = false;

        while (left_it != begin-1 || right_it != end)
        {
            if (lValue >= pValue)
            {
                if (lValue == pValue)
                {
                    lpivot--;
                    std::iter_swap(lpivot, left_it);
                }
                else
                    isGreater = true;
            }

            if (rValue <= pValue)
            {
                if (rValue == pValue)
                {
                    rpivot++;
                    std::iter_swap(rpivot, right_it);
                }
                else
                    isLess = true;
            }
            if (isGreater && isLess)
            {
                std::iter_swap(left_it, right_it);
            }
            else if (isGreater)
            {
                if (left_it != lpivot - 1)
                    std::iter_swap(left_it, lpivot - 1);
                std::iter_swap(rpivot - 1, lpivot - 1);
                std::iter_swap(rpivot, rpivot - 1);
                lpivot--;
                rpivot--;
            }
            else if (isLess)
            {
                if (right_it != rpivot + 1)
                    std::iter_swap(right_it, rpivot + 1);
                std::iter_swap(lpivot + 1, rpivot + 1);
                std::iter_swap(lpivot, lpivot + 1);
                lpivot++;
                rpivot++;
            }

            if (left_it != begin - 1)
                left_it--;
            if (right_it != end)
                right_it++;

            lValue = *left_it;
            rValue = *right_it;

            isGreater = false;
            isLess = false;
        }

        quickSort(begin, lpivot);
        quickSort(rpivot + 1, end);
    }
}

My algorithm benchmark

1000000  random integers --------> 80 ms
2000000  random integers --------> 165 ms
3000000  random integers --------> 247 ms
10000000 random integers --------> 780 ms

1000000  binary random integers -> 4 ms
2000000  binary random integers -> 9 ms
3000000  binary random integers -> 14 ms
10000000 binary random integers -> 49 ms

1000000  sorted integers --------> 19 ms
2000000  sorted integers --------> 43 ms
3000000  sorted integers --------> 65 ms
10000000 sorted integers --------> 232 ms

1000000  reversed integers ------> 17 ms
2000000  reversed integers ------> 37 ms
3000000  reversed integers ------> 60 ms
10000000 reversed integers ------> 216 ms

std::sort benchmark

1000000  random integers --------> 71 ms
2000000  random integers --------> 160 ms
3000000  random integers --------> 237 ms
10000000 random integers --------> 800 ms

1000000  binary random integers -> 4 ms
2000000  binary random integers -> 9 ms
3000000  binary random integers -> 13 ms
10000000 binary random integers -> 45 ms

1000000  sorted integers --------> 9 ms
2000000  sorted integers --------> 21 ms
3000000  sorted integers --------> 33 ms
10000000 sorted integers --------> 137 ms

1000000  reversed integers ------> 12 ms
2000000  reversed integers ------> 25 ms
3000000  reversed integers ------> 40 ms
10000000 reversed integers ------> 150 ms

bechmark code

int main()
{
    std::vector<int> values;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(0, 1000000);
    //std::uniform_int_distribution<> dist(0, 1); //just 0s and 1s array

    std::generate_n(std::back_inserter(values), 10000000, std::bind(dist, gen)); //random

    for (int i = 0; i < 10000000; i++)
    {
        //values.push_back(i);              //sorted array
        //values.push_back(10000000 - i);   //reversed array
    }

    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();

    //quickSort(values.begin(), values.end());
    //std::sort(values.begin(), values.end());

    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "sn";
    std::cout << d.count() << "msn";

    return 0;
}

(I know those arrows suck, they are there just for clarity)


Get this bounty!!!

#StackBounty: #c# #asp.net #class Class usage details from class structure

Bounty: 50

I have a question regarding the Membership and MembershipUser classes in System.Web.Security Namespace.

Both these classes are present in separate Libraries, how would someone know the usage details without going through any documentation and just by the class methods, properties etc? If I come across MembershipUser class I would know there is an Email property which I can get and set, but I wouldn’t know there exists a Membership class which has method returning user details as MembershipUser return type without somehow coming across it.

For e.g. to getting Users Email address we can create a MembershipUser object and use the GetUser() method provided by Membership class as GetUser() has the return type of Membership. Something like this.

MembershipUser user = Membership.GetUser();    
string Email = user.Email;

MembershipUser Class:

public class MembershipUser
{
  ...
  public virtual string Email { get; set; }
  ...
}

Membership Class:

public static class Membership
{
  ...
  public static MembershipUser GetUser();
  ...
}


Get this bounty!!!