|
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
|
|
|
|
|
Firstly, that's VB, not C# - so this is the wrong forum to ask this question.
Secondly, dumping a large pile of code on us and saying "it don't work" is not a good way to get help. We have no idea where in that morras of undocumented and uncommented code the problem is occuring, or any idea what data it is working with.
Post your question in the correct forum (Visual Basic Discussion Boards[^]) or in QA: https://www.codeproject.com/Questions/ask.aspx[^] and post only the relevant code fragment(s) along with an explanation of where the problem occurs and what exactly you did to get it to do it.
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!
|
|
|
|
|
If this is typical of your "new" company's production code, you're in for a lot of late nights.
The words modular and layering seem to be missing from their vocabulary.
The Master said, 'Am I indeed possessed of knowledge? I am not knowing. But if a mean person, who appears quite empty-like, ask anything of me, I set it forth from one end to the other, and exhaust it.'
― Confucian Analects
|
|
|
|
|
There is so much more code I have no documentation. Also, I'm trying to move this thread I'm new to the site
|
|
|
|
|
Hmm.
Great puzzle. "Doctor I'm ill" without any detailed symptoms.
Nevertheless I've been looking for the most common sources of OutOfMemoryException:
- properties that get or set themselves recursively; I did not see any user-defined Property.
- functions that call themselves recursively; I did not see any of them (I may have missed one though).
The next suspect would be event handlers that modify something causing ever more events, possibly resulting in an avalanche. Without any description of this beast, that is hard to find.
I have some more comments though:
1.
I see a lot of new Font statements; most if not all of them only generate two different fonts, so I suggest you generate them once, keep them around in two variables, and assign them to a local variable as appropriate.
Now whenever that approach would be impossible, keep in mind that objects offering a Dispose method require that method being called when done to free up unmanaged data; and most graphic objects (including Font) fall in that category.
2.
And now for a big issue:
you are swallowing exceptions; there are lots of try/catch blocks, and yes they always store the exception message (why only the message?) but then that magic secondLevelMsg variable is never looked at??? The author of this is making life extremely hard, exceptions are there to help you in finding what is going wrong. The current code is very good at hiding what might go wrong. Also, exceptions should not be used as the normal way out. Their occurence should be, well, exceptional.
Hope this helps.
|
|
|
|
|
The previous programmer was trying to go for visual basic.net to C# but this part is still in vb anyway you can show how you might clean up I have tried different ways including copy most of the other program with that does full sync with our item database.
|
|
|
|
|
Hi,
FYI: I'm not a moderator here, I don't have the power to hide a message and replace it by "This message has been flagged as potential spam and is awaiting moderation" (which is gone now).
I would appreciate if you gave more information, in particular at what point in the code things start to go wrong. Assuming your code is runnable, you can find out by (1) looking at the display, (2) or using the debugger, or (3) my personal preference: adding logging and reading the log.
I would never undertake a task as big as yours without logging, to me it is the easiest way of making progress. Yes, it needs extra code, but in my experience that pays off from day one. You might want to read about it here: Article: A simple logging scheme[^]
|
|
|
|
|
Some additional thoughts.
What I previously explained about possible causes for OutOfMemoryException are actually possible causes for StackOverflowException. In order to get OutOfMemory (and not StackOverflow), one needs to allocate lots of objects on the heap (not the stack).
There basically are two scenario's possible for OutOfMemory:
[1]. code is recursing abnormally (so it should result in a StackOverflow) but the heap gets exhausted before the stack is exhausted.
If we assume a workspace of 2GB and a stack size of 1MB and a stack frame of say 1KB (mainly used for local variables of the recursing method), one could recurse 1000 times before getting a stack overflow. To exhaust 2GB in less than 1000 recursions, each recursion needs to consume 2MB which is not at all impossible. If you have objects of such size, look for unlimited recursion (property recursion, function recursion, event avalanche, ...).
[2]. Even when code is running normally (I mean without abnormal recursion), too many and/or too large objects might get allocated (or remain allocated). That depends on the size of the problems your program is dealing with, and the efficiency and correctness of your code.
Things to look for are:
- object references might get stored in static lists, keeping the objects alive forever, even when they aren't really needed any more by the program;
- objetcs with a Dispose() method that aren't disposed of keep hold of their unmanaged memory; this applies to almost all GUI objects.
I stand by my suggestion to use logging. You could even log memory usage statistics periodically and/or when creating large objects.
Things that may point you in the right direction:
- does your app remain responsive (i.e. reacting to user interaction) up to the OutOfMemory exception?
- does your app do everything it should do, and only throws OutOfMemory after some time?
- how long does it take your app from seeming dead to actually throw OutOfMemory?
One wild guess: some operations throw an exception of unexpected type; example: Image.FromFile sometimes throws OutOfMemory when it does not understand the file format (ref[^]). So a single bad data file could be the cause of all this trouble... This is a sufficient reason to always properly display or log all Exception information (message AND stack trace) and never swallow an exception.
|
|
|
|
|
XML is not a database-replacement, and loading a real DB in XML will yield problems. You found them. Yay.
For a decent in-memory db, find one on google and pay the license
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.
|
|
|
|
|