|
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;
}
}
|
|
|
|
|
|
thank you any good sample code?
|
|
|
|
|
Most likely, yes. But you will probably learn more by using the documentation.
|
|
|
|
|
Will give a try but it´s not easy for me
normal copy from clipboard work´s fine
if (Clipboard.ContainsImage())
{
picSample.Image = Clipboard.GetImage();
picSample.Visible = true;
picSample.Image.Save(@"c:\abc.png" );
for
CF_ENHMETAFILE=14 is the problem
|
|
|
|
|
|
after some seach i came to this solucion but quality image saved is very low please advise.
Metafile emf = null;
if (OpenClipboard(IntPtr.Zero))
{
if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
{
var ptr = GetClipboardData(CF_ENHMETAFILE);
if (!ptr.Equals(IntPtr.Zero))
emf = new Metafile(ptr, true);
emf.Save(@"c:\image1.png");
}
CloseClipboard();
}
|
|
|
|
|
|
I'm having trouble using TLS1.2 with smtp.gmail.com and authenticating; gmail keeps saying that I'm not authenticating correctly.
Not sure if I'm using the ServicePointManager correctly at this point.
So I'm using smtp.gmail.com on port 587 with ssl enabled.
This is what I have. The SmtpClient runs first and picks up the credentials, the the SendEmailAsync runs and sends. The Catch catched the exception saying that I wasn't authenticated.
Scratching my head on this.
public static SmtpClient create_SMTPClient(smtp_credentials smtpC)
{
var smtpClient = new SmtpClient();
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
if (smtpSection == null)
{
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
<pre>
var smtpCredentials = new System.Net.NetworkCredential() {
UserName = smtpC.smtp_AccountName,
Password = smtpC.smtp_Password
};
smtpClient.Credentials = smtpCredentials;
smtpClient.Host = smtpC.smtp_ServerUrl;
smtpClient.Port = smtpC.smtp_PortNumber;
smtpClient.EnableSsl = smtpC.smtp_PortNumber == 587 ? true : false;
smtpClient.Timeout = 250000;
}
if (smtpClient.Port == 587)
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (smtpClient.Port == 443)
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidation_Callback;
return smtpClient;
}
public static async Task<SendEmailCompletedEventArgs> sendEmailAsync(SmtpClient smtpClient, MailMessage message, int retryCount)
{
int currentTry = 0;
while ((currentTry < retryCount))
{
try
{
await smtpClient.SendMailAsync(message);
return new SendEmailCompletedEventArgs(null, false, null, currentTry);
}
catch (Exception ex)
{
currentTry++;
if ((currentTry >= retryCount))
{
return new SendEmailCompletedEventArgs(ex, true, null, currentTry);
}
}
}
return new SendEmailCompletedEventArgs(null, true, null, currentTry);
}</pre>
If it ain't broke don't fix it
|
|
|
|
|
I think my issue here is I need to connect as TLS1.2 but it's connecting as TLS1.1, in which Gmail considers to be less secure.
So the Service point stepped down a notch and my code failed.
So I wonder if it's a cipher in my registry on SChannel or my protocols that I selected.
If it ain't broke don't fix it
|
|
|
|
|
Which OS? TLS1.2 was disabled by default prior to 8.1 / 2012 R2, and not available on Vista / 2008 or earlier.
You should be able to check whether it's enabled from the IE options dialog, on the "Advanced" page:
Support for SSL/TLS protocols on Windows – Unleashed[^]
AFAIK, those settings also affect .NET code.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Developing on Win10 with VS2017.
I program the ServicePointManager, and in the SmtpClient it says the address threw an exception before I even call SendMailAsync
The after the SendMailAsync runs, the caught Exception says must StartTLS first.
My endpoint is smtp.gmail.com on 587 with ssl on and using .Net 4.6.1
Strange, but after calling SendEmailAsync, it reads the SmtpCreddentials again and call Send a 2nd time.
I think it works in my VB version using .Net 4.6.1
If it ain't broke don't fix it
|
|
|
|
|
I changed my Gmail account type to less secure and it works fine with the same settings.
I wonder what the difference is between secure and less secure, I mean the whole difference is.
I hear .Net 4.6.2 is suppose to fix this for secure app.
If it ain't broke don't fix it
|
|
|
|
|
how to make calculation based on the quantity that user key in with the data(column) in the excel file that we link in c# ?
|
|
|
|
|
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind.
What have you tried?
Where are you stuck?
What help do you need?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
ok. sorry 4 that. i just think maybe some of u have example that can be shared
|
|
|
|
|
It's possible we do - but if we have no idea what you are talking about (because you gave us no information) then it's unlikely that we can tell you!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|