|
Copy and paste is to easy.. but understanding code is difficult... how its work and why its work
|
|
|
|
|
And you won't get that from most video tutorials - they are generally made by people who can't read and write, much less explain how things work!
I've yet to see a code-based video tutorial that was better than the text-based equivalent.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
|
That would be an interesting C# video tutorial to create. I will keep this in mind on my Youtube C# video channel.
Ben Scharbach
Temporalwars.Com
YouTube:Ben Scharbach
|
|
|
|
|
Message Removed
modified 20-Jul-17 10:10am.
|
|
|
|
|
Message Removed
modified 20-Jul-17 10:10am.
|
|
|
|
|
Message Removed
modified 20-Jul-17 10:10am.
|
|
|
|
|
How to call the load runner (LR) controller from visual studio
|
|
|
|
|
|
Install the Visual Studio add-in on the LoadRunner CD: open its UI, read the 'ReadMe file.
«Differences between Big-Endians, who broke eggs at the larger end, and Little-Endians gave rise to six rebellions: one Emperor lost his life, another his crown. The Lilliputian religion says an egg should be broken on the convenient end, which is now interpreted by the Lilliputians as the smaller end. Big-Endians gained favor in Blefuscu.» J. Swift, 'Gulliver's Travels,' 1726CE
|
|
|
|
|
In the diagram given in below link for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. I am struggling to create a query for it using linq to sql.I need to select OrderId, Date and TotalPrice and it should include a where clause for comparing customer ID.
<a href="https://prnt.sc/fwf7ca">Relationship Diagram</a>
What I have tried:
dc.orders.Select(o => new { o.orderId, o.date, TotalPrice = ( (o.orderLines.Select(ol => ol.foodItem.price).Sum() * decimal.Parse(o.orderLines.Select(ox => ox.quantity).ToString())) + decimal.Parse(o.orderLines.Select(x => x.extraPrice).ToString())) } );
|
|
|
|
|
Also posted in QA: OP advised to remove one of the two. Possibly homework ?
«Differences between Big-Endians, who broke eggs at the larger end, and Little-Endians gave rise to six rebellions: one Emperor lost his life, another his crown. The Lilliputian religion says an egg should be broken on the convenient end, which is now interpreted by the Lilliputians as the smaller end. Big-Endians gained favor in Blefuscu.» J. Swift, 'Gulliver's Travels,' 1726CE
|
|
|
|
|
No, its not homework my friend. If its was homework I wouldn't have posted it.
|
|
|
|
|
|
Stop and think about what you're trying to do.
Member 12462411 wrote: decimal.Parse(o.orderLines.Select(ox => ox.quantity).ToString()) Member 12462411 wrote: decimal.Parse(o.orderLines.Select(x => x.extraPrice).ToString()) You're taking a query and converting it to a string. That will most likely return the SQL query - "SELECT quantity FROM ..." . You then try to parse that SQL query as a decimal , which will throw an exception.
And even if it worked, you can't calculate the total like that anyway. For example, (1 × 10) + (2 × 5) is not that same as (1 + 2) × (10 + 5) !
For each line, you want to multiply the price by the quantity, then add the extra price. You then want to sum the results up to get the total price:
o.orderLines.Sum(ol => (ol.foodItem.price * ol.quantity) + ol.extraPrice)
If you want to filter the orders, then add a Where call[^] before the Select call.
dc.orders.Where(o => ...).Select(o => ...);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date,
val = g.Sum(x => x.c.price * x.b.quantity) + g.Select(d => d.b.quantity)
});
I have created the above query. Now the only problem is in the last line (val = g.Sum(x => x.c.price * x.b.quantity) + g.Select(d => d.b.quantity)).
It shows error (Operator + cannot be applied to operand of type decimal? and System.Collection.Generic.IENumerable<int?>
Can you please help.
|
|
|
|
|
g.Select(... return an iEnumerable NOT a numeric value.
Split that line and get a price and then a quantity into 2 variables and then do your mathematical function on the 2 variables.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
What you're trying to do doesn't seem to make sense to me, but if you combine the two operators, it will work:
val = g.Sum(x => (x.c.price * x.b.quantity) + x.b.quantity)
val = g.Sum(x => (x.c.price + 1) * x.b.quantity)
As Mycroft said above, Select returns an IEnumerable<T> , not a number.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank You All. Finally I got it right.
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date,
price1 = g.Sum(x => x.c.price * x.b.quantity) + g.Key.orderLines.Select(o => o.extraPrice).Sum()
});
here is my final query.
|
|
|
|
|
I am building a system to record 6DOF information during an aerobatic flight. I grab data from a hardware set including an IMU, a GPS and a Baro altimeter and 20 to 30ms intervals. I attempted to use the WinForms Timer to schedule data recording using BW to allow me the collect the data in the DoWork method and then write the data to the WinForm in the WorkCompleted method. All this worked properly but the WinForms timer didn't provide the accuracy for scheduling the data properly.
I did a test using a multimedia timer which provided the necessary update timing accuracy but when I used it to drive a BW the WorkCompleted method was no longer in the UI string and I get an error for trying to access a UI element from outside the UI string. I can make this work doing a BeginInvoke((MethodInvoker) delegate {all updates to UI elements in here}). What I would like to know if there is a way to force the WorkCompleted method back to the UI string. Also, not sure why changing the timer made the BW operation change and no longer have the WorkCompleted method in the UI string.
The code for the program is below. The first set is my code and the second set it the C# code that implements the timer that I got off the internet. I'm not sure I used the
correctly but at least I tried.
Appreciate any suggestions as I am still trying to figure out C# and the .net/Winforms environment.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Simple_BW_Timing_with_Winforms
{
public partial class Form1 : Form
{
Stopwatch systemTimer;
long time1 = 0, time2 = 0;
public long timeBetweenCalls;
int count;
BackgroundWorker updateInfoBW;
public delegate void _writeForm();
public readonly MicroLibrary.MicroTimer _microTimer;
public Form1()
{
updateInfoBW = new BackgroundWorker();
updateInfoBW.DoWork += updateInfoDoWork;
updateInfoBW.RunWorkerCompleted += updateInfoWorkCompleted;
InitializeComponent();
systemTimer = new Stopwatch();
systemTimer.Start();
_microTimer = new MicroLibrary.MicroTimer();
_microTimer.MicroTimerElapsed +=
new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(tmrCallBW_tick);
_microTimer.Interval = 20000;
_microTimer.Start();
}
void tmrCallBW_tick(object sender, EventArgs e)
{
time1 = time2;
time2 = systemTimer.ElapsedMilliseconds;
timeBetweenCalls = time2 - time1;
updateInfoBW.RunWorkerAsync();
}
void updateInfoDoWork(object sender, EventArgs e)
{
return;
}
void updateInfoWorkCompleted(object sender, EventArgs e)
{
count++;
BeginInvoke((MethodInvoker)delegate
{
CallTime.Text = string.Format("{0}", timeBetweenCalls);
CountBox.Text = string.Format("{0}", count);
});
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_microTimer.Abort();
}
}
}
The code for the MicroTimer is:
<pre>using System;
namespace MicroLibrary
{
public class MicroStopwatch : System.Diagnostics.Stopwatch
{
readonly double _microSecPerTick =
1000000D / System.Diagnostics.Stopwatch.Frequency;
public MicroStopwatch()
{
if (!System.Diagnostics.Stopwatch.IsHighResolution)
{
throw new Exception("On this system the high-resolution " +
"performance counter is not available");
}
}
public long ElapsedMicroseconds
{
get
{
return (long)(ElapsedTicks * _microSecPerTick);
}
}
}
public class MicroTimer
{
public delegate void MicroTimerElapsedEventHandler(
object sender,
MicroTimerEventArgs timerEventArgs);
public event MicroTimerElapsedEventHandler MicroTimerElapsed;
System.Threading.Thread _threadTimer = null;
long _ignoreEventIfLateBy = long.MaxValue;
long _timerIntervalInMicroSec = 0;
bool _stopTimer = true;
public MicroTimer()
{
}
public MicroTimer(long timerIntervalInMicroseconds)
{
Interval = timerIntervalInMicroseconds;
}
public long Interval
{
get
{
return System.Threading.Interlocked.Read(
ref _timerIntervalInMicroSec);
}
set
{
System.Threading.Interlocked.Exchange(
ref _timerIntervalInMicroSec, value);
}
}
public long IgnoreEventIfLateBy
{
get
{
return System.Threading.Interlocked.Read(
ref _ignoreEventIfLateBy);
}
set
{
System.Threading.Interlocked.Exchange(
ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value);
}
}
public bool Enabled
{
set
{
if (value)
{
Start();
}
else
{
Stop();
}
}
get
{
return (_threadTimer != null && _threadTimer.IsAlive);
}
}
public void Start()
{
if (Enabled || Interval <= 0)
{
return;
}
_stopTimer = false;
System.Threading.ThreadStart threadStart = delegate()
{
NotificationTimer(ref _timerIntervalInMicroSec,
ref _ignoreEventIfLateBy,
ref _stopTimer);
};
_threadTimer = new System.Threading.Thread(threadStart);
_threadTimer.Priority = System.Threading.ThreadPriority.Highest;
_threadTimer.Start();
}
public void Stop()
{
_stopTimer = true;
}
public void StopAndWait()
{
StopAndWait(System.Threading.Timeout.Infinite);
}
public bool StopAndWait(int timeoutInMilliSec)
{
_stopTimer = true;
if (!Enabled || _threadTimer.ManagedThreadId ==
System.Threading.Thread.CurrentThread.ManagedThreadId)
{
return true;
}
return _threadTimer.Join(timeoutInMilliSec);
}
public void Abort()
{
_stopTimer = true;
if (Enabled)
{
_threadTimer.Abort();
}
}
void NotificationTimer(ref long timerIntervalInMicroSec,
ref long ignoreEventIfLateBy,
ref bool stopTimer)
{
int timerCount = 0;
long nextNotification = 0;
MicroStopwatch microStopwatch = new MicroStopwatch();
microStopwatch.Start();
while (!stopTimer)
{
long callbackFunctionExecutionTime =
microStopwatch.ElapsedMicroseconds - nextNotification;
long timerIntervalInMicroSecCurrent =
System.Threading.Interlocked.Read(ref timerIntervalInMicroSec);
long ignoreEventIfLateByCurrent =
System.Threading.Interlocked.Read(ref ignoreEventIfLateBy);
nextNotification += timerIntervalInMicroSecCurrent;
timerCount++;
long elapsedMicroseconds = 0;
while ( (elapsedMicroseconds = microStopwatch.ElapsedMicroseconds)
< nextNotification)
{
System.Threading.Thread.SpinWait(10);
}
long timerLateBy = elapsedMicroseconds - nextNotification;
if (timerLateBy >= ignoreEventIfLateByCurrent)
{
continue;
}
MicroTimerEventArgs microTimerEventArgs =
new MicroTimerEventArgs(timerCount,
elapsedMicroseconds,
timerLateBy,
callbackFunctionExecutionTime);
MicroTimerElapsed(this, microTimerEventArgs);
}
microStopwatch.Stop();
}
}
public class MicroTimerEventArgs : EventArgs
{
public int TimerCount { get; private set; }
public long ElapsedMicroseconds { get; private set; }
public long TimerLateBy { get; private set; }
public long CallbackFunctionExecutionTime { get; private set; }
public MicroTimerEventArgs(int timerCount,
long elapsedMicroseconds,
long timerLateBy,
long callbackFunctionExecutionTime)
{
TimerCount = timerCount;
ElapsedMicroseconds = elapsedMicroseconds;
TimerLateBy = timerLateBy;
CallbackFunctionExecutionTime = callbackFunctionExecutionTime;
}
}
}
|
|
|
|
|
What do you mean "not enough accuracy".
"Timers" (in general) are "guaranteed" not to run "before" the interval has elapsed; but not how long "after" the interval has elapsed.
I use DispatcherTimers and WPF apps; the DispatcherTimer runs on the UI thread; so that issue is handled.
And I use more than one timer to create a "pipeline":
1) One retrieves new samples from the devices
2) Another backsup samples to disk
3) Another charts the samples in real-time
4) Another does a "grid" display update of the "sampled zones"
5) Another monitors device status independent of the sampling rate
6) Another "heart beat" monitors overall system health and restarts any paused processes.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
First, Windows is NOT a real-time O/S. There's over a thousands threads running before your app starts.
Timers are guaranteed to not fire before the specified interval, but there is no guarantee of them firing at all!
The Windows Forms timer is probably the least accurate timer of them all. It fires on an event, which the applications message pump has to process and dispatch to your Tick event handling code. Well, messages in the pump are queued up waiting to be processed. There could be a ton of other messages, such as mouse changes, keyboard changes, painting, ... ahead of the Tick message. Processing those messages takes time, thereby knocking your Tick event off its interval, possibly even past the next Tick interval!
I would probably have a microcontroller gathering this information at a set interval, storing it, and sending it in batches to your WinForms app when that app requests it. The drawback to this would be the limited memory of a microcontroller if it doesn't have something like SD card storage available.
|
|
|
|
|
The BackgroundWorker (BGW) uses a WindowFormsSynchronizationContext (SC) to invoke the completed and progress events on the UI thread. The SC comes from the thread that calls the RunWorkerAsync method.
A non UI thread typically has no SC and then the BGW operates what is sometimes called the "free threaded model" using a ThreadPool thread to fire the completed and progress events.
A BGW started from a new thread will behave properly if the thread is given the UI thread's SC.
Some example code, I hope the missing bits are obvious.
private void StartFromThreadWithContext_Click(Object sender, EventArgs e) {
log.WriteLine("UI thread {0}", Thread.CurrentThread.ManagedThreadId);
Thread starterThread = new Thread(StarterThreadProc);
starterThread.Start(SynchronizationContext.Current);
}
private void StarterThreadProc(Object context) {
log.WriteLine("Starting BGW from thread {0}", Thread.CurrentThread.ManagedThreadId);
WindowsFormsSynchronizationContext wfsc = context as WindowsFormsSynchronizationContext;
if (wfsc != null) {
SynchronizationContext.SetSynchronizationContext(wfsc);
}
log.WriteLine("Thread has {0}", SynchronizationContext.Current);
worker.RunWorkerAsync();
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
log.WriteLine("RunWorkerCompleted thread {0}", Thread.CurrentThread.ManagedThreadId);
}
private void Worker_DoWork(object sender, DoWorkEventArgs e) {
log.WriteLine("DoWork thread {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(300);
}
Output to the log shows correct invocation of the completed event
UI thread 10
Starting BGW from thread 12
Thread has System.Windows.Forms.WindowsFormsSynchronizationContext
DoWork thread 7
RunWorkerCompleted thread 10
Alan.
|
|
|
|
|
Anytime I do BW threads talking the UI, I have to use the Dispatcher.Invoke or Dispatcher.BeginInvoke to send the changes back to the UI thread. I am not sure if the Dispatcher specifically is available in the old WinForm, but the cross-thread issue be the right direction to think about to resolve your issue.
Ben Scharbach
Temporalwars.Com
YouTube:Ben Scharbach
|
|
|
|
|
Hi how can i paste image to file?
my image is CF_ENHMETAFILE=14 image
Code below get image without quality how can i save image from clipboard to file.
Thank you
public class ClipboardMetafileHelper
{
[DllImport("user32.dll", EntryPoint = "OpenClipboard", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenClipboard(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "EmptyClipboard", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EmptyClipboard();
[DllImport("user32.dll", EntryPoint = "SetClipboardData", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr SetClipboardData(int uFormat, IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetClipboardData", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetClipboardData(int uFormat);
[DllImport("user32.dll", EntryPoint = "CloseClipboard", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool CloseClipboard();
[DllImport("gdi32.dll", EntryPoint = "CopyEnhMetaFileA", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, IntPtr hNULL);
[DllImport("gdi32.dll", EntryPoint = "DeleteEnhMetaFile", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool DeleteEnhMetaFile(IntPtr hemfSrc);
public static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf)
{
bool bResult = new bool();
bResult = false;
IntPtr hEMF = default(IntPtr);
IntPtr hEMF2 = default(IntPtr);
hEMF = mf.GetHenhmetafile();
if (!hEMF.Equals(new IntPtr(0)))
{
hEMF2 = CopyEnhMetaFile(hEMF, new IntPtr(0));
if (!hEMF2.Equals(new IntPtr(0)))
{
if (OpenClipboard(hWnd))
{
if (EmptyClipboard())
{
IntPtr hRes = default(IntPtr);
hRes = SetClipboardData(14, hEMF2);
bResult = hRes.Equals(hEMF2);
CloseClipboard();
}
}
}
DeleteEnhMetaFile(hEMF);
}
return bResult;
}
public static Image GetEnhMetafileFromClipboard(IntPtr hWnd)
{
OpenClipboard(hWnd);
IntPtr hemf = GetClipboardData(14);
CloseClipboard();
if (hemf != IntPtr.Zero)
{
Metafile mf = new Metafile(hemf, true);
Bitmap b = new Bitmap(mf.Width, mf.Height);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(Brushes.White, 0, 0, 1000, 1000);
GraphicsUnit unit = GraphicsUnit.Millimeter;
RectangleF rsrc = mf.GetBounds(ref unit);
g.DrawImage(mf, new Rectangle(0, 0, mf.Width, mf.Height), rsrc, unit);
return b;
}
return null;
}
}
|
|
|
|
|