Call C# function Blazor Jquery - c#

Need some help sorting an error added a screenshot of code and the error returned by the code.
Trying to call a C# function from Jquery and pass parameters along.
_Host
function getElementSVG(e) {
var position = getPosition(e);
var circle = makeSVG('circle', { cx: position.pointx, cy: position.pointy, r: 0.02, stroke: 'black', 'stroke-width': 0.5, fill: 'black' });
document.getElementById(e.currentTarget.id).appendChild(circle);
DotNet.invokeMethodAsync('PeopleCounterWeb', 'AddPointToList', position.pointx, position.pointy).then(result => {
console.log(result);
});
return position;
}
function fnsuccesscallback(data) {
alert(data.d);
}
function fnerrorcallback(result) {
alert(result.statusText);
}
function makeSVG(tag, attrs) {
var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
function getPosition(e) {
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var width = rect.width;
var height = rect.height;
var pointx = ((x / width) * 100).toFixed(2);
var pointy = ((y / height) * 100).toFixed(2);
return {
pointx,
pointy
}
};
MainMap.cshtml
[JSInvokable]
public string AddPointToList(string x, string y)
{
var alpha = x + "-" + y;
return "";
//Points.Add(obj[0], obj[1]);
}
Code
[Error]

You are trying to invoke a message on an instance without passing a reference to that instance. Without an instance you can only call static methods.
You'll need to create an instance of DotNetReference in C# and pass it to JS.
There is a section on Blazor University about calling C# from JS - https://blazor-university.com/javascript-interop/calling-dotnet-from-javascript/

Related

Checking if 2 geolocations with radius are within eachothers radius

I'm trying to determine if a tracker is within 5km of it's destination.
This tracker has a Lat, Lng and Accuracy
So this would give us
public static void Main()
{
// Current location
var trackerLat = <Lat>;
var trackerLng = <Lng>;
var trackerAcc = 150;
// Destination
var destinationLat = <Lat>;
var destinationLng = <Lng>;
var withingRange = 5000;
if (isWithingRange(trackerLat, trackerLng, trackerAcc, destinationLat, destinationLng, withingRange))
Console.WriteLine("Close");
else
Console.WriteLine("Not close");
}
private static bool isWithingRange(double c1x, double c1y, double r1, double c2x, double c2y, double r2) {
var dX = c1x - c2x;
var dY = c1y - c2y;
var radius = r1 + r2;
var distsqt = Math.Sqrt((dX * dX) + (dY * dY));
Console.WriteLine(String.Format("Val1: {0}, val2: {1}", distsqt, radius));
if (distsqt < radius)
return true;
else
return false;
}
But this says it's always within range :(
I would think the range format is wrong compared to the coordinate system, but I can't seem to find on how to convert it correctly
fiddle: https://dotnetfiddle.net/FEGC2B
Take a look at GeoCoordinate (System.Device.Location). It has a GetDistanceTo() method that gives you the distance in meters to another GeoCoordinate.
https://learn.microsoft.com/en-us/dotnet/api/system.device.location.geocoordinate
Use System.Device:
var location1 = new System.Device.Location.GeoCoordinate(latitude1, longitude1);
var location2 = new System.Device.Location.GeoCoordinate(latitude2, longitude2);
return location1.GetDistanceTo(location2) <= (radius1 + radius2);

Finding Coordinates of Line-Line Intersection in C#

to start with I made a simple code that checks if 2 lines collide based on 4 points that are given by their x and y coordinates. It checks if the angle (variable k in my code) of both lines is the same, in that case they are parallel, otherwise they collide. The angle (k) was calculated based on the math equasion Click here [k = (y2-y1)/(x2-x1)]. Now I am not sure how to get the point they are colliding in. I would appreciate it very much if you could help me. Thank you in advance.
My Code: (method I call to calculate angle)
static void MetodaTrazenjaPresjeka(Duzina d1, Duzina d2)
{
int k11 = d1.Krajy - d1.Pocy; //y2-y1 - first line
int k12 = d1.Krajx - d1.Pocx; //x2-x1 - first line
double k1 = (double)k11 / k12; //angle of the first line
int k21 = d2.Krajy - d2.Pocy; //y2-y1 - second line
int k22 = d2.Krajx - d2.Pocx; //x2-x1 - second line
double k2 = (double)k21 / k22; //angle of the second line
if (k1 == k2)
{
//they are parallel
Console.WriteLine("MOJA METODA:");
Console.WriteLine("-----------------------------------");
Console.Write("Pravci zadani tockama su paralelni!");
}
else
{
//lines are colliding
Console.WriteLine("MOJA METODA:");
Console.WriteLine("-----------------------------------");
Console.Write("Pravci zadani tockama se sijeku!");
}
}
Code in class Duzina:
class Duzina
{
private int pocx, pocy, krajx, krajy;
//read/write attribute for the x coordinate of the first point
public int Pocx
{
get { return pocx; }
set { pocx = value; }
}
//read/write attribute for the y coordinate of the first point
public int Pocy
{
get { return pocy; }
set { pocy = value; }
}
//read/write attribute for the x coordinate of the second point
public int Krajx
{
get { return krajx; }
set { krajx = value; }
}
//read/write attribute for the y coordinate of the second point
public int Krajy
{
get { return krajy; }
set { krajy = value; }
}
//method that will print out coordinates of the given points
public void Ispis()
{
Console.Write("Pocetna tocka: ({0},{1})",Pocx,Pocy);
Console.Write("Krajnja tocka: ({0},{1})", Krajx, Krajy);
}
}
line equation: y = m * x + b
1) m_d1 = (d1.y2 - d1.y1) / (d1.x2 - d1.x1)
b_d1 = d1.y1 - m_d1 * d1.x1
(same for m_d2 and b_d2)
2) intersect.y = m_d1 * intersect.x + b_d1
intersect.y = m_d2 * intersect.x + b_d2
3) m_d1 * intersect.x + b_d1 = m_d2 * intersect.x + b_d2
4) intersect.x = (b_d2 - b_d1) / (m_d1 - m_d2)
now plug intersect.x that was obtained from 4) back into either equation in 2) to get intersection.y

TestStack.White How to click on Hyperlink Located in a Document in WinForm Application

I m trying to do some automation tests in 1 application using TestStack.White framework , and i can t find a solution on how to click on a hyperlink located in one Document.
document.logstructure() :
AutomationId: linkTexts
ControlType: ControlType.Document
Name: Perform an action on event#LinkId=1
from devices/recording server/management server#LinkId=2
HelpText:
Bounding rectangle: 354,563,570,151
ClassName: WindowsForms10.RichEdit20W.app.0.ca490a_r12_ad1
IsOffScreen: False
FrameworkId: WinForm
ProcessId: 6816
System.Windows.Automation.ScrollPattern
System.Windows.Automation.TextPattern
UISpy :
UISpy view
And pic of hyperlink:
Picture of hyperlink located in app
Thank you !
After days of searching , the best solution I could find is this:
{
...
//Get document container
var document = _modalWindow.Get(SearchCriteria.ByAutomationId(Config.DocumentRulesEvent));
// Get document's bounding Rectangle
string rightCorner = document.Bounds.Right.ToString();
string leftCorner = document.Bounds.Left.ToString();
string topCorner = document.Bounds.Top.ToString();
string bottomCorner = document.Bounds.Bottom.ToString();
// Hardcoded percent of x and y
int percentX = 22;
int percentY = 7;
GetCoordinatesFromBoundingRectangle(rightCorner, leftCorner, topCorner, bottomCorner, percentX, percentY);
}
public void GetCoordinatesFromBoundingRectangle(string rightCorner, string leftCorner, string topCorner, string bottomCorner, int percentX, int percentY)
{
// transform strings to integre
int a = Int32.Parse(rightCorner);
int b = Int32.Parse(leftCorner);
int c = Int32.Parse(topCorner);
int d = Int32.Parse(bottomCorner);
// Calculate X from AB segment
int x = (a - b) * percentX;
x = x / 100;
x = b + x;
//Calculate Y from CD segment
int y = (d - c) * percentY;
y = y / 100;
y = c + y;
ClickOnPoint(x, y);
}
// Method that moves mouse to x and y and click
public void ClickOnPoint(int x, int y)
{
var pointClick = new System.Windows.Point(x, y);
Mouse.Instance.Click(MouseButton.Left, pointClick);
}

Concurrent Dictionary AddOrUpdate method 3rd parameter?

private readonly ConcurrentDictionary<string, System.Drawing.Color> _colorSet;
public void BuildColorSet(IList<string> colorNames, string prefix, bool forceLastToGray)
{
var size = forceLastToGray ? colorNames.Count - 1 : colorNames.Count;
int nbHue = 6;
int nbCycle = (int)Math.Ceiling((double)size / nbHue);
var saturationMax = nbCycle <= 2 ? 1.0 : 1.0;
var saturationMin = 0.3;
var luminanceMax = nbCycle <= 2 ? 0.85 : 0.85;
var luminanceMin = 0.3;
var maxSaturationShift = 0.30;
var maxLuminanceShift = 0.15;
var interval = 1.0 / Math.Min(size, nbHue);
var saturationShift = (saturationMax - saturationMin) / (nbCycle - 1);
saturationShift = Math.Min(saturationShift, maxSaturationShift);
var luminanceShift = (luminanceMax - luminanceMin) / (nbCycle - 1);
luminanceShift = Math.Min(luminanceShift, maxLuminanceShift);
var hueShift = 0.0;
var saturation = saturationMax;
var luminance = luminanceMax;
for(var i = 0; i<size; i++)
{
if(i > 0 && (i % nbHue == 0)) // Next Cycle
{
saturation -= saturationShift;
luminance -= luminanceShift;
hueShift = hueShift == 0 ? interval/2 : 0;
}
var hue = interval*(i%nbHue) + hueShift;
System.Drawing.Color color = HSL2RGB(hue, saturation, luminance);
_colorSet.AddOrUpdate(prefix + colorNames[i], color, ???);
}
if(forceLastToGray)
{
_colorSet.TryAdd(prefix + colorNames[colorNames.Count - 1], System.Drawing.Color.LightGray);
}
_cssDirty = true;
}
I want to be able to update the dictionary if the color exists with new value. And also add to dictionary if the color is not there in dictionary.
I am using the AddOrUpdate but not able to get the 3rd parameter(form the lambda expression OR delegate method) of the AddOrUpdate method.
Any idea how my 3rd parameter would look like?
From the documentation:
updateValueFactory
Type: System.Func
The function used to generate a new value for an existing key based on the key's existing value
This will leave the value in the collection alone if it already exists:
_colorSet.AddOrUpdate(prefix + colorNames[i], color,
(key, existingVal) =>
{
return existingVal;
});
This will replace the value in the collection with the same one specified for the insert:
_colorSet.AddOrUpdate(prefix + colorNames[i], color,
(key, existingVal) =>
{
return color;
});
You can perform conditional logic, comparisons between the old value and new value, or update the original object in the function, for example.
_colorSet.AddOrUpdate(prefix + colorNames[i], color,
(key, existingVal) =>
{
if (existingVal.Name == "Red")
return existingVal;
else
return color;
});
As per the web page asawyer gave you, what's required is a function
Func<TKey, TValue, TValue>
In this case it looks like you are passing a string and a Color but how you want to combing them is largely upto you. You need a function that returns a Color so the following should work from a syntax perspective.
(key, oldValue) => oldValue
I've no idea who you might calculating the new value. You could for example use your new color
_colorSet.AddOrUpdate(prefix + colorNames[i], color, (key, oldValue) => color);
It looks like you don't care if the color is already there; you always want to update the value in the dictionary. In that case you're better off using the normal indexer, e.g.
_colorSet[prefix + colorNames[i]] = color;

C# Methods: Defined Parameter Default Value Issue

I am writing an app that requires the calculation of the Gamma function.
A code (part of a class) snippet is below:
namespace PB.Utilities.Math
{
// class definition
public class SpecialFunctions
{
// Private Fields
// Instance Constructor
public SpecialFunctions() {}
// Public Method for Gamma Function
// x = input value; x MUST BE > 0
// GammaLn = secondary output value equal to natural log of Gamma Function
public double Gamma(double x, out double GammaLn)
{
try
{
if (x <= 0) throw new System.ArgumentException("arg <= 0 in GammaFunction", "x");
}
catch
{
System.Console.WriteLine("argument <= 0 in GammaFunction");
System.Console.ReadKey();
}
double gammaln;
double _gamma = gamma(x, out gammaln);
GammaLn = gammaln;
return _gamma;
}
// private method for Gamma Function
private double gamma(double xx, out double gammaln)
{
// private constants
int j;
double x,tmp,y,ser;
const double k1 = 5.24218750000000000;
const double k2 = 0.999999999999997092;
const double k3 = 2.5066282746310005;
double[] cof = new double[14]
{
57.1562356658629235, -59.5979603554754912, 14.1360979747417471,
-0.491913816097620199, 0.339946499848118887e-4, 0.465236289270485756e-4,
-0.983744753048795646e-4, 0.158088703224912494e-3, -0.210264441724104883e-3,
0.217439618115212643e-3, -0.164318106536763890e-3, 0.844182239838527433e-4,
-0.261908384015814087e-4, 0.368991826595316234e-5
};
y = x = xx;
tmp = x + k1;
tmp = (x + 0.5) * System.Math.Log(tmp) - tmp;
ser = k2;
for (j = 0; j < 14; j++) ser += cof[j]/++y;
gammaln = tmp + System.Math.Log(k3*ser/x);
return System.Math.Exp(gammaln);
}
}
}
public class BSA
{
static void Main()
{
// Create an object of type PB.Utilities.Math.SpecialFunctions
PB.Utilities.Math.SpecialFunctions Function = new PB.Utilities.Math.SpecialFunctions();
// Call the public method GammaFunction.
double GammaLn1;
double GammaLn2;
double GammaLn3;
double g1 = Function.Gamma(3.5, out GammaLn1);
double g2 = Function.Gamma(1.5, out GammaLn2);
double g3 = Function.Gamma(1/7, out GammaLn3);
System.Console.WriteLine("g(7/2) = "+g1);
System.Console.WriteLine("g(3/2) = "+g2);
System.Console.WriteLine("g(1/7) = "+g3);
}
}
The issue is that at compilation, the parameter x in Gamma (even though x is being assigned the value 3.5 in the calling component) is assigned a value of 0 which triggers the exception. Can anyone please suggest how I can get around this? Thank you.
Seems to be 3.5 in my test cases. Are you sure you haven't excluded some information that might be the issue?
using System;
namespace Doubletesting
{
class Program
{
static void Main(string[] args)
{
double d = Doubletesting.TestDouble(3.5);
Console.WriteLine(d.ToString());
Console.ReadKey();
}
public static double TestDouble(double x)
{
double result;
result = x;
return result;
}
}
}
Result
3.5
UPDATED
The Error is caused by your Function.Gamma(1 / 7, out GammaLn3). This is because both 1 and 7 are INT and dividing (int)1 by (int)7 is zero. Try Function.Gamma(1f / 7f, out GammaLn3).

Categories

Resources