Linux HowTo: Running C# files out of Google Drive

Original Source Link

I like to be able to code on both my laptop and desktop (both with Win 10), therefore I have Google Drive to sync my files between the two. My first issue was that the user folder on both computers was different, but I’ve changed them so they’d effectively have the same path via the method in this post.

However, now the issue I’m having is that my C# files keep giving me an “access is denied” error when trying to run them through Visual Studio:

Error : DEP0700 : Registration of the app failed. error 0x80070005: Opening file from location: AppxManifest.xml failed with error: Access is denied.
. (0x80070005) App1

I’ve tried saving them to my documents folder to which they ran with no problems, so I tried reinstalling Google Drive, but with no change. Also, just to note, I made a new project to test after each change.

I was having the same issue as you but I managed to resolve this. The error you have is a logical result of the NTFS rights on your hard disk.

When installing Google Drive, the drive has been setup to only be managed by the user with the email address you provided. So, technically, the system itself has by no means access to your drive. Only you, having that email, can access it.

We can resolve your problem by adding “system” as a folder administrator of your Google Drive.

  1. Go to your drive folder. Right-click and select properties:

    enter image description here

  2. Go to the security tab:

    enter image description here

    1. Add the system as a user:

    enter image description here

    1. Set its rights to all:

    enter image description here

So, this should have resolved your problem.

Be sure to do this while your visual studio is closed, so no files from the drive can be altered during this process.

Google Drive is not appropriate for storing or syncing code.You should use version control for storing and syncing code. SVN and Git are both good at this, but Git is far more common these days and you can use Git with Github for free. It allows you to sync between two computers easily, but far, more importantly, it allows you to version your code which is absolutely essential when it comes to building software.

Sign up for Github or some other Git service and store a clone of your code there. That will mean that your code is always available wherever you are, and every line will be versioned.

Tagged : / / / /

Making Game: Running C# files out of Google Drive

Original Source Link

I like to be able to code on both my laptop and desktop (both with Win 10), therefore I have Google Drive to sync my files between the two. My first issue was that the user folder on both computers was different, but I’ve changed them so they’d effectively have the same path via the method in this post.

However, now the issue I’m having is that my C# files keep giving me an “access is denied” error when trying to run them through Visual Studio:

Error : DEP0700 : Registration of the app failed. error 0x80070005: Opening file from location: AppxManifest.xml failed with error: Access is denied.
. (0x80070005) App1

I’ve tried saving them to my documents folder to which they ran with no problems, so I tried reinstalling Google Drive, but with no change. Also, just to note, I made a new project to test after each change.

I was having the same issue as you but I managed to resolve this. The error you have is a logical result of the NTFS rights on your hard disk.

When installing Google Drive, the drive has been setup to only be managed by the user with the email address you provided. So, technically, the system itself has by no means access to your drive. Only you, having that email, can access it.

We can resolve your problem by adding “system” as a folder administrator of your Google Drive.

  1. Go to your drive folder. Right-click and select properties:

    enter image description here

  2. Go to the security tab:

    enter image description here

    1. Add the system as a user:

    enter image description here

    1. Set its rights to all:

    enter image description here

So, this should have resolved your problem.

Be sure to do this while your visual studio is closed, so no files from the drive can be altered during this process.

Google Drive is not appropriate for storing or syncing code.You should use version control for storing and syncing code. SVN and Git are both good at this, but Git is far more common these days and you can use Git with Github for free. It allows you to sync between two computers easily, but far, more importantly, it allows you to version your code which is absolutely essential when it comes to building software.

Sign up for Github or some other Git service and store a clone of your code there. That will mean that your code is always available wherever you are, and every line will be versioned.

Tagged : / / / /

Code Bug Fix: Problem when socket_setup call fcntl(sock, F_SETFD, FD_CLOEXEC)

Original Source Link

I try to make pgbouncer in windows

They have usual library (libusual) for work with ip-sokets.

When pgbouncer tune socket, it calls socket_setup from usual library

socket_setup call
res = fcntl(sock, F_SETFD, FD_CLOEXEC);
and res is -1 now.

How can I fix one?

My build system is mingw64 from msys.

Just for someone who find this page.

Problem occurred because the usual library in some (not in all) places use int instead SOCKET which is int* and has a size more than size of int on a 64-bit platform.

Tagged : / / /

Code Bug Fix: Azure App Service with User-assigned identity: retrieve clientId in the app?

Original Source Link

I am running an Azure App Service with one User-assigned identity (and no system-managed identity):
enter image description here

Is there a way inside the app (i.e. my custom code) to retrieve the clientId of the identity? Or do I need to set that in a app setting to be available inside the app?

Question comes from the fact that I want to use this identity to authenticate using an AzureCredential and it needs the clientId.

Or is the better way to use MSI and set the app setting AzureServicesAuthConnectionString?

Looking at environment variables in an App Service with a User assigned Managed Identity, there is nothing that contains the id.

So you should set the id as an App Setting on the app, and use it.
I definitely recommend that you use AzureCredential as it is the newer one.
The older AzureServiceTokenProvider would not give you any advantage over it anyway.

Tagged : / / /

Code Bug Fix: Calculate normals cylinder OpenTK

Original Source Link

I drew a cylinder in OpenTK C#. But faced with the problem of calculating the normal for it.

Drawing is done by approximating rectangles along a circle, so you get a cylinder without a top and bottom (but this is not important in this case, because I need normals for the body). I tried to find solutions on the Internet, but none of the available solutions worked. I hope someone can help me.

Draw cylinder function below.

public void Draw()
    {
        double[]a, b, c, d;
        a = new double[3] { 0.0, 0.0, 0.0 };
        b = new double[3] {0.0, height, 0.0 };
        c = new double[3];
        d = new double[3];

        c[1] = height;
        d[1] = 0;

        GL.Begin(PrimitiveType.Quads);
        for (double angle = 0; angle <= 360; angle += 1.5)
        {
            c[0] = b[0];
            c[2] = b[2];

            d[0] = a[0];
            d[2] = a[2];

            b[0] = 1 * Math.Cos(angle * (Math.PI / 180));
            b[2] = 1 * Math.Sin(angle * (Math.PI / 180));

            a[0] = 1 * Math.Cos(angle * (Math.PI / 180));
            a[2] = 1 * Math.Sin(angle * (Math.PI / 180));

            if (angle != 0)
            {

                GL.Color3(color);
                GL.Vertex3(a);
                GL.Vertex3(b);
                GL.Vertex3(c);
                GL.Vertex3(d);
            }
        }
        GL.End();

Result image

Tagged : /

Code Bug Fix: How to find total number of childs and Number of grand child levels under a hierarchical list parent in C#

Original Source Link

I have a tree menu in my project.

The data looks like below

{ParentId = null, Id = 10, Name "a"}, 
{ParentId = null, Id = 33, Name "aa"}, 
{ParentId = 10 , Id = 11, Name "aaa"}, 
{ParentId = 10, Id = 12, Name "aaaa"}, 
{ParentId = 11, Id = 13, Name "aaaaa"}, 
{ParentId = 56 ,Id = 14, Name "aas"}, 
{ParentId = 78 , Id = 15, Name "adss"}, 
{ParentId = 99 , Id = 16, Name "ader"}

I have created a hierarchical list for holding the data

public class NavBarItem
    {
        public int? Id { get; set; }
        public int? ParentId { get; set; }
        public string Name{get;set;}
        public IEnumerable<NavBarItem> Children { get; set; }
        public int ChildCount { get; set; }
        public int HierarchyLevel { get; set; }
    }

And my recursive method will get data from the table and bind it to the Hierarchical List

What I am trying to get here is total number of children/grandchildren for each and every parent.

For example Parent A has child B and Child B has Child C & D, then the total ChildCount of A should be 3 , B should be 2 and C should be 0

Also I wanted to get the Hierarchy Level in each and every parent.

In the above example : Parent A has Child B and B has other child. So for parent A the hierarchyLevel is 2 and for B it should be 1 and for C it should be 0

Example if i am taking the item with Id = 10 , it has Hierarchy two (number of grand child levels )

 {ParentId = 10 , Id = 11, Name "aaa"}, 
  {ParentId = 11, Id = 13, Name "aaaaa"}, 

Is there any better way , or easy way I can get this ChildCount as well as the Hierarchy level.

Total Child count example :

Input is Id = 10 

total childs = 3. 

Current approach :

RecursiveMethod(List)
{
 for each through the list and find the count 
call the RecursiveMethod again 
}

My attempt at a generic solution:

Edit: Added some comments and other refinements to the solution

    /// <summary>
    /// Maps the nodes in a tree
    /// </summary>
    /// <param name="node">The node to process</param>
    /// <param name="level">
    /// the level of the node in the tree,
    /// 0 for the root node,
    /// 1 for children to the root etc.</param>
    /// <param name="childResults"> The result values for each of the children to the node </param>
    /// <returns> the result value for this node</returns>
    public delegate TResult TreeMapper<in T, TResult>(T node, int level, IEnumerable<TResult> childResults);

    /// <summary>
    /// Maps each node in a tree
    /// </summary>
    /// <param name="root">The root object of the tree</param>
    /// <param name="getChildren">Method to return all children of a node in the tree</param>
    /// <param name="map">
    /// Maps an item to some other type
    /// Inputs are:
    /// 1: The node of the tree
    /// 2: The level of the tree, starting with 0 for the root node
    /// 3: The results from each child to the node
    /// Returns: the result for the node
    /// </param>
    public static TResult MapChildren<T, TResult>(
        T root, 
        Func<T, IEnumerable<T>> getChildren,
        TreeMapper<T, TResult> map)
    {
        return RecurseBody(root, 0);

        TResult RecurseBody(T item, int level) 
            => map(item, level, getChildren(item).Select(child => RecurseBody(child, level + 1)));
    }

This can recurse over any kind of object that describes a tree, and compute some kind of value. This can be used to compute various properties of the tree if different mapping methods are used:
Compute total number of nodes in a tree:

(t, l, children) => children.Sum(c => c)+1;

Get the maximum level of a tree:

(t, l, children) => children.DefaultIfEmpty(l).Max()

The the method only produces one result for the entire tree. If you want to keep result for each node, you can either update the node itself, or keep a dictionary with node->result mapping

Unit test that computes the level and number of children of each item in the a tree, similarly to your example:

 public class TestItem
    {
        public TestItem(string name, TestItem[] children )
        {
            Children = children;
            Name = name;
        }
        public TestItem(string name) : this(name, new TestItem[0])
        { }
        public string Name { get; }
        public TestItem[] Children { get; }
    }

    [Test]
    public void Test()
    {
        TestItem test = new TestItem("A", new []
        {
            new TestItem("B", new []
            {
                new TestItem("C"),
                new TestItem("D")
            } ),
        } );

        // Compute the number of children to each node in the tree
        var childrenByItem = new Dictionary<string, int>();
        MapChildren<TestItem, int>(test, i => i.Children, 
            (item, level, childResults) => (childrenByItem[item.Name] = childResults.Sum(c => c)) + 1);

        Assert.AreEqual(3, childrenByItem["A"]);
        Assert.AreEqual(2, childrenByItem["B"]);
        Assert.AreEqual(0, childrenByItem["C"]);
        Assert.AreEqual(0, childrenByItem["D"]);

        // Compute the "Hierarchy Level", i.e. maximal distance to a leaf node, for each node
        var levelByItem = new Dictionary<string, int>();
        Tree.MapChildren<TestItem, int>(test, i => i.Children,
            (item, level, childResults) => levelByItem[item.Name] = childResults.DefaultIfEmpty(-1).Max() + 1);

        Assert.AreEqual(2, levelByItem["A"]);
        Assert.AreEqual(1, levelByItem["B"]);
        Assert.AreEqual(0, levelByItem["C"]);
        Assert.AreEqual(0, levelByItem["D"]);
    }

We can use the below method to get depth of a hierarchical list

public static IEnumerable<Tuple<int, T>> FindDepthOfTreeNode<T>(T root, Func<T, IEnumerable<T>> children)
        {
            var stack = new Stack<Tuple<int, T>>();

            stack.Push(Tuple.Create(1, root));

            while (stack.Count > 0)
            {
                var node = stack.Pop();

                foreach (var child in children(node.Item2))
                {
                    stack.Push(Tuple.Create(node.Item1 + 1, child));
                }
                yield return node;
            }
        }

and just use it like below

int depth = menuItem.Children == null ? 0 : menuItem.Children
                                .SelectMany(y => FindDepthOfTreeNode(y, xs => xs.Children ??
                                Enumerable.Empty<NavBarItem>()))
                                .Max(xs => xs.Item1);

For getting the total child count in a hierarchical list node we can use below method.

public static int GetChildCountFromTree(this NavBarItem obj)
        {
            var queue = new Queue<NavBarItem>();
            queue.Enqueue(obj); // Note that you can add first object in the queue constructor

            var result = 0;

            while (queue.Any())
            {
                var current = queue.Dequeue();
                result++;
                if (null != current.Children)
                {
                    foreach (NavBarItem inner in current.Children)
                    {
                        queue.Enqueue(inner);
                    }

                    current.Last =  true;
                }
            }

            return result;
        }

and we can use it like below

ourHirarchyNode.GetChildCountFromTree();

Let me know if this works for you:

var lookup = items.ToLookup(x => x.ParentId);

(int children, int level) Recurse(int? parentId)
{
    var r = lookup[parentId].Select(x => Recurse(x.Id)).ToArray();
    return r.Any() ? (r.Sum(x => x.children + 1), r.Max(x => x.level) + 1) : (0, 0);
}

My Recurse method is a local method.

Here’s my test code:

void Main()
{
    var items = new[]
    {
        new NavBarItem() {ParentId = null, Id = 10, Name = "a"},
        new NavBarItem() {ParentId = null, Id = 33, Name = "aa"},
        new NavBarItem() {ParentId = 10 , Id = 11, Name = "aaa"},
        new NavBarItem() {ParentId = 10, Id = 12, Name = "aaaa"},
        new NavBarItem() {ParentId = 11, Id = 13, Name = "aaaaa"},
        new NavBarItem() {ParentId = 56 ,Id = 14, Name = "aas"},
        new NavBarItem() {ParentId = 78 , Id = 15, Name = "adss"},
        new NavBarItem() {ParentId = 99 , Id = 16, Name = "ader"},
    };

    var lookup = items.ToLookup(x => x.ParentId);

    (int children, int level) Recurse(int? parentId)
    {
        var r = lookup[parentId].Select(x => Recurse(x.Id)).ToArray();
        return r.Any() ? (r.Sum(x => x.children + 1), r.Max(x => x.level) + 1) : (0, 0);
    }

    var parents = new int?[] { null, 10, 11, 56, 78, 99 };

    Console.WriteLine(
        String.Join(
            Environment.NewLine,
            parents
                .Select(p => new { p, r = Recurse(p) })
                .Select(x => $"{x.p} => {x.r.children}, {x.r.level}")));
}

public class NavBarItem
{
    public int? Id { get; set; }
    public int? ParentId { get; set; }
    public string Name { get; set; }
}

The results I get are:

 => 5, 3
10 => 3, 2
11 => 1, 1
56 => 1, 1
78 => 1, 1
99 => 1, 1

Tagged : / /

Making Game: Why can’t an inherited protected constructor be made public?

Original Source Link

Consider:

class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}

Why can’t an inherited protected constructor be made public, while an inherited protected member function can?

Unlike other members, the accessibility of the using-declaration that introduced the inherited constructor is ignored.

[namespace.udecl]/19,

(emphasis mine)

A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored.

Actually, the inherited constructor can be made public, but not just the way you wrote it. You can define your B class as follows:

class B : public A {
public:
    B() {}

    B(int x) : A(x) {}  // instead of using A::A(int)
    using A::f;
};

(see it on GodBolt)

Perhaps the standard committee thought that saying using A::A would be a bit ambiguous, since a constructor of the base class is not exactly the same thing as a constructor of the subclass.

Tagged : / / / /

Code Bug Fix: Generic Abstract Enum

Original Source Link

I am working on state machine for my Unity experimenting and I want to create system that would be responsible for state of individual objects.

My vision is this:

StateManager – Class responsible for Transforming states etc.

StateCollection – Abstract class in which derived clases would hold all instances of States for the object.

Enum – I want to use enums to select which state should be active now.

My Implementation looks like this:

public class StateManager<T,enumT> where T : StateCollection, new() where enumT : Enum
{

  private T states = new T();
  public T States 
  {
      get { return states;}
  }

  public void TransformState(enumT newState)
  {
    //some code
  }
}

public abstract class StateCollection
{

  public GameObject Object { get; set; }
  public abstract State GetState<enumT>(enumT enumState);
}

public class PlayerStatesCollection<enumT> : StateCollection
{

  private PlayerIdleState Idle = new PlayerIdleState();
  private PlayerShootState Shoot = new PlayerShootState();
  private PlayerMoveState Move = new PlayerMoveState();
  private PlayerDeadState Dead = new PlayerDeadState();



  public override State GetState(enumT enumState)
  {

    switch (enumState)
    {
        case PlayerStates.Idle:
            return Idle;
        case PlayerStates.Move:
            return Move;
        case PlayerStates.Shoot:
            return Shoot;
        case PlayerStates.Dead:
            return Dead;
        default:
            throw new System.Exception("Invalid State. #002");
    }
  }

}

public enum PlayerStates
{
  Idle,
  Shoot,
  Move,
  Dead
}

Now when I create Instance of StateManager I must write something like this:

public StateManager<PlayerStatesCollection<PlayerStates>, PlayerStates> StavManager = new StateManager<PlayerStatesCollection<PlayerStates>, PlayerStates>();

now I am not kinda happy with this, how it looks.. The generic parameter has twice “PlayerStates” which is unnecessary because it always be the same and I have not figured out how to do simply with “just”

StateManager<PlayerStatesCollection,PlayerStates>

If I create for example EnemyStatesCollection, it will be derived from StateCollection and have its own enum EnemyStates. and when I work with StateManager to transform state I want to be able to use its own enum, which will be defined when StateManager is created.

Tagged : /

Code Bug Fix: in WPF. How to scroll Objects in ScrollViewer by mouse-dragging, like as iPhone?

Original Source Link

it’s done well to scroll by mouse-wheel or scrollbar seed-dragging.
but scrolling by mouse-dragging contents on scroll view is not done.
How can i implement this action?

        <ScrollViewer x:Name="scrollViewer" Grid.Row="1" HorizontalScrollBarVisibility="Auto" CanContentScroll="True">
            <Grid x:Name="galleryGrid" ShowGridLines="True">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"></RowDefinition>
                    <RowDefinition Height="*"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="500"></ColumnDefinition>
                    <ColumnDefinition Width="500"></ColumnDefinition>
                    <ColumnDefinition Width="500"></ColumnDefinition>
                    <ColumnDefinition Width="500"></ColumnDefinition>
                    <ColumnDefinition Width="500"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Button Grid.Column="0" Magin="10,10,10,10">Test</Button>
                <Button Grid.Column="1" Magin="10,10,10,10">Test</Button>
                <Button Grid.Column="2" Magin="10,10,10,10">Test</Button>
                <Button Grid.Column="3" Magin="10,10,10,10">Test</Button>
                <Button Grid.Column="4" Magin="10,10,10,10">Test</Button>
            </Grid>
        </ScrollViewer>

I found a way of resolving this.
It’s following…

    Point scrollMousePoint = new Point();
    double hOff = 1;
    private void scrollViewer_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        scrollMousePoint = e.GetPosition(scrollViewer);
        hOff = scrollViewer.HorizontalOffset;
        scrollViewer.CaptureMouse();
    }

    private void scrollViewer_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        if(scrollViewer.IsMouseCaptured)
        {
            scrollViewer.ScrollToHorizontalOffset(hOff + (scrollMousePoint.X - e.GetPosition(scrollViewer).X));
        }
    }

    private void scrollViewer_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        scrollViewer.ReleaseMouseCapture();
    }

    private void scrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
        scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + e.Delta);
    }

thanks!

I did this class to scroll while keeping the scrollviewer buttons. From the code from user110777, but this works with vertical instead of horizontally, and works well with the viewer (Since I’m now only capturing the content). Plus I’m using MouseLeftButtonDown instead of the preview in order to allow the user to click things like the combobox without causing a drag. (If you want label or Textblock to drag set their IsHitTestVisible=false)

public class ScrollDragger
{
    private readonly ScrollViewer _scrollViewer;
    private readonly UIElement _content;
    private Point _scrollMousePoint;
    private double _hOff = 1;

    public ScrollDragger(UIElement content, ScrollViewer scrollViewer)
    {
        _scrollViewer = scrollViewer;
        _content = content;
        content.MouseLeftButtonDown += scrollViewer_MouseLeftButtonDown;
        content.PreviewMouseMove += scrollViewer_PreviewMouseMove;
        content.PreviewMouseLeftButtonUp += scrollViewer_PreviewMouseLeftButtonUp;
    }

    private void scrollViewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        _content.CaptureMouse();
        _scrollMousePoint = e.GetPosition(_scrollViewer);
        _hOff = _scrollViewer.VerticalOffset;
    }

    private void scrollViewer_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        if (_content.IsMouseCaptured)
        {
            var newOffset = _hOff + (_scrollMousePoint.Y - e.GetPosition(_scrollViewer).Y);
            _scrollViewer.ScrollToVerticalOffset(newOffset);
        }
    }

    private void scrollViewer_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        _content.ReleaseMouseCapture();
    } 
}

UWP variation:

    Pointer pointer;
    PointerPoint scrollMousePoint ;
    double hOff = 1;

    private void MainScrollviewer_PointerPressed(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        pointer = e.Pointer;
        scrollMousePoint = e.GetCurrentPoint(scrollviewer);
        hOff = scrollviewer.HorizontalOffset;
        scrollviewer.CapturePointer(pointer);
    }

    private void MainScrollviewer_PointerReleased(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        scrollviewer.ReleasePointerCaptures();
    }

    private void MainScrollviewer_PointerMoved(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        if (scrollviewer.PointerCaptures!= null&& scrollviewer.PointerCaptures.Count>0)
        {
          scrollviewer.ChangeView(hOff + (scrollMousePoint.Position.X - e.GetCurrentPoint(scrollviewer).Position.X),null,null);
        }
    }

I know that question was for WPF, but this was best result I found searching for UWP solution.

This is how I did it, XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="20px"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Text="this is not in the scrollviewer" Name="tb"/>
    <ScrollViewer Name="sv" 
                  HorizontalScrollBarVisibility="Auto" 
                  Grid.Row="1">
        <StackPanel Name="sp" Width="500" Height="500"
                    MouseMove="sp_MouseMove" 
                    Background="Transparent">
            <Ellipse Height="50" Width="50" Fill="Green"/>
        </StackPanel>

    </ScrollViewer>
</Grid>

C#:

private void sp_MouseMove(object sender, MouseEventArgs e)
    {
        Point newMousePosition = Mouse.GetPosition((StackPanel)sender);
        tb.Text = newMousePosition.X + " | " + newMousePosition.Y;

        if (Mouse.LeftButton == MouseButtonState.Pressed)
        {
            if (newMousePosition.Y < oldMousePosition.Y)
                sv.ScrollToVerticalOffset(sv.VerticalOffset + 1);
            if (newMousePosition.Y > oldMousePosition.Y)
                sv.ScrollToVerticalOffset(sv.VerticalOffset - 1);

            if (newMousePosition.X < oldMousePosition.X)
                sv.ScrollToHorizontalOffset(sv.HorizontalOffset + 1);
            if (newMousePosition.X > oldMousePosition.X)
                sv.ScrollToHorizontalOffset(sv.HorizontalOffset - 1);
        }
        else
        {
            oldMousePosition = newMousePosition;
        }
    }

where Point oldMousePosition; is a member of the window.

use this

for horizontal scrolling

private void ScrollViewer_OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)     
{             
    ScrollViewer scv = (ScrollViewer)sender;               
    scv.ScrollToHorizontalOffset(scv.HorizontalOffset - e.Delta);
    e.Handled = true;    
}

My experience: follow user110777
Changed below code

private void scrollViewer_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
       scrollMousePoint = e.GetPosition(scrollViewer);
        hOff = scrollViewer.HorizontalOffset;
        scrollViewer.CaptureMouse();
    }

You can do this in C# WPF like this.
note that there are two type of Point classes.From them you should use System.Windows.Point to get this work.These are mouse related events for your ScrollViewer.The code below will scroll your object to both horizontal and vertical inside the ScrollViewer.

   System.Windows.Point ScrollMousePoint1 = new System.Windows.Point();
   double HorizontalOff1 = 1; double VerticalOff1 = 1;
   private void ScrollViewer1_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ScrollMousePoint1 = e.GetPosition(ScrollViewer1);
            HorizontalOff1 = ScrollViewer1.HorizontalOffset;
            VerticalOff1 = ScrollViewer1.VerticalOffset;
            ScrollViewer1.CaptureMouse();
        }

        private void ScrollViewer1_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (ScrollViewer1.IsMouseCaptured)
            {
                ScrollViewer1.ScrollToHorizontalOffset(HorizontalOff1 + (ScrollMousePoint1.X - e.GetPosition(ScrollViewer1).X));
                ScrollViewer1.ScrollToVerticalOffset(VerticalOff1 + (ScrollMousePoint1.Y - e.GetPosition(ScrollViewer1).Y));
            }
        }

        private void ScrollViewer1_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ScrollViewer1.ReleaseMouseCapture();
        }

        private void ScrollViewer1_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            ScrollViewer1.ScrollToHorizontalOffset(ScrollViewer1.HorizontalOffset + e.Delta);
            ScrollViewer1.ScrollToVerticalOffset(ScrollViewer1.VerticalOffset + e.Delta);
        }

Tagged : / /

Code Bug Fix: I’m getting a “redefinition of” error for every method in the class

Original Source Link

I’m getting a redefinition error for every method in the class. I tried to put the .cpp code in the header where the “include Algebra.cpp” is, but didn’t change a thing.

// This is the .h file
#ifndef ALGEBRA_H
#define ALGEBRA_H

#include <iostream>

template <size_t rows, size_t cols>
class Matrix {
    double** matrix;
    void debug_print();    
public:
    Matrix();
    Matrix(double (&_matrix)[rows][cols]);
    ~Matrix();

    double calculate_determinant();

};

#include "Algebra.cpp"

#endif
// This is the .cpp file
#include "Algebra.h"

#include <cassert>

template <size_t rows, size_t cols>
Matrix<rows, cols>::Matrix() {...}
// I have defined all the methods below..

First, that template function definition belongs in the header file that gets pulled in wherever it’s needed with #include "algebra.h".

The reason you’re getting problems with this particular setup is that, as several comments have suggested, you’re compiling the .cpp file that contains that template function definition. When the compiler compiles “algebra.cpp”, it first sees the #include directive at the top of the file, and pulls in the text from “algebra.h”. That’s fine as far as it goes, but at the end of “algebra.h” it sees #include "algebra.cpp". So it pulls in the text from there.

Now it’s compiling “algebra.cpp” inside of “algebra.cpp”. The include guard in “algebra.h” works here, so there is no redefinition of the contents of “algebra.h”. And then it sees the definition of Matrix<rows, cols>::Matrix(). Still okay, so far.

Now it comes to the end of the code that comes in through the #include directive, so it continues to compile the code in “algebra.cpp”, and it again sees the definition of Matrix<rows, cols>::Matrix(), and that’s the redefinition that the compiler is complaining about.

That’s why you shouldn’t do that.

Some folks like to put definitions of member functions of class templates in a separate file from the header that defines the class template. That’s okay, but don’t compile that file; it should only be compiled as part of the header that uses it. And as a practical matter, that means giving it an extension that makes it clear that it’s not a source file to be compiled on its own. When I’ve used that approach, I use “.inl” as the extension. If you change the name of “algebra.cpp” to “algebra.inl” and make sure that you’re not telling the compiler to compile “algebra.inl” this problem should go away.

Tagged : /