MsftDiscFormat2Data Event Handler - c#

I have successfully integrated IMAPI2 using Interop.cs into my application. I can burn CD/DVDs without any problem. However, the event handler for MsftDiscFormat2Data update does not work, so I can't get my progress bar moving.
Here is the code I found at codeproject website:
private void backgroundBurnWorker_DoWork(object sender, DoWorkEventArgs e)
{
MsftDiscRecorder2 discRecorder = null;
MsftDiscFormat2Data discFormatData = null;
try
{
//
// Create and initialize the IDiscRecorder2 object
//
discRecorder = new MsftDiscRecorder2();
var burnData = (BurnData)e.Argument;
discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId);
//
// Create and initialize the IDiscFormat2Data
//
discFormatData = new MsftDiscFormat2Data
{
Recorder = discRecorder,
ClientName = ClientName,
ForceMediaToBeClosed = _closeMedia
};
//
// Set the verification level
//
var burnVerification = (IBurnVerification)discFormatData;
burnVerification.BurnVerificationLevel = _verificationLevel;
//
// Check if media is blank, (for RW media)
//
object[] multisessionInterfaces = null;
if (!discFormatData.MediaHeuristicallyBlank)
{
multisessionInterfaces = discFormatData.MultisessionInterfaces;
}
//
// Create the file system
//
IStream fileSystem;
if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem))
{
e.Result = -1;
return;
}
//
// add the Update event handler
//
discFormatData.Update += discFormatData_Update;
//
// Write the data here
//
try
{
discFormatData.Write(fileSystem);
e.Result = 0;
}
catch (COMException ex)
{
e.Result = ex.ErrorCode;
MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
if (fileSystem != null)
{
Marshal.FinalReleaseComObject(fileSystem);
}
}
//
// remove the Update event handler
//
discFormatData.Update -= discFormatData_Update;
if (_ejectMedia)
{
discRecorder.EjectMedia();
}
}
catch (COMException exception)
{
//
// If anything happens during the format, show the message
//
MessageBox.Show(exception.Message);
e.Result = exception.ErrorCode;
}
finally
{
if (discRecorder != null)
{
Marshal.ReleaseComObject(discRecorder);
}
if (discFormatData != null)
{
Marshal.ReleaseComObject(discFormatData);
}
}
}
void discFormatData_Update([In, MarshalAs(UnmanagedType.IDispatch)] object sender, [In, MarshalAs(UnmanagedType.IDispatch)] object progress)
{
//
// Check if we've cancelled
//
if (backgroundBurnWorker.CancellationPending)
{
var format2Data = (IDiscFormat2Data)sender;
format2Data.CancelWrite();
return;
}
var eventArgs = (IDiscFormat2DataEventArgs)progress;
_burnData.task = BURN_MEDIA_TASK.BURN_MEDIA_TASK_WRITING;
// IDiscFormat2DataEventArgs Interface
_burnData.elapsedTime = eventArgs.ElapsedTime;
_burnData.remainingTime = eventArgs.RemainingTime;
_burnData.totalTime = eventArgs.TotalTime;
// IWriteEngine2EventArgs Interface
_burnData.currentAction = eventArgs.CurrentAction;
_burnData.startLba = eventArgs.StartLba;
_burnData.sectorCount = eventArgs.SectorCount;
_burnData.lastReadLba = eventArgs.LastReadLba;
_burnData.lastWrittenLba = eventArgs.LastWrittenLba;
_burnData.totalSystemBuffer = eventArgs.TotalSystemBuffer;
_burnData.usedSystemBuffer = eventArgs.UsedSystemBuffer;
_burnData.freeSystemBuffer = eventArgs.FreeSystemBuffer;
//
// Report back to the UI
//
backgroundBurnWorker.ReportProgress(0, _burnData);
}
Unfortunately, the update handler gets never called. I looked up everywhere on internet but could not find a solution. I saw some people with same problem but no one was able to answer.
The original code from Eric, http://www.codeproject.com/KB/miscctrl/imapi2.aspx?msg=2695517,
does work for some reason.
Can someone please help me?

I know, it's too late, but I've got the same problem with update callbacks.
Open Project->Properties->Application->Assembly Information and tick "Make Assembly COM-visible".

Related

How to implement multi threading on Text Adornment project VSIX

I am creating a VSIX project having TextAdornment features. Here when My CreateGeom() method executes, and try to run new Image{};, It throws exception The calling thread must be STA, because many UI components require this. I tried setting ApartmentState manually but no luck. Following is my code:
[STAThread]
internal async void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
string lang = getCurruntCodeLanguage();
if (lang.ToString() != "java" && lang.ToString() != "ts" && lang.ToString() != "js")
{
}
else
{
try
{
currentSnapshotText = this.view.TextBuffer.CurrentSnapshot.GetText();
this.currentSnapshotLinesList = this.view.TextBuffer.CurrentSnapshot.GetText().Split('\n');
foreach (string str in this.currentSnapshotLinesList.ToList<string>())
{
TextAdornment1.allLinesList.Add(str.Trim('\r'));
}
if (numberOfLinesBeforeEnter != this.currentSnapshotLinesList.Length)
{
boundstart = 0;
boundend = 0;
this.checkCountIfMarked = 1;
this.markthis.Clear();
if (this.image != null)
{
RemoveMarkedArea();
}
if (threadSendText != null)
{
if (threadSendText.IsAlive)
{
threadSendText.Abort();
}
}
var v = System.Threading.Thread.CurrentThread.GetApartmentState(); //returns 'STA'
threadSendText = new System.Threading.Thread(new ThreadStart(SndTextCall)); // Apartment State is 'Unknown'
threadSendText.SetApartmentState(ApartmentState.STA); // Apartment State is 'STA'
threadSendText.IsBackground = true;
threadSendText.Priority = ThreadPriority.Highest;
threadSendText.Start();
}
numberOfLinesBeforeEnter = this.currentSnapshotLinesList.Length;
}
catch (Exception exc)
{
//MessageBox.Show(exc.ToString());
}
}
}
There are other recursive methods also in SndTextCall(). All are working fine but when CreateGeom() method comes into execution, it throws an exception.
private void CreateGeom(SnapshotSpan span)
{
IWpfTextViewLineCollection textViewLines = this.view.TextViewLines;
this.geometry = textViewLines.GetMarkerGeometry(span);
if (this.geometry != null)
{
this.drawing = new GeometryDrawing(this.brush, this.pen, this.geometry);
this.drawing.Freeze();
var drawingImage = new DrawingImage(this.drawing);
drawingImage.Freeze();
image = new Image
{
Source = drawingImage,
}; // Here the exception comes
Canvas.SetLeft(image, this.geometry.Bounds.Left);
Canvas.SetTop(image, this.geometry.Bounds.Top);
this.drawingImageList.Add(image);
}
}
You can explicitly switch to the UI Thread using the VS Threading Rules or the explanations in the Cookbook for Visual Studio.
private void CreateGeom(SnapshotSpan span)
{
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// You're now on the UI thread.
// ... Create your image here
});
}

Answer and Hangup a call using TAPI3 C#

I'm stuck in TAPI programming. I've created a program to monitor activity of phone call. Everything is working fine, but now I want to implement a functionality to accept and reject a call from web directly.
what I've done is below:
namespace Shared
{
public partial class Site : System.Web.UI.MasterPage
{
public static ITAddress ln;
static int index = -1;
static int line;
static ITAddress[] ia;
protected void Page_Load(object sender, EventArgs e)
{
#region TAPI
TAPIClass tobj;
int[] registertoken;
tobj = new TAPI3Lib.TAPIClass();
tobj.Initialize();
IEnumAddress ea = tobj.EnumerateAddresses();
uint lines;
uint arg3 = 0;
int TotalLines = 0;
lines = 0;
foreach (TAPI3Lib.ITAddress ad in (tobj.Addresses as TAPI3Lib.ITCollection))
{
TotalLines++;
}
callnotification cn = new callnotification();
tobj.ITTAPIEventNotification_Event_Event += new TAPI3Lib.ITTAPIEventNotification_EventEventHandler(cn.Event);
tobj.EventFilter = (int)(TAPI_EVENT.TE_CALLNOTIFICATION |
TAPI_EVENT.TE_DIGITEVENT |
TAPI_EVENT.TE_PHONEEVENT |
TAPI_EVENT.TE_CALLSTATE |
TAPI_EVENT.TE_GENERATEEVENT |
TAPI_EVENT.TE_GATHERDIGITS |
TAPI_EVENT.TE_REQUEST);
registertoken = new int[TotalLines];
ia = new TAPI3Lib.ITAddress[TotalLines];
for (int i = 0; i = 0)
{
ln = ia[line];
}
IEnumCall ec = ln.EnumerateCalls();
uint arg = 0;
ITCallInfo ici;
try
{
ec.Next(1, out ici, ref arg);
ITBasicCallControl2 bc = (TAPI3Lib.ITBasicCallControl2)ici;
if (ici != null && ici.CallState == CALL_STATE.CS_OFFERING)
{
if (bc != null)
{
bc.Answer();
}
}
}
catch (Exception ex)
{
COMException comEx = ex as COMException;
if (comEx != null)
comEx.ErrorCode.ToString();
else
{
string aa = ex.Message;
}
}
//addtolist("Call Offering from " + callernumber + " to Ext " + viaextension + " via DID " + DIDNumber);
break;
case TAPI3Lib.CALL_STATE.CS_IDLE:
//addtolist("Call is created!");
break;
}
break;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.StackTrace.ToString());
}
}
}
#endregion
}
}
I'm always getting ITBasicCallControl2 bc NULL and when I press the Accept button, nothing happens.
Okay, so the first thing you have to do in order to successfully answer calls, is to register your line with owner rights.
tobj.RegisterCallNotifications(ln, true, true, TapiConstants.TAPIMEDIATYPE_AUDIO, 2);
After that, you can either iterate through every call using EnumerateCalls(), or you can implement the ITTAPIEventNotification interface to get notified if there is a change in callstate (for example).
One way or the other, at some point, you have found the call you want to answer. Now you need to make sure, that the call is in an alerting state (CS_OFFERING for inbound calls), before you can finally call the answer method.
try
{
ec.Next(1, out ici, ref arg);
if (ici != null && ici.CallState == CALL_STATE.CS_OFFERING)
{
ITBasicCallControl2 bc = (TAPI3Lib.ITBasicCallControl2)ici;
if (bc != null)
{
bc.Answer();
}
}
}
catch (Exception exp)
{
COMException comEx = exp as COMException;
if (comEx != null)
MessageBox.Show(comEx.ErrorCode.ToString());
else
MessageBox.Show(exp.Message);
}
If the call you want to answer is not in the callstate CS_CONNECTED, the method will throw a COMException with an error code of 0x800040010.
For further information on the ITTAPIEventNotification interface, see https://msdn.microsoft.com/en-us/library/windows/desktop/ms732506(v=vs.85).aspx
EDIT:
If you want to detect new incoming calls, I'd recommend to use the TE_CALLNOTIFICATION-Event, because it is triggered only once per new incoming call.
The TE_CALLSTATE-Event will be triggered every time the callstate changes.
Now, i've updated the callnotification class:
public class callnotification : TAPI3Lib.ITTAPIEventNotification
{
public InboundCall OnNewIncomingCall;
public void Event(TAPI_EVENT TapiEvent, object pEvent)
{
switch (TapiEvent)
{
case TAPI_EVENT.TE_CALLNOTIFICATION:
this.OnCallNotification((ITCallNotificationEvent)pEvent);
break;
}
}
private void OnCallNotification(ITCallNotificationEvent callNotification)
{
ITCallInfo ici = callNotification.Call;
if (ici != null && ici.CallState == CALL_STATE.CS_OFFERING)
this.OnNewIncomingCall(ici);
}
}
I've also declared a delegate Method to use if there is a new inbound call:
public delegate void InboundCall(ITCallInfo ici);
So your initialization of the callnotification event could look like this:
callnotification cn = new callnotification();
cn.OnNewIncomingCall += this.OnNewIncomingCall;
And finally, in the OnNewIncomingCallMethod, you can answer the call:
private void OnNewIncomingCall(ITCallInfo ici)
{
ITBasicCallControl bcc = (ITBasicCallControl)ici;
if (bcc != null)
{
string caller = ici.get_CallInfoString(CALLINFO_STRING.CIS_CALLERIDNUMBER);
DialogResult dlg = MessageBox.Show(string.Format("New incoming call from {0}\r\nDo you wish to answer the call now?", caller), "New incoming call", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlg == System.Windows.Forms.DialogResult.Yes)
bcc.Answer();
}
}
I've tested your code with the additions of mine and it worked fine. Should you be having any exceptions when answering or during the initialization, let me know.

LayoutSerializationCallback not be called

I'm using AvalonDock and I would serialize and deserialize my layout. But the callback (where I use the ContentId for create an instance of correct object) is not always called. For this reason the loaded not work correctly. I have tried to add one "try-catch", but not thrown exception.
This is my code:
` var layoutSerializer = new XmlLayoutSerializer(manager);
layoutSerializer.LayoutSerializationCallback += (s, e) =>
{
MyClass item;
if (items.TryGetValue(e.Model.ContentId, out item))
{
e.Content = item;
var tool = item as IMyClassToolApp;
var anchorable = e.Model as LayoutAnchorable;
var document = item as IMyClassDocumentApp;
var layoutDocument = e.Model as LayoutDocument;
if (tool != null && anchorable != null)
{
addToolCallback(tool);
tool.IsVisible = anchorable.IsVisible;
tool.IsSelected = e.Model.IsSelected;
return;
}
if (document != null && layoutDocument != null)
{
addDocumentCallback(document);
// Nasty hack to get around issue that occurs if documents are loaded from state,
// and more documents are opened programmatically.
layoutDocument.GetType().GetProperty("IsLastFocusedDocument").SetValue(layoutDocument, false, null);
document.IsVisible = true;
document.IsSelected = layoutDocument.IsSelected;
return;
}
}
e.Cancel = true;
};
try
{
layoutSerializer.Deserialize(stream);
}
catch
{
return false;
}`
Thank you for your help!
Are you sure your stream is O.K? If for example configuration file does not exist LayoutSerializationCallback method will not be called.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "MainWindow_Loaded");
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Jofta\Analyzer\configs\AvalonDock.config");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
XmlLayoutSerializer serializer = new XmlLayoutSerializer(this.dockingManager);
serializer.LayoutSerializationCallback += this.Serializer_LayoutSerializationCallback;
serializer.Deserialize(filePath);
}
MainWindow.logger.Debug("Exiting: {0}", "MainWindow_Loaded");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "MainWindow_Loaded");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
private void Serializer_LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "serializer_LayoutSerializationCallback");
if (e.Model.ContentId == ObjectExplorerViewModel.AnchorableContentId)
{
e.Content = Workspace.Instance.ObjectExplorer;
return;
}
// ...
// ...
MainWindow.logger.Debug("Exiting: {0}", "serializer_LayoutSerializationCallback");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "serializer_LayoutSerializationCallback");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}

Biometric finger scanner deserializing template from database C#

good day to all I just need some help. I was wondering if my code is correct so please guide if it is not. I have a Digital Personal Biometric Model U.ar.U 4500 using DPFP .NET (C#) SDK I was able to save the serialize template to Database ms-sql and I was wondering if the way a serialize is correct. If it is correct how do I deserialize and compare the data to the machine template. here is my code.
public void EnrollmentControl_OnEnroll(Object Control, int Finger, DPFP.Template
Template, ref DPFP.Gui.EventHandlerStatus Status) {
if (Data.IsEventHandlerSucceeds) {
byte[] by = new byte[0];
foreach (DPFP.Template template in Data.Templates)
{
if (template != null)
{
by = new byte[template.Bytes.Length];
template.Serialize(ref by);
string PP;
string CR;
PP = iSQL.STORED_PROCEDURE_FNG_IMG; // <- Stored Procedure INSERT INTO Employee_Img
CR = "AB-0001-R12";
iEmp emp = new iEmp(PP); // <- Class that insert to MS SQL
int rt = emp.Insert_Finger(CR, template.Bytes); // <- return 1 if Successfully
if (rt == 1) { iCon.success_mgs(1, "Successfully Inserted", iSQL.EMPLOYEE_REGISTRN); } //<- Popup message
else { iCon.success_mgs(1, "Successfully Inserted", iSQL.EMPLOYEE_REGISTRN); }
}
}
Data.Templates[Finger - 1] = Template; // store a finger template
ExchangeData(true); // update other data
ListEvents.Items.Insert(0, String.Format("OnEnroll: finger {0}", Finger));
}else
Status = DPFP.Gui.EventHandlerStatus.Failure; // force a "failure" status
}
I have faced with this problem, then I have fixed it already by following steps:
Example:
pgAdmin:
Table Name:
-tbl_fptable
DB Fields:
fp_id (int)
fp_data (text)
Insert Data to Database;
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Enrollment);
// Check quality of the sample and add to enroller if it's good
if (features != null) try
{
MakeReport("The fingerprint feature set was created.");
Enroller.AddFeatures(features); // Add feature set to template.
}
finally {
UpdateStatus();
// Check if template has been created.
switch (Enroller.TemplateStatus)
{
case DPFP.Processing.Enrollment.Status.Ready:
// report success and stop capturing
byte[] serializedTemplate = null;
string str_temp = null;
DateTime cur_date = DateTime.Now;
Enroller.Template.Serialize(ref serializedTemplate);
//Enroller.Template.Serialize(ref str_temp);
if (serializedTemplate != null)
{
string result = System.Text.Encoding.UTF8.GetString(serializedTemplate);
Console.Write(result);
try
{
using (NpgsqlConnection conn = new NpgsqlConnection("Host=127.0.0.1;Port=5432;User Id=UserName;Password=*****;Database=finger_print_db;"))
{
conn.Open();
NpgsqlCommand dbcmd = conn.CreateCommand();
try
{
// Store TemplateSerialize as string data
dbcmd.CommandText= "INSERT INTO tbl_fptable( fp_data ) VALUES ( #serializedTemplate )";
dbcmd.Parameters.AddWithValue("#serializedTemplate ", serializedTemplate);
dbcmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
OnTemplate(Enroller.Template);
SetPrompt("Click Close, and then click Fingerprint Verification.");
Stop();
break;
case DPFP.Processing.Enrollment.Status.Failed: // report failure and restart capturing
Enroller.Clear();
Stop();
UpdateStatus();
OnTemplate(null);
Start();
break;
}
}
}
Get Data from Database to verified
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
if (features != null)
{
try
{
using (NpgsqlConnection conn = new NpgsqlConnection("Host=127.0.0.1;Port=5432;User Id=UserName;Password=*****;Database=finger_print_db;"))
{
conn.Open();
try
{
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM tbl_fptable ORDER BY enr_id DESC LIMIT 1", conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
long fpid = Convert.ToInt64(dr["id"]);
byte[] fpbyte = (byte[])dr["finger_data"];
Stream stream = new MemoryStream(fpbyte );
DPFP.Template tmpObj = new DPFP.Template(stream);
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
// Compare the feature set with our template
Verificator.Verify(features, tmpObj, ref result);
UpdateStatus(result.FARAchieved);
if (result.Verified)
MakeReport("The fingerprint was VERIFIED.");
else
MakeReport("The fingerprint was NOT VERIFIED.");
}
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I hope this example can solve this stuck.
public class VerificationForm : CaptureForm
{
public void Verify(DPFP.Template template)
{
Template = template;
ShowDialog();
}
protected override void Init()
{
base.Init();
base.Text = "Fingerprint Verification";
Verificator = new DPFP.Verification.Verification(); // Create a fingerprint template verificator
UpdateStatus(0);
}
bool found = false; string fname = "";
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
if (features != null)
{
// Compare the feature set with our template
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
string[] flist = Directory.GetFiles("c:/finger");
int mx = flist.Length;
int cnt = 0;
bool found = false;
DPFP.Template templates;
while (cnt < mx && !found)
{
// MessageBox.Show(flist[cnt]);
using (FileStream fs = File.OpenRead(flist[cnt]))
{
templates = new DPFP.Template(fs);
Verificator.Verify(features, templates, ref result);
UpdateStatus(result.FARAchieved);
}
if (result.Verified)
{
found = true;
FileInfo nfo = new FileInfo(flist[cnt]);
fname = nfo.Name;
break;
}
else
{
found = false;
cnt++;
}
}
if (found)
{
MakeReport("The fingerprint was VERIFIED. "+fname);
MessageBox.Show("Verified!!");
}
else
{
MakeReport("The fingerprint was NOT VERIFIED.");
MessageBox.Show("Not Verified!!");
}
}
}
private void UpdateStatus(int FAR)
{
// Show "False accept rate" value
SetStatus(String.Format("False Accept Rate (FAR) = {0}", FAR));
}
private DPFP.Template Template;
private DPFP.Verification.Verification Verificator;
private void InitializeComponent()
{
this.SuspendLayout();
//
// VerificationForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.ClientSize = new System.Drawing.Size(693, 373);
this.Name = "VerificationForm";
this.Load += new System.EventHandler(this.VerificationForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}

Synchronization-Thread with Server every 5 secs

I have a server-client environment, where the client connects and synchronizes data with the server every 5 second.
For synchronizing I use a background thread on the client which works fine, but on one specific hardware the method GetNetworkAvailable throws out of memory exceptions occasionaly. The errors occur whitout logic, so I guess somethings just not good with this hardware. Anyways I'd like to get your opinion on my background - polling function.
private void SynchronizedWorker()
{
bool initialization = true;
int initializationTries = 0;
// Sync loop
while (!_shouldStop)
{
// Initialize locals
int syncInterval = _syncInterval; // Reset Sync Interval to default
SyncStatus syncStatus = SyncStatus; // Get current Status
bool hasNetworkConnection = true; // Has Network connection
try
{
//*******************************************
// Check Network connection
//*******************************************
if (!NetworkInterface.GetIsNetworkAvailable())
{
hasNetworkConnection = false;
_syncResetEvent.Set();
syncStatus = SyncStatus.Offline;
}
else if (syncStatus == SyncStatus.Offline) // Is in offline - State, but Network available again recognize going online
{
_syncResetEvent.Set();
hasNetworkConnection = IsServiceAvailable();
// Sync-Status stays offline
if (!hasNetworkConnection)
{
// Wait 1 minute, before retry
syncInterval = 60000;
}
}
//*******************************************
// Proceed with Syncronisation
//*******************************************
if (hasNetworkConnection)
{
syncStatus = SyncStatus.Ok;
// Try Initialization
if (initialization)
{
try
{
// Sync initialization here...
// ..............................
////////////////////////////////////
}
catch (Exception ex)
{
log.LogError(string.Format("Initialization Try {0}", initializationTries), ex);
syncStatus = SyncStatus.InitializationFailed;
}
}
// To many Init-Tries --> Stop
if (initializationTries > 1)
{
// Proceed
_syncResetEvent.Set();
_syncStatus = syncStatus;
break; // Stop Synch
}
// Debug
var sw = System.Diagnostics.Stopwatch.StartNew();
// Do Up/Download
if (!initialization)
{
try
{
// Synchronisation with service here...
// ..............................
////////////////////////////////////
// Proceed
_syncResetEvent.Set();
}
catch (Exception ex)
{
log.LogError("Download", ex);
syncStatus = SyncStatus.SynchFailed;
}
}
}
// Set Sync status
_syncStatus = syncStatus;
}
catch (Exception ex)
{
log.LogError("Sync-Worker", ex);
_syncStatus = Core.Sync.SyncStatus.SynchFailed;
// Proceed
_syncResetEvent.Set();
// Reset Force
_syncForce = false;
}
finally
{
// Set Completed
if (OnSyncCompleted != null)
{
OnSyncCompleted(downloaded, uploaded, executed);
}
// Always Wait for Interval
DateTime sleepuntil = DateTime.Now.AddMilliseconds(syncInterval);
while (sleepuntil > DateTime.Now && !_shouldStop && !_syncForce)
{
// Sleep
Thread.Sleep(100);
}
}
}
// Stop
_syncStatus = SyncStatus.Unknown;
}

Categories