Getting rid of duplication in a VB list box - asp.net

Using ASP/VB, I'm trying to get rid of some duplication in a list box that is coming from an XML document.
Sorry if this is a daft question, I'm new to this.
I've tried various things, but nothing has worked. Here is the code - thanks for any help / assistance!
Function getAssets(ByVal siteid As String) As String
Dim oAssets As New Xteam.XteamWebService
Dim strAssets As String = ""
Dim oDoc As New XmlDocument
'Dim oNode As XmlNode
strAssets = oAssets.ReadHAssetCodes(siteid)
oDoc.LoadXml(strAssets)
For Each Node As XmlNode In oDoc.SelectSingleNode("XteamAssets")
lstHAssets.Items.Add(New ListItem(Node("hassetdescription").InnerText, Node("hassetcode").InnerText))
Next
lstHAssets.Items.Insert(0, "--Please Select--")
Return "ToSender"
End Function

There's probably a more efficient way but this will work.
Function getAssets(ByVal siteid As String) As String
Dim oAssets As New Xteam.XteamWebService
Dim strAssets As String = ""
Dim oDoc As New XmlDocument '
Dim oNode As XmlNode
strAssets = oAssets.ReadHAssetCodes(siteid)
oDoc.LoadXml(strAssets)
Dim strAryUniqueValues as string()
Dim strUniqueValues as string = ""
Dim i as int = 0
Dim strSearchPair as string
For Each Node As XmlNode In oDoc.SelectSingleNode("XteamAssets")
strSearchPair = "~" & Node("hassetdescription").InnerText & "/" & Node("hassetcode").InnerText & "~"
' see if these values have been included already, if not then add them
if instr(strUniqueValues,strSearchPair) = -1 then
strAryUniqueValues(i) = strSearchPair
strUniqueValues = strUniqueValues & strAryUniqueValues(i)
i = i + 1
end if
Next
'now loop back through and build your listbox
Dim strAryPair as string()
For each strPair in strAryUniqueValues
strAryPair = split(strPair,"/")
lstHAssets.Items.Add(New ListItem(Replace(strAryPair(0),"~",""),Replace(strAryPair(1),"~",""))
Next
lstHAssets.Items.Insert(0, "--Please Select--")
Return "ToSender"
End Function

Related

Delete file from server based on database query asp.net vb

I have a file folder that contains pdf files. The sql database is not directly related to the files. For example, I have "Invoice_co_355_24636.pdf" and "Invoice_co_355_25127.pdf" in the Invoices folder. I query the database and find that Invoice "24636" is not paid and "25127" is marked paid in full, so I would like to delete "Invoice_co_355_25127.pdf" at that point since it is paid.
So what I'm doing is getting all the file names from the folder, parsing each file to get just the last numbers, (which correlate to the database). If the database shows that one or more of the Invoices has been paid, I would like to delete the file.
I have successfully, (below), been able to parse the server file names as
"InvNo" as the parsed file name, (which corelates to the database), and
"InvNoFull", which is the full database file name that needs to be deleted if it is marked as paid in the database.
But after getting the file names and the parsed file names, I do not know how to actually compare it to the database and then delete. Any help is appreciated.
Dim files() As String = Directory.GetFiles(Server.MapPath("/Contents/Invoices/" + Variable.ToString() + "/Co/" + ddlCo.SelectedValue.ToString() + "/"))
For Each file As String In files
Dim InvNo As String = Path.GetFileNameWithoutExtension(file)
Dim InvNoFull As String = Path.GetFileName(file)
InvNo = InvNo.Substring(InvNo.LastIndexOf("_") + 1, InvNo.Length - InvNo.LastIndexOf("_") - 1)
Dim CnStr As String = (ConfigurationManager.ConnectionStrings("ClientConnectionString").ConnectionString)
Dim adp As SqlDataAdapter = New SqlDataAdapter("select OrderBilling.OrderId from orderBilling Left Outer Join Orders on OrderBilling.OrderId = Orders.OrderId Where Orders.CompanyId = " & ddlCo.SelectedValue.ToString() & " And Orders.OwnerId = " & Variable.ToString() & " And OrderBilling.PaidInFull = 'False'", CnStr)
Dim ds As DataSet = New DataSet()
adp.Fill(ds, "outBill")
For Each Row As DataRow In ds.Tables(0).Rows
For Each Coll As DataColumn In ds.Tables(0).Columns
Dim s As String = Row(Coll.ColumnName).ToString()
If s <> InvNo Then
Dim FileToDelete() As String
FileToDelete = Directory.GetFiles(Server.MapPath("/Contents/Invoices/" + Variable.ToString() + "/Co/" + ddlCo.SelectedValue.ToString() + "/" + InvNoFull))
If System.IO.File.Exists(FileToDelete.ToString()) = True Then
System.IO.File.Delete(FileToDelete.ToString())
'MsgBox("File Deleted")
End If
End If
Next
Next
Next
With help from Mary but this deletes all the files in the folder, but I want it to delete only the files not returned in the database query:
Private Sub DeletePaidInvoices(OwnerID2 As String, CompanyID As String)
Dim InvoicePath = "/Contents/Invoices/" & OwnerID2 & "/Co/" & CompanyID & "/"
Dim files() As String = Directory.GetFiles(Server.MapPath(InvoicePath))
Dim lst = GetInvoiceInfo(CInt(CompanyID), CInt(OwnerID2))
For Each file As String In files
Dim InvNo As String = Path.GetFileNameWithoutExtension(file)
Dim InvNoFull As String = Path.GetFileName(file)
InvNo = InvNo.Substring(InvNo.LastIndexOf("_") + 1, InvNo.Length - InvNo.LastIndexOf("_") - 1)
'Debug.Print(InvNo) 'To check your substring, will not be in release version
For Each i As Integer In lst
Dim s As String = i.ToString()
If s <> InvNo Then
Dim FileToDelete As String
FileToDelete = "Invoice_co_" & CompanyID & "_" & InvNo & ".pdf"
If System.IO.File.Exists(Server.MapPath(InvoicePath & FileToDelete.ToString())) = True Then
System.IO.File.Delete(Server.MapPath(InvoicePath & FileToDelete.ToString()))
End If
End If
Next
Next
End Sub
Call your delete method from, say, a button passing the variable from the user interface.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CompID = ddlCo.SelectedValue.ToString()
Dim OwnerID = "comes from somewhere"
DeletePaidInvoices(OwnerID, CompID)
End Sub
The delete method gets the file list. I have no idea about Server.MapPath but I assume you do. Next we get a List(Of Integer) representing the results of you database query (the OrderID's). Next we enter the For loop. I added a Debug line to see what is being returned by SubString code. As you can see it is simpler code to loop through a list.
Private Sub DeletePaidInvoices(OwnerID As String, CompanyID As String)
Dim InvoicePath = $"/Contents/Invoices/{OwnerID}/Co/{CompanyID}/"
Dim files() As String = Directory.GetFiles(Server.MapPath(InvoicePath))
Dim lst = GetInvoiceInfo(CInt(CompanyID), CInt(OwnerID))
For Each file As String In files
Dim InvNo As String = Path.GetFileNameWithoutExtension(file)
Dim InvNoFull As String = Path.GetFileName(file)
InvNo = InvNo.Substring(InvNo.LastIndexOf("_") + 1, InvNo.Length - InvNo.LastIndexOf("_") - 1)
Debug.Print(InvNo) 'To check your substring, will not be in release version
For Each i As Integer In lst
Dim s As String = i.ToString()
If s <> InvNo Then
Dim FileToDelete() As String
FileToDelete = Directory.GetFiles(Server.MapPath(InvoicePath & InvNoFull))
If System.IO.File.Exists(FileToDelete.ToString()) = True Then
System.IO.File.Delete(FileToDelete.ToString())
'MsgBox("File Deleted")
End If
End If
Next
Next
End Sub
The data retrieval is in a separate function. Use Using blocks to make sure your connections and commands are closed and disposed. Always use parameters with Sql Server. There is a bit of Linq magic at the end to create the list from the DataTable.
Private Function GetInvoiceInfo(CompanyID As Integer, OwnerID As Integer) As List(Of Integer)
Dim dt As New DataTable
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("ClientConnectionString").ConnectionString),
cmd As New SqlCommand("select OrderBilling.OrderId
from orderBilling
Left Outer Join Orders on OrderBilling.OrderId = Orders.OrderId
Where Orders.CompanyId = #CompanyID
And Orders.OwnerId = #OwnerID
And OrderBilling.PaidInFull = #Paid;", cn)
cmd.Parameters.Add("#CompanyID", SqlDbType.Int).Value = CompanyID
cmd.Parameters.Add("#OwnerID", SqlDbType.Int).Value = OwnerID
cmd.Parameters.Add("#Paid", SqlDbType.Bit).Value = False
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Dim lstOrderID As List(Of Integer) = (From dRow In dt.AsEnumerable() Select dRow.Field(Of Integer)(0)).ToList
Return lstOrderID
End Function
The actual deleting of the files (or moving to a Paid folder) is up to you.

Can't retrive image from mdb database this program show error "parameter in not valid"

Try
'connection string
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
Dim my_connection As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=D:\DataBase\KhandagramPS.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim DR As OleDbDataReader
'Dim source As String
'query string
Dim my_query As String = "SELECT sl_no,f_name,dob,sex,add,reg,[class],a_date,a_per,r_a_per,f_status,[name],photo,document FROM " & TextBox2.Text & " where sl_no=" & TextBox3.Text & " ;"
'create a connection
Dim my_dbConnection As New OleDbConnection(my_connection)
my_dbConnection.Open()
'create a command
Dim my_Command As New OleDbCommand(my_query, my_dbConnection)
DR = my_Command.ExecuteReader()
While (DR.Read())
txtslno.Text = (DR(0).ToString())
txtfname.Text = (DR(1).ToString())
Date1.Text = (DR(2).ToString())
comsex.Text = (DR(3).ToString())
txtadd.Text = (DR(4).ToString())
txtreg.Text = (DR(5).ToString())
comclass.Text = (DR(6).ToString())
Date2.Text = (DR(7).ToString())
txtaper.Text = (DR(8).ToString())
txtraper.Text = (DR(9).ToString())
txtfstatus.Text = (DR(10).ToString())
txtname.Text = (DR(11).ToString())
Dim ImageBuffer = CType(DR(12), Byte())
Dim imgStrm As New MemoryStream(ImageBuffer, True)
imgStrm.Write(ImageBuffer, 0, ImageBuffer.Length)
Dim img As Image = Image.FromStream(imgStrm)
PictureBox1.Image = img
End While
'close connection
my_dbConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
I suspect some error in your Byte-Array to Image conversion. Make sure that your Byte-Array is not messed up. Use this function instead.
Private Function getImage(imageBuffer as Byte())
Using ms as new IO.MemoryStream(imageBuffer)
Dim img = ImageIO.FromStream(ms)
Return img
End Using
End Function
my 2 cents: you shouldn't store images in an mdb file (unless things have changed a lot in the past few years). store images in a separate directory and store the file paths in the mdb so the image can be found when needed.

JSON.net - Using VB.NET Unable to iterate through results

I am trying to process this json document using JSON.NET.
With the VB.NET code:
Dim o As JObject = JObject.Parse(json)
Dim results As List(Of JToken) = o.Children().ToList
Dim count As Integer = 0
For Each item As JProperty In results
Dim snippet As String = String.Empty
Dim URL As String = String.Empty
Dim source As String = String.Empty
item.CreateReader()
Select Case item.Name
Case "response"
snippet = item.Last.SelectToken("docs").First.Item("snippet").ToString
URL = item.Last.SelectToken("docs").First.Item("web_url").ToString
source = ControlChars.NewLine & "<font size='2'>" & item.First.SelectToken("docs").First.Item("source").ToString & "</font>" & ControlChars.NewLine
tbNews.Text &= "<a href=" & URL & " target='new'>" & snippet & "</a> - " & source
End Select
Next
I am only receiving the first document as a result. Can someone advise as to how I can get the 1st - Nth documents as a complete list?
The docs are 2 levels deep, you're only looping in the top level. Try this...
Dim parsedObject = JObject.Parse(json)
Dim docs = parsedObject("response")("docs")
For Each doc In docs
Dim snippet As String = doc("snippet")
Dim URL As String = doc("web_url")
Dim source As String = doc("source")
'....
Next

Searching particular files in the folder

Hi I can search all the images with .jpg extension and pass it to the fancybox gallery , The issue is i just want the images of particular productid
for instance if a product has 5 images , and they are saved as (productid_imagenumber.jpg) , therefore a product with productid 99 will be saved as 99_1.jpg , 99_2.jpg similarly 99_5.jpg,
I can pass the productID but i cant find a away just to get the images of that productID , instead of getting all the images which is done by the function below:
Dim directory As DirectoryInfo = New System.IO.DirectoryInfo("C:Images\")
Dim allImages() = directory.GetFiles("*.jpg", SearchOption.AllDirectories)
Dim strContent As String = ""
For Each image As FileInfo In allImages
Dim strTemp As String = (String.Format("<img src=""{0}"" />", image.Name))
strContent = "<a class=""fancybox-thumb"" rel=""fancybox-thumb1"" href=""" & image.Name + image.Extension & """ title="""">" & _
"<img src=""" & image.Name + image.Extension & """ alt="" /></a>"
Next
If Not String.IsNullOrEmpty(strContent) Then
Return String.Format("<div id=""product-lightbox""><p>{0}</p></div>", strContent)
Else
Return String.Empty
End If
End Function
Can any one give any suggestion or assistance on how to do this.
Try this:
Dim images = (From img In directory.GetFiles("*.jpg", IO.SearchOption.AllDirectories)
Where img.Name.Contains("_") _
AndAlso img.Name.Split("_"c)(0) = productID).ToList
Ok, you are using .NET 2.0:
Dim allProductIDImages As New List(Of IO.FileInfo)
For Each img As IO.FileInfo In directory.GetFiles("*.jpg", IO.SearchOption.AllDirectories)
If img.Name.Contains("_") Then
Dim ID As String = img.Name.Split("_"c)(0)
If ID.Equals(productID) Then
allProductIDImages.Add(img)
End If
End If
Next
Another - possibly faster - approach is to let GetFiles pre-search:
Dim pattern As String = String.Format("*{0}_*.jpg", productID)
Dim allProductIDImages() As IO.FileInfo = _
directory.GetFiles(pattern, IO.SearchOption.AllDirectories)

exporting rdlc report into pdf on button click

Hi can any one help me out for this.
I have RDLC Report displayed on my web page using asp.net And C#.net I want to export it to PDF on button click.
Please can you help me?
Thanks
I did something like this a while ago. Below is the code I used in the page_load event of a page. It is in VB and isn't the best code in the world but might help you get a solution..
Dim jobid As Integer = Request("jobid")
Dim rv As New Microsoft.Reporting.WebForms.ReportViewer
Dim r As String = "apps/Reports/legal_document.rdlc"
Dim ds As New jobmanagerTableAdapters.JobInformationTableAdapter
Dim ds2 As New ordermanagementTableAdapters.RecoveryItemsInformationTableAdapter
Dim ds3 As New expensemanagerTableAdapters.tbl_expensesTableAdapter
Dim ds4 As New ordermanagementTableAdapters.tbl_orders_collection_itemsTableAdapter
Dim ds5 As New attachmentsmanagerTableAdapters.tbl_attachmentsTableAdapter
Dim ds6 As New notesmanagerTableAdapters.tbl_notesTableAdapter
Dim ds7 As New payments_managerTableAdapters.tbl_paymentsTableAdapter
Dim rptSource1 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource2 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource3 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource4 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource5 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource6 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptsource7 As New Microsoft.Reporting.WebForms.ReportDataSource
rptSource1.Name = "jobmanager_JobInformation"
rptSource1.Value = ds.GetJobInfobyJobID(jobid)
rptSource2.Name = "ordermanagement_RecoveryItemsInformation"
rptSource2.Value = ds2.GetRecoveryItemsbyJobIDOrderID(jobid, 0)
rptSource3.Name = "expensemanager_tbl_expenses"
rptSource3.Value = ds3.GetExpensesbyJobIDOrderID(jobid, 0)
rptSource4.Name = "ordermanagement_tbl_orders_collection_items"
rptSource4.Value = ds4.GetDataByJobIDOrderID(jobid, 0)
rptSource5.Name = "attachmentsmanager_tbl_attachments"
rptSource5.Value = ds5.GetAllAttachmentsbyJobID(jobid)
rptSource6.Name = "notesmanager_tbl_notes"
rptSource6.Value = ds6.GetAllNotesbyJobID(jobid)
rptsource7.Name = "payments_manager_tbl_payments"
rptsource7.Value = ds7.GetPaymentsbyJobID(jobid)
rv.LocalReport.DataSources.Clear()
rv.LocalReport.ReportPath = r.ToString
rv.LocalReport.DataSources.Add(rptSource1)
rv.LocalReport.DataSources.Add(rptSource2)
rv.LocalReport.DataSources.Add(rptSource3)
rv.LocalReport.DataSources.Add(rptSource4)
rv.LocalReport.DataSources.Add(rptSource5)
rv.LocalReport.DataSources.Add(rptSource6)
rv.LocalReport.DataSources.Add(rptsource7)
'Page.Controls.Add(rv)
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
'Get folder on web server from web.config
Dim FolderLocation As String
FolderLocation = Server.MapPath("reports")
'First delete existing file
Dim filepath As String = FolderLocation & "\legal.PDF"
File.Delete(filepath)
'Then create new pdf file
bytes = rv.LocalReport.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Dim fs As New FileStream(FolderLocation & "\legal.PDF", FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
Response.Redirect("reports/legal.pdf")

Resources