How to scroll down while page loading - GeckoFx C# - c#

I want to scroll down while a page loading in geckofx 45.
I tried to to do with following code, but it seems not to work.
wb.Navigate("javascript: var s = function() { window.scrollBy(550, 10000); }; s();");
How is that possible?

int scrollTo = 30;
public void scrollDown()
{
this.wb.Focus();
string result = string.Empty;
AutoJSContext context;
string jsScript = string.Empty;
try
{
if (scrollTo > 100)
{
scrollTo = 5;
}
context = new AutoJSContext(this.wb.Window);
jsScript = "var x = document.getElementsByClassName('ANY_ELEMENTS_CLASS_NAME'); x[" + (scrollTo * 2) + "].scrollIntoView(); ";// CHANGE ANY_ELEMENTS_CLASS_NAME
context.EvaluateScript(jsScript, (nsISupports)wb.Window.DomWindow, out result);
scrollTo += 5;
}
catch (Exception e)
{
}
}
this helped me

Related

loop use async or thread instead of timer

Sorry for my little English
I have a problem
Instead of the timer, I need to run the codes below in a loop.
can you help me with this
my main purpose
to use thread or async
if (NumbersIndexCounter != PhoneNumbersList.Count)
{
SendMessage(PhoneNumbersList[NumbersIndexCounter++]);
}
lblFailedProcess.Text = FailedProcess.ToString();
lblSuccedProcess.Text = SuccedProcess.ToString();
//metroLabel2.Text = toplamprocess.ToString();
Thread.Sleep(2000);
dataGridİnfos.DataSource = "";
dataGridİnfos.DataSource = InfoList;
Thread.Sleep(Convert.ToInt16(txtWaitBeforeEveryMessage.Text)*1000);
ProcessCounter++;
if (NumbersIndexCounter == PhoneNumbersList.Count)
{
int s1, s2;
s1 = Convert.ToInt32(lblFailedProcess.Text);
s2 = Convert.ToInt32(lblSuccedProcess.Text);
int toplam = s1 + s2;
metroLabel2.Text = "Toplam = " + toplam;
timer1.Stop();
Driver.Quit();
MessageBox.Show("Bitti!");
NumbersIndexCounter = 0;
grpBxMessage.Enabled = true;
grpBxPhoneNumbers.Enabled = true;
grpBxSettings.Enabled = true;
PhoneNumbersList.Clear();
}
if (ProcessCounter == Convert.ToInt32(txtMessageCountForWait.Text))
{
Thread.Sleep(Convert.ToInt16(txtWait.Text) * 1000);
ProcessCounter = 0;
}
but when I use a private void in my codes, it works once and does not continue. When I use a timer, it works without any problems, but the form is not response.

I tried to modify the IL of the System.String.Concat method through the ICorProfilerCallback interface, but something went wrong

I try to modify the IL of the System.String.Concat method through the ICorProfilerCallback interface, and add my own tracking code before the method is executed。
I modified the IL of other methods and added the tracking code without any problems. After the compilation passed, it can be run.
....
if (!isStatic) {
reWriterWrapper.LoadNull();// Ldnull
reWriterWrapper.StLocal(indexMethodTrace); //stloc
reWriterWrapper.LoadNull(); //Ldnull
reWriterWrapper.StLocal(indexEx);
reWriterWrapper.LoadNull();
reWriterWrapper.StLocal(indexRet);
ILInstr* pTryStartInstr = reWriterWrapper.CallMember0(getInstanceMemberRef, false);
reWriterWrapper.Cast(traceAgentTypeRef); //castclass
reWriterWrapper.LoadToken(functionInfo.type.id);//ldtoken
reWriterWrapper.CallMember(moduleMetaInfo->getTypeFromHandleToken, false);
reWriterWrapper.LoadArgument(0); //ldarg 0
auto argNum = functionInfo.signature.NumberOfArguments();
reWriterWrapper.CreateArray(objectTypeRef, argNum);
auto arguments = functionInfo.signature.GetMethodArguments();
for (unsigned i = 0; i < argNum; i++) {
reWriterWrapper.BeginLoadValueIntoArray(i);
reWriterWrapper.LoadArgument(i + 1);//ldarg
auto argTypeFlags = arguments[i].GetTypeFlags(elementType);
if (argTypeFlags & TypeFlagByRef) {
reWriterWrapper.LoadIND(elementType); //ldind 中
}
if (argTypeFlags & TypeFlagBoxedType) {
auto tok = arguments[i].GetTypeTok(pEmit, corLibAssemblyRef); /
if (tok == mdTokenNil) {
return S_OK;
}
reWriterWrapper.Box(tok);
}
reWriterWrapper.EndLoadValueIntoArray(); //stelem_ref
}
reWriterWrapper.LoadInt32((INT32)function_token); //ldc_i4
reWriterWrapper.CallMember(beforeMemberRef, true); // call
reWriterWrapper.Cast(methodTraceTypeRef); //Castclass
reWriterWrapper.StLocal(rewriter.cNewLocals - 1); //STLOC
ILInstr* pRetInstr = pReWriter->NewILInstr();
pRetInstr->m_opcode = CEE_RET;
pReWriter->InsertAfter(pReWriter->GetILList()->m_pPrev, pRetInstr);
bool isVoidMethod = (retTypeFlags & TypeFlagVoid) > 0;
auto ret = functionInfo.signature.GetRet();
bool retIsBoxedType = false;
mdToken retTypeTok;
if (!isVoidMethod) {
retTypeTok = ret.GetTypeTok(pEmit, corLibAssemblyRef);
if (ret.GetTypeFlags(elementType) & TypeFlagBoxedType) {
retIsBoxedType = true;
}
}
reWriterWrapper.SetILPosition(pRetInstr);
reWriterWrapper.StLocal(indexEx); //stloc
ILInstr* pRethrowInstr = reWriterWrapper.Rethrow(); //Rethrow
reWriterWrapper.LoadLocal(indexMethodTrace); //ldloc
ILInstr* pNewInstr = pReWriter->NewILInstr(); //Brfalse
pNewInstr->m_opcode = CEE_BRFALSE_S;
pReWriter->InsertBefore(pRetInstr, pNewInstr);
reWriterWrapper.LoadLocal(indexMethodTrace); //ldloc
reWriterWrapper.LoadLocal(indexRet);//ldloc
reWriterWrapper.LoadLocal(indexEx); //ldloc
reWriterWrapper.CallMember(endMemberRef, true); // call [
ILInstr* pEndFinallyInstr = reWriterWrapper.EndFinally();
pNewInstr->m_pTarget = pEndFinallyInstr;
if (!isVoidMethod) {
reWriterWrapper.LoadLocal(indexRet);//ldloc
if (retIsBoxedType) {
reWriterWrapper.UnboxAny(retTypeTok);
}
else {
reWriterWrapper.Cast(retTypeTok);
}
}
for (ILInstr* pInstr = pReWriter->GetILList()->m_pNext; pInstr != pReWriter->GetILList(); pInstr = pInstr->m_pNext) {
switch (pInstr->m_opcode)
{
case CEE_RET:
{
if (pInstr != pRetInstr) {
if (!isVoidMethod) {
reWriterWrapper.SetILPosition(pInstr);
if (retIsBoxedType) {
reWriterWrapper.Box(retTypeTok);
}
reWriterWrapper.StLocal(indexRet); //ldloc
}
pInstr->m_opcode = CEE_LEAVE_S; //Leave_S
pInstr->m_pTarget = pEndFinallyInstr->m_pNext;
}
break;
}
default:
break;
}
}
EHClause exClause{};
exClause.m_Flags = COR_ILEXCEPTION_CLAUSE_NONE;
exClause.m_pTryBegin = pTryStartInstr;
exClause.m_pTryEnd = pRethrowInstr->m_pPrev;
exClause.m_pHandlerBegin = pRethrowInstr->m_pPrev;
exClause.m_pHandlerEnd = pRethrowInstr;
exClause.m_ClassToken = exTypeRef;
EHClause finallyClause{};
finallyClause.m_Flags = COR_ILEXCEPTION_CLAUSE_FINALLY;
finallyClause.m_pTryBegin = pTryStartInstr;
finallyClause.m_pTryEnd = pRethrowInstr->m_pNext;
finallyClause.m_pHandlerBegin = pRethrowInstr->m_pNext;
finallyClause.m_pHandlerEnd = pEndFinallyInstr;
auto m_pEHNew = new EHClause[rewriter.m_nEH + 2];
for (unsigned i = 0; i < rewriter.m_nEH; i++) {
m_pEHNew[i] = rewriter.m_pEH[i];
}
rewriter.m_nEH += 2;
m_pEHNew[rewriter.m_nEH - 2] = exClause;
m_pEHNew[rewriter.m_nEH - 1] = finallyClause;
rewriter.m_pEH = m_pEHNew;
}
else
{
//static method
reWriterWrapper.LoadNull();// Ldnull
reWriterWrapper.StLocal(indexMethodTrace); //stloc
reWriterWrapper.LoadNull(); //Ldnull
reWriterWrapper.StLocal(indexEx); //stloc
reWriterWrapper.LoadNull();// Ldnull
reWriterWrapper.StLocal(indexRet);
ILInstr* pTryStartInstr = reWriterWrapper.CallMember0(getInstanceMemberRef, false);
reWriterWrapper.Cast(traceAgentTypeRef); //castclass
reWriterWrapper.LoadNull(); //ldstr
reWriterWrapper.LoadNull();
auto argNum = functionInfo.signature.NumberOfArguments();
reWriterWrapper.CreateArray(objectTypeRef, argNum); //newarr
auto arguments = functionInfo.signature.GetMethodArguments();
for (unsigned i = 0; i < argNum; i++) {
reWriterWrapper.BeginLoadValueIntoArray(i);
reWriterWrapper.LoadArgument(i);//ldarg Static index 0
auto argTypeFlags = arguments[i].GetTypeFlags(elementType);
if (argTypeFlags & TypeFlagByRef) {
reWriterWrapper.LoadIND(elementType); //ldind
}
if (argTypeFlags & TypeFlagBoxedType) {
auto tok = arguments[i].GetTypeTok(pEmit, corLibAssemblyRef);
if (tok == mdTokenNil) {
return S_OK;
}
reWriterWrapper.Box(tok);
}
reWriterWrapper.EndLoadValueIntoArray(); //stelem_ref
}
reWriterWrapper.LoadInt32((INT32)function_token); //ldc_i4
reWriterWrapper.CallMember(beforeMemberRef, true); // call
reWriterWrapper.Cast(methodTraceTypeRef); //Castclass
reWriterWrapper.StLocal(rewriter.cNewLocals - 1); //STLOC
ILInstr* pRetInstr = pReWriter->NewILInstr();/
pRetInstr->m_opcode = CEE_RET;
pReWriter->InsertAfter(pReWriter->GetILList()->m_pPrev, pRetInstr);
bool isVoidMethod = (retTypeFlags & TypeFlagVoid) > 0;
auto ret = functionInfo.signature.GetRet();
bool retIsBoxedType = false;
mdToken retTypeTok;
if (!isVoidMethod) {
retTypeTok = ret.GetTypeTok(pEmit, corLibAssemblyRef);
if (ret.GetTypeFlags(elementType) & TypeFlagBoxedType) {
retIsBoxedType = true;
}
}
reWriterWrapper.SetILPosition(pRetInstr);
reWriterWrapper.StLocal(indexEx); //stloc
ILInstr* pRethrowInstr = reWriterWrapper.Rethrow(); //Rethrow
reWriterWrapper.LoadLocal(indexMethodTrace); //ldloc
ILInstr* pNewInstr = pReWriter->NewILInstr(); //Brfalse
pNewInstr->m_opcode = CEE_BRFALSE_S;
pReWriter->InsertBefore(pRetInstr, pNewInstr);
reWriterWrapper.LoadLocal(indexMethodTrace); //ldloc
reWriterWrapper.LoadLocal(indexRet);//ldloc
reWriterWrapper.LoadLocal(indexEx); //ldloc
reWriterWrapper.CallMember(endMemberRef, true); // call
ILInstr* pEndFinallyInstr = reWriterWrapper.EndFinally(); //Endfinally
pNewInstr->m_pTarget = pEndFinallyInstr;
if (!isVoidMethod) {
reWriterWrapper.LoadLocal(indexRet);//ldloc
if (retIsBoxedType) {
reWriterWrapper.UnboxAny(retTypeTok); // Unbox_Any
}
else {
reWriterWrapper.Cast(retTypeTok);
}
}
for (ILInstr* pInstr = pReWriter->GetILList()->m_pNext; pInstr != pReWriter->GetILList(); pInstr = pInstr->m_pNext) {
switch (pInstr->m_opcode)
{
case CEE_RET:
{
if (pInstr != pRetInstr) {
if (!isVoidMethod) {
reWriterWrapper.SetILPosition(pInstr);
if (retIsBoxedType) {
reWriterWrapper.Box(retTypeTok);
}
reWriterWrapper.StLocal(indexRet); //ldloc
}
pInstr->m_opcode = CEE_LEAVE_S; //Leave_S
pInstr->m_pTarget = pEndFinallyInstr->m_pNext;
}
break;
}
default:
break;
}
}
EHClause exClause{};
exClause.m_Flags = COR_ILEXCEPTION_CLAUSE_NONE;
exClause.m_pTryBegin = pTryStartInstr;
exClause.m_pTryEnd = pRethrowInstr->m_pPrev;
exClause.m_pHandlerBegin = pRethrowInstr->m_pPrev;
exClause.m_pHandlerEnd = pRethrowInstr;
exClause.m_ClassToken = exTypeRef;
EHClause finallyClause{};
finallyClause.m_Flags = COR_ILEXCEPTION_CLAUSE_FINALLY;
finallyClause.m_pTryBegin = pTryStartInstr;
finallyClause.m_pTryEnd = pRethrowInstr->m_pNext;
finallyClause.m_pHandlerBegin = pRethrowInstr->m_pNext;
finallyClause.m_pHandlerEnd = pEndFinallyInstr;
auto m_pEHNew = new EHClause[rewriter.m_nEH + 2];
for (unsigned i = 0; i < rewriter.m_nEH; i++) {
m_pEHNew[i] = rewriter.m_pEH[i];
}
rewriter.m_nEH += 2;
m_pEHNew[rewriter.m_nEH - 2] = exClause;
m_pEHNew[rewriter.m_nEH - 1] = finallyClause;
rewriter.m_pEH = m_pEHNew;
}
hr = rewriter.Export();
....
LocalSigCode
HRESULT ModifyLocalSig(CComPtr<IMetaDataImport2>& pImport, CComPtr<IMetaDataEmit2>& pEmit, ILRewriter& reWriter, mdTypeRef exTypeRef,mdTypeRef methodTraceTypeRef)
{
HRESULT hr;
PCCOR_SIGNATURE rgbOrigSig = NULL;
ULONG cbOrigSig = 0;
UNALIGNED INT32 temp = 0;
if (reWriter.m_tkLocalVarSig != mdTokenNil)
{
IfFailRet(pImport->GetSigFromToken(reWriter.m_tkLocalVarSig, &rgbOrigSig, &cbOrigSig));
const auto len = CorSigCompressToken(methodTraceTypeRef, &temp);
if(cbOrigSig - len > 0){
if(rgbOrigSig[cbOrigSig - len -1]== ELEMENT_TYPE_CLASS){
if (memcmp(&rgbOrigSig[cbOrigSig - len], &temp, len) == 0) {
return E_FAIL;
}
}
}
}
auto exTypeRefSize = CorSigCompressToken(exTypeRef, &temp);
auto methodTraceTypeRefSize = CorSigCompressToken(methodTraceTypeRef, &temp);
ULONG cbNewSize = cbOrigSig + 1 + 1 + methodTraceTypeRefSize + 1 + exTypeRefSize;
ULONG cOrigLocals;
ULONG cNewLocalsLen;
ULONG cbOrigLocals = 0;
if (cbOrigSig == 0) {
cbNewSize += 2;
reWriter.cNewLocals = 3;
cNewLocalsLen = CorSigCompressData(reWriter.cNewLocals, &temp);
}
else {
cbOrigLocals = CorSigUncompressData(rgbOrigSig + 1, &cOrigLocals);
reWriter.cNewLocals = cOrigLocals + 3;
cNewLocalsLen = CorSigCompressData(reWriter.cNewLocals, &temp);
cbNewSize += cNewLocalsLen - cbOrigLocals;
}
auto rgbNewSig = new COR_SIGNATURE[cbNewSize];
*rgbNewSig = IMAGE_CEE_CS_CALLCONV_LOCAL_SIG;
ULONG rgbNewSigOffset = 1;
memcpy(rgbNewSig + rgbNewSigOffset, &temp, cNewLocalsLen);
rgbNewSigOffset += cNewLocalsLen;
if (cbOrigSig > 0) {
const auto cbOrigCopyLen = cbOrigSig - 1 - cbOrigLocals;
memcpy(rgbNewSig + rgbNewSigOffset, rgbOrigSig + 1 + cbOrigLocals, cbOrigCopyLen);
rgbNewSigOffset += cbOrigCopyLen;
}
rgbNewSig[rgbNewSigOffset++] = ELEMENT_TYPE_OBJECT;
rgbNewSig[rgbNewSigOffset++] = ELEMENT_TYPE_CLASS;
exTypeRefSize = CorSigCompressToken(exTypeRef, &temp);
memcpy(rgbNewSig + rgbNewSigOffset, &temp, exTypeRefSize);
rgbNewSigOffset += exTypeRefSize;
rgbNewSig[rgbNewSigOffset++] = ELEMENT_TYPE_CLASS;
methodTraceTypeRefSize = CorSigCompressToken(methodTraceTypeRef, &temp);
memcpy(rgbNewSig + rgbNewSigOffset, &temp, methodTraceTypeRefSize);
rgbNewSigOffset += methodTraceTypeRefSize;
IfFailRet(pEmit->GetTokenFromSig(&rgbNewSig[0], cbNewSize, &reWriter.m_tkLocalVarSig));
return S_OK;
}
Modification method template:
//before fixing method
private Task DataRead(string a, int b)
{
return Task.Delay(10);
}
//After modification
private Task DataReadWrapper(string a, int b)
{
object ret = null;
Exception ex = null;
MethodTrace methodTrace = null;
try
{
methodTrace = (MethodTrace)((TraceAgent)TraceAgent.GetInstance())
.BeforeMethod(this.GetType(), this, new object[]{ a, b }, functiontoken);
ret = Task.Delay(10);
goto T;
}
catch (Exception e)
{
ex = e;
throw;
}
finally
{
if (methodTrace != null)
{
methodTrace.EndMethod(ret, ex);
}
}
T:
return (Task)ret;
}
Error:
Unhandled exception.
Cannot print exception string because Exception.ToString() failed.
Application '/LM/W3SVC/1/ROOT' with physical root 'C:\inetpub\wwwroot\DotNetRangeCore\' failed to load coreclr. Exception message: CLR worker thread exited prematurely
There is no problem if I modify the IL through this code in other methods。such as:set_CommandText、System.Random.Next、System.Web.HttpContext.FinishPipelineRequest....
I don’t know why it would be wrong to modify Concat。
I solved it by replacing it. If an error is reported after this IL is modified, I replaced it with a packaging method.

How to show an informative real time progress data during long server process

I have a so long process may take 1 hour .
This process consists of many steps run from year to year .My main problem is :
How to provide an informative real time progress to the end user during the process not just a dummy loading bar.
int index = Convert.ToInt32(e.CommandArgument);
bool done = false;
int res = -1;
int fromVal = int.Parse(gv_balance.Rows[index].Cells[0].Text);
int toVal = int.Parse(gv_balance.Rows[index].Cells[1].Text);
int finMonth = 1;
int finYear = 0;
int EndServ = 0;
int calcYear = int.Parse(gv_balance.Rows[index].Cells[2].Text);
int total;
total = ((toVal - fromVal) + 1);
string msg = string.Empty;
int confirm = Balance.GetConfirmState(calcYear);
if (confirm == 0)
{
RadProgressContext progress = RadProgressContext.Current;
progress.Speed = "N/A";
finYear = fromVal;
for (int i = fromVal; i <= toVal; i++)
{
decimal ratio;
//Load New Employees
if (toVal - fromVal > 0)
{
ratio = ((decimal)toVal - i) / (toVal - fromVal) * 100;
}
else
{
ratio = ((decimal)toVal - i) / 1 * 100;
}
progress.PrimaryTotal = total;
progress.PrimaryValue = total;
progress.PrimaryPercent = 100;
progress.SecondaryTotal = 100; // total;
progress.SecondaryValue = ratio;//i ;
progress.SecondaryPercent = ratio; //i;
progress.CurrentOperationText = "Step " + i.ToString();
if (!Response.IsClientConnected)
{
//Cancel button was clicked or the browser was closed, so stop processing
break;
}
progress.TimeEstimated = (toVal - i) * 100;
//Stall the current thread for 0.1 seconds
System.Threading.Thread.Sleep(100);
EndServ = i + 1;
if (i == fromVal)
{
//--->STEP1
//Load intial data
int intial = Balance.PrepareIntialData(calcYear);
//--->STEP2
res = Balance.CalcEndServed(calcYear, EndServ - 1, 6, 30);
}
//--->STEP3
int newEmps = Balance.PrepareNewEmployees(calcYear, i);
for (int j = 0; j < 2; j++)
{
if (j == 0)
{
finMonth = 7;
finYear = i;
}
else
{
finMonth = 1;
finYear = i + 1;
}
//--->STEP4
int promotion1 = Balance.PreparePromotionFirst(finYear, finMonth, calcYear);
//--->STEP5
int promotion2 = Balance.PreparePromotionSecond(finYear, finMonth, calcYear);
//--->STEP6
int appointment1 = Balance.PrepareAppointmentFirst(finYear, finMonth, calcYear);
//--->STEP7
int appointment2 = Balance.PrepareAppointmentSecond(finYear, finMonth, calcYear);
//--->STEP8
int bonus = Balance.PrepareBonus(finMonth, finYear, 0, calcYear);
//--->STEP9
int salary = Balance.PrepareSalary(finYear, finMonth, calcYear);
(((CheckBox)gv_balance.Rows[index].Cells[3].FindControl("chk_redirect")).Checked == true)
{
//--->STEP9
int acco = Balance.PrepareFinanceAccount(finYear, finMonth, calcYear);
}
}
//--->STEP10
res = Balance.CalcEndServed(calcYear, EndServ, 6, 30);
Balance.CalcStudy(calcYear);
UpdateProgressContext();
if (res < 0)
{
success_lb.Visible = false;
error_lb.Visible = true;
error_lb.Text = "ERROR";
}
else
{
done = true;
success_lb.Visible = true;
error_lb.Visible = false;
success_lb.Text = "Success";
}
}
}
I want to show the current step for example :
(Promotion 1 ) in ---> 1-2018 and the percentage of the whole process beside the estimated time .
To report progress of a very long task using signalR you can do something like this (it's only an example to show how it can work):
Server part
We start by mapping SignalR.
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
We create a hub class (don't forget to install the signalr package):
(If you want to report progress to all connected users or a specific group of users take a look here : http://www.asp.net/signalr/overview/guide-to-the-api/working-with-groups)
In the given example it report progress only to the caller of the Start function.
public class MyHub : Hub
{
public void Start(string arg)
{
Task.Run(() =>
{
AVeryLongTask();
});
}
//simulate a long task
void AVeryLongTask()
{
for (int i = 0; i < 10000; i++)
{
Thread.Sleep(100);
Clients.Caller.ReportProgress("AVeryLongTask", i * 100 / 10000);
}
}
}
Client Part
In the html you must add these references :
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-2.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
and now the Js part to get the progress from the hub :
$(function() {
// Declare a proxy to reference the hub.
var hub = $.connection.myHub;
// Create a function that the hub can call to report progress.
hub.client.reportProgress = function(functionName, progress) {
$('#progression').append('<li><strong>' + progress + '</strong>: ' + functionName + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function() {
$('#startlongprocess').click(function() {
//start the long process
hub.server.start("arg");
alert("started");
});
});
});
The html container for the progress and the start button :
<div class="container">
<input type="button" id="startlongprocess" value="Send" />
<ul id="progression"></ul>
</div>
If you need more explanations don't hesitate to ask.
( My example is based on this one http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr from signalr team )
You can use web sockets to push progress updates down to the client. SignalR is a dotnet library that wraps websockets and falls back where websockets isn't available. There are comprehensive examples online showing how to implement progress reporting using SignalR so no need to repeat them. Have a look here:
https://github.com/dragouf/SignalR.Progress
or here:
https://www.safaribooksonline.com/blog/2014/02/06/server-side-signalr/
for examples.
Here is a simplification of your problem that I think will solve your problem. If you run your long operation in a task, you can update the application with a status object. If your application is WPF, and you bind the status, it will update automatically. In WinForms, you can bind or just implement the event handler.
void Main()
{
var status = new Status();
object locker = new object();
status.PropertyChanged += Status_PropertyChanged;
//
// Long running job in a task
//
var task = new Task((s) =>
{
for(int i = 0; i < 1000; i++)
{
Task.Delay(TimeSpan.FromSeconds(5)).Wait();
//Thread.Sleep(5000);
lock (locker)
{
status.Message = string.Format("Iteration: {0}", i);
}
}
}, status);
//
// start and wait for the task to complete. In a real application, you may end differently
task.Start();
task.Wait();
}
static void Status_PropertyChanged(object sender,
PropertyChangedEventArgs e)
{
var s = sender as Status;
if(s != null && string.Equals(e.PropertyName, "Message"))
{
Console.WriteLine( s.Message);
}
}
public class Status : PropertyNotifier
{
private string _Message = string.Empty;
public string Message
{
get { return _Message; }
set { SetField(ref _Message, value); }
}
}
public abstract class PropertyNotifier : INotifyPropertyChanged, INotifyPropertyChanging
{
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged; // ? = new Delegate{};
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanging(string propertyName)
{
PropertyChangingEventHandler handler = PropertyChanging;
if (handler != null) handler(this, new PropertyChangingEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
OnPropertyChanging(propertyName);
field = value;
OnPropertyChanged(propertyName);
return true;
}
}

error CS0246: The type or namespace name `AForge' could not be found. Are you missing a using directive or an assembly reference?

I'm trying to make a n-Queens with Genetic Algorithm in Unity3D, but this error appears everytime...
code:
using UnityEngine;
using System;
using System.Collections;
using AForge.Genetic;
using AForge.Math;
namespace AlgoritmoGenetico
{
public class GA : MonoBehaviour {
int populationSizeBox;
int iterationsBox;
int nRainhasBox;
int crossoverRateBox;
int motacaoRateBox;
int paradaBox;
//int selecao;
private String log = "";
private int nRainhas = 14;
private int nPopulacao = 14;
private int nGeracoes = 8000;
private int nParada = 100;
private double crossoverRate = 0.75;
private double mutationRate = 0.01;
// Use this for initialization
void Start () {
Iniciar ();
}
// Update is called once per frame
void Update () {
}
public void Iniciar(){
configuraAlgoritimo();
int selecao = 0; // definimos para o metodo roleta
ISelectionMethod metodoDeSelecao = (selecao == 0) ? (ISelectionMethod)new RouletteWheelSelection() :
(selecao == 1) ? (ISelectionMethod)new EliteSelection() :
(ISelectionMethod)new RankSelection();
AvaliadorDeRainhas avaliador = new AvaliadorDeRainhas();
Population populacao = new Population(nPopulacao, new ShortArrayChromosome(nRainhas, nRainhas - 1), avaliador, metodoDeSelecao);
populacao.CrossoverRate = crossoverRate;
populacao.MutationRate = mutationRate;
int iteracao = 0;
int pararEm = nParada;
while (iteracao < nGeracoes)
{
populacao.RunEpoch();
if (nParada > 0 && iteracao == pararEm)
{
atualizaDadosPara(iteracao, populacao);
pararEm += nParada;
}
if (populacao.BestChromosome.Fitness == nRainhas)
break;
iteracao++;
}
atualizaDadosPara(iteracao,populacao);
}
private void atualizaDadosPara(int iteracao,Population populacao)
{
log = "Geração: " + iteracao +
"\n Método de Seleção : " + populacao.SelectionMethod +
"\n Avaliação Média: " + populacao.FitnessAvg +
"\n Melhor Avaliação : " + populacao.FitnessMax +
"\n Melhor indivíduo: " + populacao.BestChromosome.ToString();
print (log);
}
private void configuraAlgoritimo(){
try
{
nPopulacao = Math.Max(10, Math.Min(100, int.Parse(populationSizeBox)));
}
catch
{
nPopulacao = 8;
}
try
{
nGeracoes = Math.Max(0, int.Parse(iterationsBox));
}
catch
{
nGeracoes = 100;
}
try
{
nRainhas = Math.Max(4, int.Parse(nRainhasBox));
}
catch
{
nRainhas = 8;
}
try
{
crossoverRate = Math.Max(0.0, int.Parse(crossoverRateBox));
}
catch
{
crossoverRate = 0.75;
}
try
{
mutationRate = Math.Max(0.0, int.Parse(motacaoRateBox));
}
catch
{
mutationRate = 0.01;
}
try
{
nParada = Math.Max(0, int.Parse(paradaBox));
}
catch
{
nParada = 0;
}
}
}
}
I've recreated the problem that occured in your case.
You're missing AForge.dll file in your project's \Assets folder.
DLL you are looking for should be located in AForge.NET Framework-x.x.x-(libs only)\Release folder that you probably have downloaded zipped from AForge.NET site.
If you still struggle to find it, consider redownloading whole package from choosing [ Download Libraries Only ]:
http://www.aforgenet.com/framework/downloads.html
I've also fixed some issues you had there. You don't need to cast int value with int.Parse() if it is declared as int already.
Just do Math.Max(x, y) etc with functions you are using.
Also you are not using anything from AForge.Math namespace. If that was intentional, consider removing using AForge.Math; as it's unused.

Broken C# else if returning error page

I am trying to work with if else statements for different things. I need one that pulls the value of a dropdown list to determine what the calculation will be, another that pulls the value of a check box and assigns a calculation, another for input validation for if the number exceeds 32, and the last to give me a value determined by the amount (up to 32) entered into the textbox. I think i've gotten the checkbox statement corrected (guideFee), and the input validation and the one that goes with it seem to be correct already, but I am having trouble assigning the constant decimal values to the dropdown list values and I don't understand why. I have the basetourRate = Convert.ToDecimal(riverTour) and the if statement that follows, but when I run the program I get an error page. I have pasted the whole code. If anyone could help me out i'd greatly appreciate it, thank you!
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butCalculate_Click(object sender, EventArgs e )
{
//1. Declare Variables
decimal totalBaseTourFee;
decimal totalGuideFee;
decimal totalWeekendSurcharge;
decimal subtotal;
decimal salesTaxCharge;
decimal totalCharge;
decimal baseTourRate;
decimal guideFee = 0m;
bool isGuidedTour;
int numberOfRafters;
int numberOfRaftsNeeded;
string riverTour;
string timeOfWeek;
string displayTotalBaseTourFee;
string displayNumberOfRaftsNeeded;
string displayTotalGuideFee;
string displayTotalWeekendSurcharge;
string displaySubtotal;
string displaySalesTaxCharge;
string displayTotalCharge;
const decimal FRENCH_BROAD = 40m;
const decimal NANTAHALA = 30m;
const decimal TUCK = 20m;
const decimal WEEKEND_SURCHARGE = 10M;
const decimal GUIDE_FEE = 35M;
const decimal SALES_TAX_RATE = .07M;
//2. Get Values
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
riverTour = ddlTour.SelectedValue;
isGuidedTour = chkGuided.Checked;
timeOfWeek = rblDay.SelectedValue;
Trace.Warn("numberOfRafters = " + numberOfRafters);
Trace.Warn(("isGuidedTour = " + isGuidedTour));
Trace.Warn("riverTour = " + riverTour);
Trace.Warn("timeOfWeek = " + timeOfWeek);
//Input Validation
if (numberOfRafters > 32)
{
Console.WriteLine("Sorry, we can't handle this large of a group!");
return;
}
//3. Do Calculations
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
if (isGuidedTour == true)
{
guideFee = GUIDE_FEE;
}
else if (!isGuidedTour == false)
{
guideFee = 0;
}
totalBaseTourFee = numberOfRafters * baseTourRate;
numberOfRaftsNeeded = numberOfRafters;
if (numberOfRafters <= 8)
{
numberOfRaftsNeeded = 1;
}
else if (numberOfRafters <= 16)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <= 24)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <=32)
{
numberOfRaftsNeeded = 4;
}
totalGuideFee = numberOfRaftsNeeded * guideFee;
totalWeekendSurcharge = numberOfRafters * WEEKEND_SURCHARGE;
subtotal = totalBaseTourFee + totalGuideFee + totalWeekendSurcharge;
salesTaxCharge = subtotal * SALES_TAX_RATE;
totalCharge = subtotal + salesTaxCharge;
//4. Display Results
displayTotalBaseTourFee = totalBaseTourFee.ToString("C") + "<br>";
displayNumberOfRaftsNeeded = numberOfRaftsNeeded.ToString("C") + "<br>";
displayTotalGuideFee = totalGuideFee.ToString("C") + "<br>";
displayTotalWeekendSurcharge = totalWeekendSurcharge.ToString("C") + "<br>";
displaySubtotal = subtotal.ToString("C") + "<br>";
displaySalesTaxCharge = salesTaxCharge.ToString("C") + "<br>";
displayTotalCharge = totalCharge.ToString("C") + "<br>";
lblTotalBaseTourFee.Text = displayTotalBaseTourFee;
lblNumberOfRafts.Text = displayNumberOfRaftsNeeded;
lblTotalGuideFee.Text = displayTotalGuideFee;
lblTotalWeekendSurcharge.Text = displayTotalWeekendSurcharge;
lblSubtotal.Text = displaySubtotal;
lblSalesTaxCharge.Text = displaySalesTaxCharge;
lblTotalCharge.Text = displayTotalCharge;
}
protected void butClear_Click(object sender, EventArgs e)
{
//Clear TextBox and Label
txtNumberOfRafters.Text = "";
lblTotalBaseTourFee.Text = "";
lblNumberOfRafts.Text = "";
lblTotalGuideFee.Text = "";
lblTotalWeekendSurcharge.Text = "";
lblSubtotal.Text = "";
lblSalesTaxCharge.Text = "";
lblTotalCharge.Text = "";
ddlTour.SelectedIndex = -1;
rblDay.SelectedIndex = -1;
chkGuided.Checked = false;
//Set focus back to name textbox
txtNumberOfRafters.Focus();
}
}
The one thing that sticks out to me is the Convert.ToDecimal(...) call.
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
You are attempting to convert a string to a decimal but then you are comparing that string to a string. My guess is that riverTour is not really a decimal and therefore you are getting an exception. Basically, the logic does not make sense. Convert.ToDecimal will throw an exception if it is not a valid decimal. Therefore, riverTour cannot contain a convertible value to decimal and a comparable value to FB/NH/TK. What exactly are you trying to accomplish? If you are trying to convert to decimal if it is valid and then check those 3 cases if it is not then you should look into decimal.TryParse(string, out decimal) https://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx. This might help you achieve what you are trying to do.
If the input is always numeric, then you should consider using NumericUpDown. Or, at the very least, use TryParse methods so you can tell if the input is valid or invalid.
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
Is also unsafe.

Categories