|
I do not understand why there is an UnobservedTaskException in that code at all...
A method in a WCF service is defined as
[OperationContract]
[FaultContract(typeof(RemoteException))]
Task SetInfraredFocus(string _clientName, double _focus);
A WPF application calls out to it via:
public void SetFocus(double _focus)
{
try
{
m_RemoteManualPsControl.SetInfraredFocus(UtilsEnvironment.TerminalName, _focus).Wait();
}
catch (Exception ex)
{
Logger.LogException(Name, ex);
}
}
Note the .Wait() and the catch . That in turn calls the WCF client class
public Task SetInfraredFocus(string _clientName, double _focus)
{
Task task = new Task(() => RemoteChannelProvider.Call(_channel => _channel.SetInfraredFocus(_clientName, _focus)));
task.Start();
return task;
}
True, I ought to add a CallAsync function to our WCF client base class, but that's quite convoluted code there...
The server (a singleton service, multi-threaded) has a simple implementation for the sake of demonstration:
public async Task SetInfraredFocus(string _clientName, double _focus)
{
try
{
await Task.Delay(1);
throw new Exception("Oh f***!");
}
catch (Exception ex)
{
Logger.LogException(Name, ex);
RemoteException.ThrowFaultExceptionFromException(ex);
}
}
And then I get that UnobservedTaskException... Its detail clearly shows where it comes from: it is the RemoteException created from the "Oh f***!" exception of the server. But why does the "catch" in the function on the top not catch the exception?
Oh sanctissimi Wilhelmus, Theodorus, et Fredericus!
|
|
|
|
|
Bernhard Hiller wrote:
Task task = new Task(() => RemoteChannelProvider.Call(_channel => _channel.SetInfraredFocus(_clientName, _focus))); That line looks suspicious to me.
The RemoteChannelProvider doesn't seem to be a built-in class. What's the signature of the Call method?
What I suspect is happening is this:
SetInfraredFocus returns a Task ;Call may or may not discard that task;- Even if it doesn't discard the task, the
new Task constructor definitely discards it - none of the overloads accept a Func<Task> ; - The task returned from the client therefore doesn't observe the result of the task returned from the server. It could even complete before the server call has finished.
If the RemoteChannelProvider.Call method returns the Task , then you should be able to fix this by replacing the client code with:
public Task SetInfraredFocus(string _clientName, double _focus)
{
return Task.Run(() => RemoteChannelProvider.Call(_channel => _channel.SetInfraredFocus(_clientName, _focus)));
} Task.Run has overloads which accept a Func<Task> . The task returned from these will not complete until the inner task has completed, and it will propagate any exceptions correctly.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
That overload does not do the trick either...
The "RemoteChannelProvider" is not a built-in class. The signature is:
public delegate void CallProxyDelegate<in T>(T _channel);
...
void Call(CallProxyDelegate<T> _codeBlock, [CallerMemberName] string _functionName = ""); Some implementation details:
m_ConfigurationChannelFactory = new ConfigurationDuplexChannelFactory<T>(m_CallbackObject, ConfigurationName, null, config);
...
m_CommunicationChannel = (ICommunicationObject)m_ConfigurationChannelFactory.CreateChannel();
...
_codeBlock((T)m_CommunicationChannel); I do not know how that handles a Task.
Oh sanctissimi Wilhelmus, Theodorus, et Fredericus!
|
|
|
|
|
OK, then it's definitely throwing the Task away.
How does the RemoteChannelProvider class cope with server methods which return a value?
If it doesn't, you might still be able to hack around it:
public Task SetInfraredFocus(string _clientName, double _focus)
{
return Task.Run(delegate
{
Task result = null;
RemoteChannelProvider.Call(_channel => result = _channel.SetInfraredFocus(_clientName, _focus));
return result;
});
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Perfect! That hack really works.
(But I still will need some time to find out how it works...)
Oh sanctissimi Wilhelmus, Theodorus, et Fredericus!
|
|
|
|
|
A long time ago, Eric wrote: Quote: Any time you find yourself switching on a type in a generic you are almost certainly doing something wrong. Generics should be generic; they should operate identically completely independent of the type.
If T can only be int or string then don't write your code this way at all in the first place. Write two methods, one that returns an int and one that returns a string. Of course, Eric is always right !
I thought the new pattern-matching facilities in C# 7,8 might allow me to simplify a 'Switch based on a Generic Type; here's a compilable (VS 2019, FrameWork 4.8) example:
public TKey GetNextKey(TKey key = default(TKey))
{
if (! KeysUsed.Contains(key))
{
CurrentKey = key;
KeysUsed.Add(key);
return key;
}
switch (KeyType)
{
case Type _ when KeyType == typeof(Int32):
int i = (Int32) (object) key + 1;
CurrentKey = (TKey)(object) i;
break;
case Type _ when KeyType == typeof(string):
string s = (string) (object) key;
s += GetAGuid();
CurrentKey = (TKey)(object)s;
break;
default:
throw new ArgumentException("unsupported TKey Type");
}
KeysUsed.Add(CurrentKey);
return CurrentKey;
} Okay, if you think "case Type _ when KeyType == typeof(Int32):" is simplification ... game over.
What really irritates me is the conversions to object necessary here. This issue came up in a QA question here in 2016; see FES_SiteCore's solution: [^]
references: Mads Torgensen on C# 8 patterns: [^], ReSharper recent blog: [^]
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
modified 18-Jul-19 10:32am.
|
|
|
|
|
BillWoodruff wrote:
TKey key = default(TKey) Since you're using a recent compiler version, you can omit the type name from the default keyword here:
public TKey GetNextKey(TKey key = default)
BillWoodruff wrote:
if (! KeysUsed.Contains(key))
{
CurrentKey = key;
KeysUsed.Add(key);
return key;
} If KeysUsed is a HashSet<TKey> , you can simplify that to:
if (KeysUsed.Add(key))
{
CurrentKey = key;
return key;
}
BillWoodruff wrote:
switch (KeyType) As you've shown, this is a horrible way to solve the problem. I'd be inclined to make the "next key generation" strategy external to the class, and pass it in via the constructor:
public class Foo<TKey>
{
private readonly HashSet<TKey> KeysUsed;
private readonly Func<TKey, TKey> GenerateNextKey;
public Foo(Func<TKey, TKey> generateNextKey, IEqualityComparer<TKey> comparer = default)
{
if (generateNextKey is null) throw new ArgumentNullException(nameof(generateNextKey));
GenerateNextKey = generateNextKey;
KeysUsed = new HashSet<TKey>(comparer ?? EqualityComparer<TKey>.Default);
}
public TKey CurrentKey { get; private set; }
public TKey GetNextKey(TKey key = default)
{
while (!KeysUsed.Add(key))
{
key = GenerateNextKey(key);
}
CurrentKey = key;
return key;
}
} You could then provide static key generators and/or factory methods to simplify creating the class:
public static class Foo
{
public static class Int32
{
public static readonly Func<int, int> GenerateNextKey = i => i + 1;
public static Foo<int> Create() => new Foo<int>(GenerateNextKey);
}
public static class String
{
public static readonly Func<string, string> GenerateNextKey = s => s + GetAGuid();
private static string GetAGuid() => Guid.NewGuid().ToString("N");
public static Foo<string> Create(IEqualityComparer<string> comparer = default) => new Foo<string>(GenerateNextKey, comparer);
}
} Usage:
Foo<int> fooInt = Foo.Int.Create();
Foo<string> fooString = Foo.String.Create(StringComparer.OrdinalIgnoreCase);
Foo<Guid> fooGuid = new Foo<Guid>(_ => Guid.NewGuid());
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks for this detailed response ! My conclusion is that making a "next key" generator ... where the constraint is to ensure keys are unique ... is best off-loaded to a user-supplied Func passed in to the Class instance as a parameter. I can still do validation in the generic class.
I find it wonderful you describe the code as 'horrible' ... and I agree ! ... since your posting the example of casting voodoo here, as a comment: [^] in 2016 was a source
As I study your code and comments, I look forward to more insights.
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
I think what C#/.NET would need (and I'm not sure it's even possible) in order to completely obviate the need for type checking in generics is a way to do true specialization at the very least.
Unless I'm missing something (and I don't have an example offhand but I run into it from time to time), you can't entirely replace the ability to declare both MyClass<t> and MyClass<char> with function template specialization, short of using all static classes or something.
I always felt like either I was missing something, or .NET was here.
Generics always struck me as less elegant than C++ source based templates anyway. I like the idea of them being truly typed and binary but the tradeoffs are irritating.
When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.
|
|
|
|
|
I think all-in-all C# Generics are excellent, and I think the case I've described here is an "edge case."
I don't have your experience with C++ templates to compare it to.
Given my intense respect for Eric Lippert, over many years, I heed his voice.
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
Lippert is solid. I've read him off and on over the years. I'm not disagreeing with him as such. More like a "gosh it would be nice" scenario.
C++'s template system is really elegant. You can actually get the compiler to do do complex computations (like generating parse tables - see the Spirit framework) all at compile time, using a combination of macros and templates. That's an extreme example, but illustrates the flexibility.
Generics don't have the advantage of source level control - they aren't "fancy typed checked source macros" like C++ templates are. They are binary. That's advantageous for a number of reasons, just not in this case.
And you're right it's probably kind of an edge case. But it's one I ran headfirst into in a non-trivial coding project (my regular expression engine)
I could have made the FA engine far more flexible if I had had template specialization. In order to keep the functionality I had, I had to limit it to only dealing with char inputs. =/
When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.
|
|
|
|
|
I am struggling to deserialize a load of JSON as below (the relevant sections).
The problem is the last array titled volunteer_properties which the DataContractJsonSerializer seems to have a problem with. It appears to me to be an array of anonymous objects, each of which contains a named object which has a number of members. So my DataContract entries are trying to follow the same pattern. The array named "roles" is deserialized quite correctly. Note the deserializer recognises the array and creates it, but each object is null.
I have tried a number of different approaches, including naming the Propentry member corresponding to "first_name", etc, changing the type of the array, etc., all to no avail.
If anyone has a suggestion as to how to get past this I will be most grateful.
[DataContract]
internal class Role
{
[DataMember]
internal int id;
[DataMember]
internal string name;
[DataMember]
internal string suffix;
}
[DataContract]
internal class Property
{
[DataMember]
internal int id;
[DataMember]
internal string org_name;
[DataMember]
internal string value;
}
[DataContract]
internal class Propentry
{
[DataMember]
internal Property property;
}
[DataContract]
internal class Properties
{
[DataMember]
internal Propentry propentry;
}
[DataContract]
internal class Volunteer
{
[DataMember]
internal int id;
[DataMember]
internal Role[] roles;
[DataMember]
internal Propentry[] volunteer_properties;
}
[DataContract]
internal class VolList
{
[DataMember]
internal Volunteer[] volunteers;
}
modified 18-Jul-19 12:19pm.
|
|
|
|
|
Have you tried feeding your JSON into a class generator and comparing them?
I use json2csharp - generate c# classes from json[^] which does it pretty well most times.
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thanks I will give it a try.
|
|
|
|
|
The generator worked fine, but the deserializer still fails. I am drawn to the conclusion that it is the structure of the data. I will talk to the people who produce it.
|
|
|
|
|
The DataContractJsonSerializer is not particularly flexible, but you can make this work. (Assuming you're using .NET 4.5 or later.)
.net - Any way to make DataContractJsonSerializer serialize Dictionaries properly? - Stack Overflow[^]
Based on your sample JSON, the classes I came up with are:
public class PropertyValue
{
public int id { get; set; }
public string org_name { get; set; }
public string value { get; set; }
}
public class Role
{
public int id { get; set; }
public string name { get; set; }
public string suffix { get; set; }
}
public class Volunteer
{
public int id { get; set; }
public IList<Role> roles { get; set; }
public IList<IDictionary<string, PropertyValue>> volunteer_properties { get; set; }
}
public class Root
{
public Volunteer volunteer { get; set; }
} With those classes in place:
var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
var ser = new DataContractJsonSerializer(typeof(Root), new DataContractJsonSerializerSettings(){ UseSimpleDictionaryFormat = true });
var root = (Root)ser.ReadObject(ms);
The volunteer_properties property is a pain - it's a list of dictionaries, each containing a single entry using the property name as a key. If you switched to JSON.NET, you could use a custom converter to tidy that up. But if you can change the source JSON, you could simplify it to:
"volunteer_properties": {
"first_name":{
"id":3990,
"org_name":"First Name",
"value":"Richard"
},
"surname":{
"id":3991,
"org_name":"Surname",
"value":"MacCutchan "
},
} which would then let you remove the IList<...> from the property declaration:
public IDictionary<string, PropertyValue> volunteer_properties { get; set; } giving you a single dictionary of properties.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks for the excellent response Richard, that was indeed the answer.
|
|
|
|
|
I am having windows application in asp.net using vb.net as a language. I have scheduled that application using task Scheduler and it will schedule that .exe every after 5 minutes. So whenever this .exe executes it is throw an Error i.e; "Window Class Name is Not valid" or "Error Creating Window Handle()". So anyone can help me on that. I am stuck on that from last 2 days.
Thanks,
|
|
|
|
|
Does your program include the line Application.EnableVisualStyles(); ?
does your app use TreeView controls ?
If so, try again with that line removed. Things may look slightly different, but the program might work, according to parts of this[^] and this [^] .
Googling for "window class name is not valid" yielded that (and many other pages) in a matter of minutes, not sure it will solve your situation, but it basically seems to be a Microsoft problem.
|
|
|
|
|
No, my application does not have Application.EnableVisualStyles() and Treeview Control.
It contains ListView and Panels with Labels and Textboxes.
|
|
|
|
|
That is too bad
You may want to ask Google and read all you get. One frequent idea there is insufficient access to a code folder.
BTW: you are in the wrong forum, this should be about C#, not VB.NET; but then, you're not the first VBer today to visit and ask here
|
|
|
|
|
Post the entire exception, and the code that the exception references
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Member 14533819 wrote: I am having windows application in asp.net
This statement is self-contradictory: either you have a Windows application (an executable), or you have an ASP.NET solution, which requires a web server and produces no .exe file (the application is used in a web browser accessing the web server).
You cannot create a Windows executable project, copy and paste some ASP.NET code fetched from internet, and expect it to work.
There is no solution apart from understanding what the asp.net code is doing and re-develop it with Windows Forms objects.
enum HumanBool { Yes, No, Maybe, Perhaps, Probably, ProbablyNot, MostLikely, MostUnlikely, HellYes, HellNo, Wtf }
|
|
|
|
|
Member 14533819 wrote: using vb.net as a language
So why have you posted this in the C# forum, rather than the Visual Basic forum[^]?
And as others have said, if you want help, we'll need to see the full details of the exception and the relevant parts of your code.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
The new company I just started working for has had a problem doing full price sync from their database this part of the program is visual basic.net while a lot of the code has been redone in C# we have other programs to pull from the same data link that was created and updates just fine. Any help would be appreciated.
<pre lang="vb"><pre>
Public Class ImportPricing
Public dbUpgrade As Boolean
Public dbFull As Boolean
Dim Failed As Boolean = True
Dim Silent As Boolean = False
Dim msg As String
Dim secondLevelMsg As String
Private printingFont As Font
Private objReader As StreamReader
Public File As String
Public ReadMe As String
Dim Progress As Double
Private Config As Models.Config
Private ConfigService As IConfig = ServiceLocator.Current.GetInstance(Of IConfig)
Private ReadOnly DataSetPricing As New DataSetPricing
Private Alpha As ICollection(Of Models.Alpha)
Private Commodities As ICollection(Of Models.Commodity)
Private LevelTypes As ICollection(Of Models.LevelType)
Private Manufacturers As ICollection(Of Models.Manufacturer)
Private WorkGroups As ICollection(Of Models.Workgroup)
Private ItemStatus As ICollection(Of Models.ItemStatusType)
Private UOM As ICollection(Of Models.Uom)
Delegate Sub OverallProgressSafe(ByVal Task As Enums.CurrentTask, ByVal Status As Enums.CurrentStatus)
Private Sub ImportPricing_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
lblSaving.Visible = False
MemoEdit1.Properties.ReadOnly = True
Config = ConfigService.GetById(1)
If dbFull Or dbUpgrade Then
MemoEdit1.EditValue = "This is a Full Database update and may take 15+ minutes. Press Next to begin the update."
btnPrint.Enabled = False
Else
objReader = New StreamReader(ReadMe)
MemoEdit1.EditValue = objReader.ReadToEnd()
objReader.Close()
End If
End Sub
Private Sub WizardControl1_SelectedPageChanged(ByVal sender As Object, ByVal e As WizardPageChangedEventArgs) Handles WizardControl1.SelectedPageChanged
If e.Page Is WizardPage1 Then
e.Page.AllowBack = False
e.Page.AllowNext = False
e.Page.AllowCancel = False
btnPrint.Visible = False
Failed = False
BackgroundWorker.RunWorkerAsync()
End If
If e.Page Is CompletionWizardPage1 Then
e.Page.AllowBack = False
e.Page.AllowCancel = False
btnPrint.Enabled = True
btnPrint.Visible = True
If Failed = False Then
If dbFull Then
GridControl1.Visible = False
MemoEdit2.Visible = True
MemoEdit2.Dock = DockStyle.Fill
MemoEdit2.EditValue = "Full Price Update has completed. You should restart Quantum before continuing."
Else
MemoEdit2.Visible = False
ManufacturersBS.DataSource = DataSetPricing.Manufacturers
cboManufacturers.DataSource = ManufacturersBS
cboManufacturers.DisplayMember = "Description"
cboManufacturers.ValueMember = "PK_ManufacturerID"
UOMsBS.DataSource = DataSetPricing.UOM
cboUOMs.DataSource = UOMsBS
cboUOMs.DisplayMember = "ShortDescription"
cboUOMs.ValueMember = "PK_UOMID"
GridControl1.DataSource = DataSetPricing.Items
Try
Dim column As DevExpress.XtraGrid.Columns.GridColumn
Dim imageCombo As DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox = TryCast(GridControl1.RepositoryItems.Add("ImageComboBoxEdit"), DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox)
imageCombo.SmallImages = ImageCollection1
imageCombo.Items.Add(New DevExpress.XtraEditors.Controls.ImageComboBoxItem("Add", 1, 0))
imageCombo.Items.Add(New DevExpress.XtraEditors.Controls.ImageComboBoxItem("Delete", 2, 1))
imageCombo.Items.Add(New DevExpress.XtraEditors.Controls.ImageComboBoxItem("Arrow_Down", 3, 2))
imageCombo.Items.Add(New DevExpress.XtraEditors.Controls.ImageComboBoxItem("Arrow_Up", 4, 3))
imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Center
column = GridView1.Columns("ItemChange")
column.ColumnEdit = imageCombo
column = GridView1.Columns("CostChange")
column.ColumnEdit = imageCombo
Catch ex As Exception
Exit Try
End Try
End If
Else
GridControl1.Visible = False
MemoEdit2.Visible = True
MemoEdit2.Dock = DockStyle.Fill
MemoEdit2.EditValue = msg & vbCrLf & vbCrLf & secondLevelMsg
End If
End If
End Sub
Private Sub BackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
Dim safeDelegate As New OverallProgressSafe(AddressOf OverallProgress)
If File = Nothing Then
Invoke(safeDelegate, Enums.CurrentTask.Download, Enums.CurrentStatus.InProgress)
If DoGetFiles() = True Then
Invoke(safeDelegate, Enums.CurrentTask.Download, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.Download, Enums.CurrentStatus.Failed)
Exit Sub
End If
End If
Invoke(safeDelegate, Enums.CurrentTask.Extract, Enums.CurrentStatus.InProgress)
If DoExtract() = True Then
Invoke(safeDelegate, Enums.CurrentTask.Extract, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.Extract, Enums.CurrentStatus.Failed)
Exit Sub
End If
Invoke(safeDelegate, Enums.CurrentTask.Alpha, Enums.CurrentStatus.InProgress)
If DoImpAlpha() = True Then
Invoke(safeDelegate, Enums.CurrentTask.Alpha, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.Alpha, Enums.CurrentStatus.Failed)
Exit Sub
End If
Invoke(safeDelegate, Enums.CurrentTask.Commodities, Enums.CurrentStatus.InProgress)
If DoImpCommodities() = True Then
Invoke(safeDelegate, Enums.CurrentTask.Commodities, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.Commodities, Enums.CurrentStatus.Failed)
Exit Sub
End If
Invoke(safeDelegate, Enums.CurrentTask.Manufacturers, Enums.CurrentStatus.InProgress)
If DoImpManufacturers() = True Then
Invoke(safeDelegate, Enums.CurrentTask.Manufacturers, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.Manufacturers, Enums.CurrentStatus.Failed)
Exit Sub
End If
Invoke(safeDelegate, Enums.CurrentTask.WorkGroups, Enums.CurrentStatus.InProgress)
If DoImpWorkGroups() = True Then
Invoke(safeDelegate, Enums.CurrentTask.WorkGroups, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.WorkGroups, Enums.CurrentStatus.Failed)
Exit Sub
End If
Invoke(safeDelegate, Enums.CurrentTask.Items, Enums.CurrentStatus.InProgress)
If DoImpItems() = True Then
Invoke(safeDelegate, Enums.CurrentTask.Items, Enums.CurrentStatus.Done)
Else
Invoke(safeDelegate, Enums.CurrentTask.Items, Enums.CurrentStatus.Failed)
Exit Sub
End If
Config.LastUpdateOn = Date.Now
Config.UpdateEffectiveDate = Date.Now
ConfigService.Update(Config)
End Sub
Private Sub BackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker.ProgressChanged
CurrentTask.Position = e.ProgressPercentage
If e.ProgressPercentage = 100 Then
lblSaving.Visible = True
Else
lblSaving.Visible = False
End If
End Sub
Private Sub BackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker.RunWorkerCompleted
WizardControl1.SelectedPage = CompletionWizardPage1
End Sub
Public Sub OverallProgress(ByVal Task As Enums.CurrentTask, ByVal Status As Enums.CurrentStatus)
Select Case Task
Case Enums.CurrentTask.Download
If Status = Enums.CurrentStatus.InProgress Then
imgDownload.Image = My.Resources.DoubleRightArrowHS
lblDownload.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgDownload.Image = My.Resources.PushpinHS
Progress = 25
lblDownload.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgDownload.Image = My.Resources.WarningHS
Progress = 100
msg = "Download failed. Please contact support."
Failed = True
End If
Case Enums.CurrentTask.Extract
If Status = Enums.CurrentStatus.InProgress Then
imgExtracting.Image = My.Resources.DoubleRightArrowHS
lblExtracting.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgExtracting.Image = My.Resources.PushpinHS
Progress = 37.5
lblExtracting.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgExtracting.Image = My.Resources.WarningHS
Progress = 100
msg = "Extract failed. Please contact support."
Failed = True
End If
Case Enums.CurrentTask.Alpha
If Status = Enums.CurrentStatus.InProgress Then
imgImpAlpha.Image = My.Resources.DoubleRightArrowHS
lblImpAlpha.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgImpAlpha.Image = My.Resources.PushpinHS
Progress = 50
lblImpAlpha.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgImpAlpha.Image = My.Resources.WarningHS
Progress = 100
msg = "Alpha Import failed. Please contact support."
Failed = True
End If
Case Enums.CurrentTask.Commodities
If Status = Enums.CurrentStatus.InProgress Then
imgImpCommodities.Image = My.Resources.DoubleRightArrowHS
lblImpCommodities.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgImpCommodities.Image = My.Resources.PushpinHS
Progress = 62.5
lblImpCommodities.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgImpCommodities.Image = My.Resources.WarningHS
Progress = 100
msg = "Commodities Import failed. Please contact support."
Failed = True
End If
Case Enums.CurrentTask.Manufacturers
If Status = Enums.CurrentStatus.InProgress Then
imgImpManufacturers.Image = My.Resources.DoubleRightArrowHS
lblImpManufacturers.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgImpManufacturers.Image = My.Resources.PushpinHS
Progress = 75
lblImpManufacturers.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgImpManufacturers.Image = My.Resources.WarningHS
Progress = 100
msg = "Manufacturers Import failed. Please contact support."
Failed = True
End If
Case Enums.CurrentTask.WorkGroups
If Status = Enums.CurrentStatus.InProgress Then
imgImpWorkGroups.Image = My.Resources.DoubleRightArrowHS
lblImpWorkGroups.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgImpWorkGroups.Image = My.Resources.PushpinHS
Progress = 87.5
lblImpWorkGroups.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgImpWorkGroups.Image = My.Resources.WarningHS
Progress = 100
msg = "WorkGroup Import failed. Please contact support."
Failed = True
End If
Case Enums.CurrentTask.Items
If Status = Enums.CurrentStatus.InProgress Then
imgImpItems.Image = My.Resources.DoubleRightArrowHS
lblImpItems.Font = New Font("Tahoma", 10.0!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Done Then
imgImpItems.Image = My.Resources.PushpinHS
Progress = 100
lblImpItems.Font = New Font("Tahoma", 10.0!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
ElseIf Status = Enums.CurrentStatus.Failed Then
imgImpItems.Image = My.Resources.WarningHS
Progress = 100
msg = "Item Import failed. Please contact support."
Failed = True
End If
Case Else
Progress = 100
End Select
AllTasks.Position = CInt(Progress)
End Sub
Private Function DoGetFiles() As Boolean
Dim theResponse As HttpWebResponse
Dim theRequest As HttpWebRequest
Try
If dbUpgrade Or dbFull Then
theRequest = CType(WebRequest.Create("https://www.electricalresources.com/Price/Full/DataLink.zip"), HttpWebRequest)
Else
theRequest = CType(WebRequest.Create("https://www.electricalresources.com/Price/DataLink.zip"), HttpWebRequest)
End If
theResponse = CType(theRequest.GetResponse, HttpWebResponse)
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
Dim length As Long = theResponse.ContentLength
File = My.Computer.FileSystem.GetTempFileName
Using writeStream As New IO.FileStream(File, IO.FileMode.Append)
Dim nRead As Integer
Dim speedtimer As New Stopwatch()
Do
speedtimer.Start()
Dim readBytes(4095) As Byte
Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
Dim percent As Integer = CInt((nRead * 100) / length)
BackgroundWorker.ReportProgress(percent)
If bytesread = 0 Then Exit Do
writeStream.Write(readBytes, 0, bytesread)
speedtimer.Stop()
Loop
theResponse.GetResponseStream.Close()
writeStream.Close()
End Using
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Return True
End Function
Private Function DoExtract() As Boolean
Try
Using zip As ZipFile = ZipFile.Read(File)
zip.Password = "dr@gon"
zip.Encryption = EncryptionAlgorithm.WinZipAes128
For Each e As ZipEntry In zip
e.Extract(My.Computer.FileSystem.SpecialDirectories.Temp, ExtractExistingFileAction.OverwriteSilently)
Next
End Using
DataSetPricing.Alpha.BeginLoadData()
DataSetPricing.Alpha.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\Alpha.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.Alpha.EndLoadData()
BackgroundWorker.ReportProgress(20)
DataSetPricing.Commodities.BeginLoadData()
DataSetPricing.Commodities.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\Commodities.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.Commodities.EndLoadData()
BackgroundWorker.ReportProgress(40)
DataSetPricing.Items.BeginLoadData()
DataSetPricing.Items.DataSet.ReadXml(String.Format("{0}\Items.xml", My.Computer.FileSystem.SpecialDirectories.Temp), XmlReadMode.InferTypedSchema)
DataSetPricing.Items.EndLoadData()
BackgroundWorker.ReportProgress(60)
DataSetPricing.Manufacturers.BeginLoadData()
DataSetPricing.Manufacturers.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\Manufacturers.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.Manufacturers.EndLoadData()
BackgroundWorker.ReportProgress(80)
DataSetPricing.WorkGroups.BeginLoadData()
DataSetPricing.WorkGroups.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\WorkGroups.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.WorkGroups.EndLoadData()
DataSetPricing.LevelTypes.BeginLoadData()
DataSetPricing.LevelTypes.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\LevelTypes.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.LevelTypes.EndLoadData()
DataSetPricing.Status.BeginLoadData()
DataSetPricing.Status.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\Status.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.Status.EndLoadData()
DataSetPricing.UOM.BeginLoadData()
DataSetPricing.UOM.DataSet.ReadXml(My.Computer.FileSystem.SpecialDirectories.Temp & "\UOM.xml", XmlReadMode.InferTypedSchema)
DataSetPricing.UOM.EndLoadData()
If Not dbFull Then
Dim col1 As New DataColumn("ItemChange", GetType(Integer))
Dim col2 As New DataColumn("CostChange", GetType(Integer))
DataSetPricing.Items.Columns.Add(col1)
DataSetPricing.Items.Columns.Add(col2)
Dim Item As Models.Item
For Each row In DataSetPricing.Items
Item = ServiceLocator.Current.GetInstance(Of IItems).GetByRowId(row.RowID)
If Not Item Is Nothing Then
row("ItemChange") = 0
row("CostChange") = 0
If row.Cost < Item.Cost Then
row("CostChange") = 3
End If
If row.Cost > Item.Cost Then
row("CostChange") = 4
End If
Else
row("ItemChange") = 1
End If
If row.FK_StatusID = 3 Then
row("ItemChange") = 2
End If
Next
End If
BackgroundWorker.ReportProgress(100)
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Return True
End Function
Private Function DoImpAlpha() As Boolean
Dim percent As Integer = 0
Dim currentRow As Integer = 0
Dim objRow As DataSetPricing.AlphaRow
Alpha = ServiceLocator.Current.GetInstance(Of IAlpha).Get()
Try
currentRow = 0
For Each row In DataSetPricing.Alpha
Dim x = (From c In Alpha Where c.RowId = row.RowID).SingleOrDefault
If x Is Nothing Then
Dim entity As New Models.Alpha() With {.ParentId = 0}
If Not row.ParentID = 0 Then
Try
objRow = DataSetPricing.Alpha.Where(Function(d) d.PK_AlphaID = row.ParentID).SingleOrDefault
If Not objRow Is Nothing Then
Dim q = (From c In Alpha Where c.RowId = objRow.RowID).SingleOrDefault
entity.ParentId = q.AlphaId
End If
Catch ex As Exception
Exit Try
End Try
End If
entity.Description = row.Description
entity.DisplayEri = row.DisplayERI
entity.IndexNumber = row.IndexNumber
entity.Level = 0
entity.RowId = row.RowID
ServiceLocator.Current.GetInstance(Of IAlpha).Add(entity)
Alpha.Add(entity)
End If
currentRow += 1
percent = CInt((currentRow / DataSetPricing.Alpha.Rows.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
currentRow = 0
For Each row In DataSetPricing.Alpha
Try
Dim x = (From c In Alpha Where c.RowId = row.RowID).SingleOrDefault
If Not x Is Nothing Then
objRow = DataSetPricing.Alpha.Where(Function(d) d.PK_AlphaID = row.ParentID).SingleOrDefault
If Not objRow Is Nothing Then
Dim q = (From c In Alpha Where c.RowId = objRow.RowID).SingleOrDefault
If x.ParentId <> q.AlphaId Then
x.ParentId = q.AlphaId
ServiceLocator.Current.GetInstance(Of IAlpha).Update(x)
End If
End If
End If
Catch ex As Exception
Exit Try
End Try
currentRow += 1
percent = CInt((currentRow / DataSetPricing.Alpha.Rows.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
currentRow = 0
For Each row In Alpha
objRow = DataSetPricing.Alpha.Where(Function(d) d.RowID = row.RowId).SingleOrDefault
If Not objRow Is Nothing Then
If row.IndexNumber <> objRow.IndexNumber Or row.Description <> objRow.Description Then
row.IndexNumber = objRow.IndexNumber
row.Description = objRow.Description
ServiceLocator.Current.GetInstance(Of IAlpha).Update(row)
End If
Else
ServiceLocator.Current.GetInstance(Of IAlpha).DeleteById(row.AlphaId)
End If
currentRow += 1
percent = CInt((currentRow / Alpha.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Return True
End Function
Private Function DoImpCommodities() As Boolean
Dim percent As Integer = 0
Dim currentRow As Integer = 0
Dim objRow As DataSetPricing.CommoditiesRow
Commodities = ServiceLocator.Current.GetInstance(Of ICommodities).Get
Try
currentRow = 0
For Each row In DataSetPricing.Commodities
Dim RowID As String = row.RowID
Dim x = (From c In Commodities Where c.RowId = RowID).SingleOrDefault
If x Is Nothing Then
Dim entity As New Models.Commodity() With {.ParentId = 0}
If Not row.ParentID = 0 Then
objRow = DataSetPricing.Commodities.Where(Function(d) d.PK_CommodityID = row.ParentID).SingleOrDefault
If Not objRow Is Nothing Then
Dim q = (From c In Commodities Where c.RowId = objRow.RowID).SingleOrDefault
entity.ParentId = q.PkCommodityId
End If
End If
entity.Description = row.Description
entity.ImageIndex = row.ImageIndex
If Len(row.BeginERI) = 0 Then
entity.BeginEri = "000000000000000"
Else
entity.BeginEri = row.BeginERI
End If
If Len(row.EndERI) = 0 Then
entity.EndEri = "000000000000000"
Else
entity.EndEri = row.BeginERI
End If
entity.RowId = row.RowID
ServiceLocator.Current.GetInstance(Of ICommodities).Add(entity)
Commodities.Add(entity)
End If
currentRow += 1
percent = CInt((currentRow / DataSetPricing.Commodities.Rows.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
currentRow = 0
For Each row In Commodities
objRow = DataSetPricing.Commodities.Where(Function(d) d.RowID = row.RowId).SingleOrDefault
If Not objRow Is Nothing Then
row.Description = objRow.Description
Else
ServiceLocator.Current.GetInstance(Of ICommodities).DeleteById(row.PkCommodityId)
End If
currentRow += 1
percent = CInt((currentRow / Commodities.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Commodities.Clear()
Return True
End Function
Private Function DoImpManufacturers() As Boolean
Dim percent As Integer = 0
Dim currentRow As Integer = 0
Dim objRow As DataSetPricing.ManufacturersRow
Manufacturers = ServiceLocator.Current.GetInstance(Of IManufacturers).Get
Try
Dim list = Manufacturers.AsQueryable().Where(Function(d) d.RowId Is Nothing)
For Each entity As Models.Manufacturer In list
For Each row In DataSetPricing.Manufacturers
If Trim(entity.ManufacturerName) = Trim(row.Description) Then
entity.RowId = row.RowID
End If
ServiceLocator.Current.GetInstance(Of IManufacturers).Update(entity)
Next
currentRow += 1
percent = CInt((currentRow / DataSetPricing.Manufacturers.Rows.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
currentRow = 0
For Each row In Manufacturers
objRow = DataSetPricing.Manufacturers.Where(Function(d) d.RowID = row.RowId).SingleOrDefault
If Not objRow Is Nothing Then
row.ManufacturerName = objRow.Description
row.Upc = objRow.UPC
ServiceLocator.Current.GetInstance(Of IManufacturers).Update(row)
End If
currentRow += 1
percent = CInt((currentRow / Manufacturers.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
currentRow = 0
For Each row In DataSetPricing.Manufacturers
Dim RowID As String = row.RowID
Dim x = (From c In Manufacturers Where c.RowId = RowID).FirstOrDefault
If x Is Nothing Then
Dim entity As New Models.Manufacturer
entity.ManufacturerName = row.Description
entity.Upc = row.UPC
entity.RowId = row.RowID
ServiceLocator.Current.GetInstance(Of IManufacturers).Add(entity)
End If
currentRow += 1
percent = CInt((currentRow / DataSetPricing.Manufacturers.Rows.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Return True
End Function
Private Function DoImpWorkGroups() As Boolean
Dim percent As Integer = 0
Dim currentRow As Integer = 0
WorkGroups = ServiceLocator.Current.GetInstance(Of IWorkgroups).Get
LevelTypes = ServiceLocator.Current.GetInstance(Of ILevelTypes).Get
Try
If dbFull Or dbUpgrade Then
For Each entity As Models.Workgroup In WorkGroups
For Each row In DataSetPricing.WorkGroups
If entity.Description = row.Description Then
entity.RowId = row.RowID
End If
Next
ServiceLocator.Current.GetInstance(Of IWorkgroups).Update(entity)
currentRow += 1
percent = CInt((currentRow / WorkGroups.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
End If
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Try
currentRow = 0
If dbFull Or dbUpgrade Then
For Each entity As Models.LevelType In LevelTypes
For Each row In DataSetPricing.LevelTypes
If entity.LevelTypeId = row.PK_LevelTypeID Then
entity.RowId = row.RowID
End If
Next
ServiceLocator.Current.GetInstance(Of ILevelTypes).Update(entity)
currentRow += 1
percent = CInt((currentRow / LevelTypes.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
End If
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Return True
End Function
Private Sub TestReader()
Dim reader As XmlReader = XmlReader.Create(String.Format("{0}\Items.xml", My.Computer.FileSystem.SpecialDirectories.Temp))
reader.MoveToContent()
While reader.Read
If reader.NodeType = XmlNodeType.Element And reader.Name = "Items" Then
Dim row As DataSetPricing.ItemsRow = New DataSetPricing.ItemsDataTable().NewItemsRow
While reader.Read
If reader.NodeType = XmlNodeType.Element Then
Dim element As XElement = XElement.ReadFrom(reader)
Select Case reader.Name
Case "PK_ItemID"
row.PK_ItemID = element.Value
Exit Select
Case "ParentID"
row.ParentID = element.Value
Exit Select
Case "ERINumber"
row.ERINumber = element.Value
Exit Select
Case "Comparative"
row.Comparative = element.Value
Exit Select
Case "AlphaIndex"
row.AlphaIndex = element.Value
Exit Select
Case "Description"
row.Description = element.Value
Exit Select
Case "ImKing"
row.ImKing = element.Value
Exit Select
Case "FK_ManufacturerID"
row.PK_ItemID = element.Value
Exit Select
Case "FK_StatusID"
row.FK_StatusID = element.Value
Exit Select
Case "FK_LevelTypeID"
row.FK_LevelTypeID = element.Value
Exit Select
Case "FK_WorkGroupID"
row.FK_WorkgroupID = element.Value
Exit Select
Case "FK_CommodityID"
row.FK_CommodityID = element.Value
Exit Select
Case "UPC"
row.CatalogNumber = element.Value
Exit Select
Case "FK_UOMID"
row.FK_UOMID = element.Value
Exit Select
Case "Retail"
row.Retail = element.Value
Exit Select
Case "Cost"
row.Cost = element.Value
Exit Select
Case "Labor"
row.Labor = element.Value
Exit Select
Case "Multiplier"
row.Multiplier = element.Value
Exit Select
Case "ReportGroup"
row.ReportGroup = element.Value
Exit Select
Case "DateEffective"
row.DateEffective = element.Value
Exit Select
Case "ImageURL"
row.ImageURL = element.Value.ToString
Exit Select
Case "CatalogPageURL"
row.CatalogPageURL = element.Value.ToString
Exit Select
Case "LastUpdateDateTime"
row.LastUpdateDateTime = element.Value
Exit Select
Case "RowID"
row.RowID = element.Value
Exit Select
End Select
End If
End While
End If
End While
End Sub
Private Function DoImpItems() As Boolean
Dim percent As Integer = 0
Dim currentRow As Integer = 0
Dim ItemDataRow As DataSetPricing.ItemsRow
Dim CommodityDataRow As DataSetPricing.CommoditiesRow
Dim LevelTypeDataRow As DataSetPricing.LevelTypesRow
Dim StatusDataRow As DataSetPricing.StatusRow
Dim ManufacturerDataRow As DataSetPricing.ManufacturersRow
Dim UomDataRow As DataSetPricing.UOMRow
Dim WorkgroupDataRow As DataSetPricing.WorkGroupsRow
Dim Item As Models.Item
Manufacturers = ServiceLocator.Current.GetInstance(Of IManufacturers).Get
WorkGroups = ServiceLocator.Current.GetInstance(Of IWorkgroups).Get
LevelTypes = ServiceLocator.Current.GetInstance(Of ILevelTypes).Get
ItemStatus = ServiceLocator.Current.GetInstance(Of IItemStatusTypes).Get
UOM = ServiceLocator.Current.GetInstance(Of IUom).Get
Try
currentRow = 0
For Each row In DataSetPricing.Items
Item = ServiceLocator.Current.GetInstance(Of IItems).GetByRowId(row.RowID)
If Not Item Is Nothing Then
If Not Item.DoNotUpdate Then
Item.EriNumber = row.ERINumber
Item.EriNumberSearch = row.ERINumber
Item.Comparative = row.Comparative
If row.ParentID <> 0 Then
ItemDataRow = DataSetPricing.Items.Where(Function(d) d.PK_ItemID = row.ParentID).SingleOrDefault
If Not ItemDataRow Is Nothing Then
Dim ItemParent As Models.Item = ServiceLocator.Current.GetInstance(Of IItems).GetByRowId(ItemDataRow.RowID)
If Not ItemParent Is Nothing Then
Item.ParentId = ItemParent.PkItems
Else
Item.ParentId = 0
End If
Else
Item.ParentId = 0
End If
Else
Item.ParentId = 0
End If
Item.CatalogNumber = row.CatalogNumber
Item.Description = row.Description
Item.MyCost = CDec(Math.Round(row.Cost * IIf(IsDBNull(Item.MyMultiplier), 1, Item.MyMultiplier), 2))
Item.Cost = row.Cost
Item.Retail = row.Retail
If Not Config.NoUpdateLabor Then
Item.Labor = row.Labor
End If
Item.EffectiveDate = row.DateEffective
Item.Comparative = row.Comparative
Item.UPC = Strings.Right(row.UPC, 5)
Item.AlphaIndex = row.AlphaIndex
Item.ReportGroup = row.ReportGroup
Item.ImKing = row.ImKing
Item.ImageUrl = IIf(IsDBNull(row.ImageURL), String.Empty, row.ImageURL)
Item.CatalogPageUrl = IIf(IsDBNull(row.CatalogPageURL), String.Empty, row.CatalogPageURL)
Item.LastCostUpdate = Date.Now
LevelTypeDataRow = DataSetPricing.LevelTypes.Where(Function(d) d.PK_LevelTypeID = row.FK_LevelTypeID).SingleOrDefault
If Not LevelTypeDataRow Is Nothing Then
Dim q = (From c In LevelTypes Where c.RowId = LevelTypeDataRow.RowID).SingleOrDefault
Item.FkLevel = q.LevelTypeId
Else
Item.FkLevel = 1
End If
StatusDataRow = DataSetPricing.Status.Where(Function(d) d.PK_StatusID = row.FK_StatusID).SingleOrDefault
If Not StatusDataRow Is Nothing Then
Dim q = (From c In ItemStatus Where c.Status = StatusDataRow.Description).SingleOrDefault
Item.FkStatus = q.PkItemStatusTypes
Else
Item.FkStatus = 1
End If
UomDataRow = DataSetPricing.UOM.Where(Function(d) d.PK_UOMID = row.FK_UOMID).SingleOrDefault
If Not UomDataRow Is Nothing Then
Dim q = (From c In UOM Where c.UOM = UomDataRow.ShortDescription).SingleOrDefault
Item.FkUom = q.IdUom
Else
Item.FkUom = 0
End If
WorkgroupDataRow = DataSetPricing.WorkGroups.Where(Function(d) d.PK_WorkGroupID = row.FK_WorkgroupID).SingleOrDefault
If Not WorkgroupDataRow Is Nothing Then
Dim q = (From c In WorkGroups Where c.RowId = WorkgroupDataRow.RowID).SingleOrDefault
Item.FkWorkgroup = q.PkWorkgroups
Else
Item.FkWorkgroup = 0
End If
CommodityDataRow = DataSetPricing.Commodities.Where(Function(d) d.PK_CommodityID = row.FK_CommodityID).SingleOrDefault
If Not CommodityDataRow Is Nothing Then
Dim q = ServiceLocator.Current.GetInstance(Of ICommodities).GetByRowId(CommodityDataRow.RowID)
Item.FkCommodityId = q.PkCommodityId
Else
Item.FkCommodityId = 0
End If
ManufacturerDataRow = DataSetPricing.Manufacturers.Where(Function(d) d.PK_ManufacturerID = row.FK_ManufacturerID).SingleOrDefault
If Not ManufacturerDataRow Is Nothing Then
Dim q = (From c In Manufacturers Where c.RowId = ManufacturerDataRow.RowID).FirstOrDefault
Item.FkManufacturer = q.PkManufacturerId
Else
Item.FkManufacturer = 0
End If
End If
ServiceLocator.Current.GetInstance(Of IItems).Update(Item)
Else
Dim entity As New Models.Item
entity.EriNumber = row.ERINumber
entity.EriNumberSearch = row.ERINumber
entity.CatalogNumber = row.CatalogNumber
entity.Description = row.Description
entity.MyCost = row.Cost
entity.Cost = row.Cost
entity.Retail = row.Retail
entity.Labor = row.Labor
entity.EffectiveDate = row.DateEffective
entity.Comparative = row.Comparative
entity.UPC = Strings.Right(CStr(row.UPC), 5)
entity.AlphaIndex = row.AlphaIndex
entity.ReportGroup = row.ReportGroup
entity.ImKing = row.ImKing
entity.MyMultiplier = 1
entity.RowId = row.RowID
entity.ImageUrl = row.ImageURL
entity.CatalogPageUrl = row.CatalogPageURL
entity.LastCostUpdate = Date.Now
entity.DefaultCostCode = 0
If row.ParentID <> 0 Then
ItemDataRow = DataSetPricing.Items.Where(Function(d) d.PK_ItemID = row.ParentID).SingleOrDefault
If Not ItemDataRow Is Nothing Then
Dim ItemParent As Models.Item = ServiceLocator.Current.GetInstance(Of IItems).GetByRowId(ItemDataRow.RowID)
If Not ItemParent Is Nothing Then
entity.ParentId = ItemParent.PkItems
Else
entity.ParentId = 0
End If
Else
entity.ParentId = 0
End If
Else
entity.ParentId = 0
End If
LevelTypeDataRow = DataSetPricing.LevelTypes.Where(Function(d) d.PK_LevelTypeID = row.FK_LevelTypeID).SingleOrDefault
If Not LevelTypeDataRow Is Nothing Then
Dim q = (From c In LevelTypes Where c.RowId = LevelTypeDataRow.RowID).SingleOrDefault
entity.FkLevel = q.LevelTypeId
Else
entity.FkLevel = 1
End If
StatusDataRow = DataSetPricing.Status.Where(Function(d) d.PK_StatusID = row.FK_StatusID).SingleOrDefault
If Not StatusDataRow Is Nothing Then
Dim q = (From c In ItemStatus Where c.Status = StatusDataRow.Description).SingleOrDefault
entity.FkStatus = q.PkItemStatusTypes
Else
entity.FkStatus = 1
End If
UomDataRow = DataSetPricing.UOM.Where(Function(d) d.PK_UOMID = row.FK_UOMID).SingleOrDefault
If Not UomDataRow Is Nothing Then
Dim q = (From c In UOM Where c.UOM = UomDataRow.ShortDescription).SingleOrDefault
entity.FkUom = q.IdUom
Else
entity.FkUom = 0
End If
WorkgroupDataRow = DataSetPricing.WorkGroups.Where(Function(d) d.PK_WorkGroupID = row.FK_WorkgroupID).SingleOrDefault
If Not WorkgroupDataRow Is Nothing Then
Dim q = (From c In WorkGroups Where c.RowId = WorkgroupDataRow.RowID).SingleOrDefault
entity.FkWorkgroup = q.PkWorkgroups
Else
entity.FkWorkgroup = 0
End If
CommodityDataRow = DataSetPricing.Commodities.Where(Function(d) d.PK_CommodityID = row.FK_CommodityID).SingleOrDefault
If Not CommodityDataRow Is Nothing Then
Dim q = ServiceLocator.Current.GetInstance(Of ICommodities).GetByRowId(CommodityDataRow.RowID)
entity.FkCommodityId = q.PkCommodityId
Else
entity.FkCommodityId = 0
End If
ManufacturerDataRow = DataSetPricing.Manufacturers.Where(Function(d) d.PK_ManufacturerID = row.FK_ManufacturerID).SingleOrDefault
If Not ManufacturerDataRow Is Nothing Then
Dim q = (From c In Manufacturers Where c.RowId = ManufacturerDataRow.RowID).FirstOrDefault
entity.FkManufacturer = q.PkManufacturerId
Else
entity.FkManufacturer = 0
End If
ServiceLocator.Current.GetInstance(Of IItems).Add(entity)
End If
currentRow += 1
percent = CInt((currentRow / DataSetPricing.Items.Rows.Count) * 100)
BackgroundWorker.ReportProgress(percent)
Next
Catch ex As Exception
secondLevelMsg = ex.Message
Return False
Exit Function
End Try
Return True
End Function
Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnPrint.Click
If WizardControl1.SelectedPage Is WelcomeWizardPage1 Then
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
printingFont = New Font("Arial", 10)
objReader = New StreamReader(ReadMe)
With PrintDialog1
.Document = pd
.AllowPrintToFile = True
.AllowSelection = True
.AllowSomePages = True
If .ShowDialog() = DialogResult.OK Then
pd.Print()
End If
End With
objReader.Close()
pd.Dispose()
End If
If WizardControl1.SelectedPage Is CompletionWizardPage1 Then
GridControl1.Print()
End If
End Sub
Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim linesPerPage As Single = 0
Dim yPos As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = Nothing
linesPerPage = ev.MarginBounds.Height / printingFont.GetHeight(ev.Graphics)
While count < linesPerPage
line = objReader.ReadLine()
If line Is Nothing Then
Exit While
End If
yPos = topMargin + count * printingFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(line, printingFont, Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
End While
If Not (line Is Nothing) Then
ev.HasMorePages = True
Else
ev.HasMorePages = False
End If
End Sub
Private Sub ImportPricing_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.FormClosing
If Failed Then
DialogResult = Windows.Forms.DialogResult.Abort
Else
DialogResult = Windows.Forms.DialogResult.OK
End If
End Sub
End Class
|
|
|
|
|