VB.Net and XDocument - Group By - asp.net

I have the following code which I need to amend to group by offer but I'm not sure how to add in the group by part in this query.
Any ideas?
propertyInfo = myXmlFile.Descendants("offer").Descendants("site") _
.Where(Function(f) _
f.Attributes("code").First.Value = Location.Text) _
.Select(Function(f) New With { _
.LOCATION = f.Attributes("code").First.Value, _
.TITLE = f.Parent.Attributes("title").First.Value, _
.OFFER = f.Parent.Attributes("offerid").First.Value, _
.POPUPDESC = f.Parent.Descendants("short_desc").Value
Example XML
<offers>
<offer title="Offer title" offerid="AS32">
<short_desc><![CDATA[
<div>Your HTML's body <a href='dfgdfgdfgdfg.html'>Offer title</a>
</div>
]]></short_desc>
<site code="CO">
<year_week_start>201344</year_week_start>
<year_week_end>201414</year_week_end>
</site>
<site code="FH">
<year_week_start>201446</year_week_start>
<year_week_end>201450</year_week_end>
</site>
</offer>
</offers>

I think you need to be a little more specific in what you want after you group. It's pretty easy to group, but then you get an enumerable of groups:
propertyInfo = myXmlFile.Descendants("offer").Descendants("site") _
.Where(Function(f) _
f.Attributes("code").First.Value = Location.Text) _
.Select(Function(f) New With { _
.LOCATION = f.Attributes("code").First.Value, _
.TITLE = f.Parent.Attributes("title").First.Value, _
.OFFER = f.Parent.Attributes("offerid").First.Value, _
.POPUPDESC = f.Parent.Descendants("short_desc").Value) _
.GroupBy(Function(f) f.OFFER)

Related

Scapy AsyncSniffer fails if stop() is called right after start()

Look at the following example
a = AsyncSniffer()
a.start()
a.stop()
a.stop() will throw an exception. Is there a way to fix this without adding a time.sleep() between the start() and stop()?
this ofcourse is a contrived example but the code in our project has the same problem if I create a test stub in between the start() and the stop()
Update:
tracebak from pycharm run:
FAILED [100%]
test_async_sniffer.py:3 (test_async_sniffer)
self = <scapy.sendrecv.AsyncSniffer object at 0x7f1d57a7f1f0>, join = True
def stop(self, join=True):
"""Stops AsyncSniffer if not in async mode"""
if self.running:
try:
> self.stop_cb()
E AttributeError: 'AsyncSniffer' object has no attribute 'stop_cb'
venv/lib/python3.8/site-packages/scapy/sendrecv.py:1017: AttributeError
During handling of the above exception, another exception occurred:
def test_async_sniffer():
a = AsyncSniffer()
a.start()
> a.stop()
test_async_sniffer.py:7:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <scapy.sendrecv.AsyncSniffer object at 0x7f1d57a7f1f0>, join = True
def stop(self, join=True):
"""Stops AsyncSniffer if not in async mode"""
if self.running:
try:
self.stop_cb()
except AttributeError:
> raise Scapy_Exception(
"Unsupported (offline or unsupported socket)"
)
E scapy.error.Scapy_Exception: Unsupported (offline or unsupported socket)
venv/lib/python3.8/site-packages/scapy/sendrecv.py:1019: Scapy_Exception
A possible answer although not pretty:
a = AsyncSniffer()
a.start()
if not hasattr(a, 'stop_cb'):
time.sleep(0.06)
a.stop()
seems the start() creates the attribute stop_cb, and if stop() is called right after start() the stop_cb has not been created yet, so I add an hasattr with a sleep (testing shows 0.06 secs is sufficient time but I guess it's very arbitrary)

Paypal SDK problems

Goodmornig,
I have some problems with the integration of SDK paypal, I have the IPN that works nice, now I was trying to do the first request, instead of the form client side, the call server side, to be more safe.
I have put in my bin folder Paypal.dll and Newtonsoft.Json.dll then I have configurated the web.config
This is what I have read when I downloaded the Paypal nuget from Visual.
ATTENTION: This package replaces the RestApiSDK package (https://www.nuget.org/packages/restapisdk). You do not need to include the RestApiSdk package in your project if you are using this, the PayPal .NET SDK, package.
The PayPal REST API uses HTTP verbs and a RESTful endpoint structure. OAuth2.0 is used as the API Authorization framework. Request and response payloads are formatted as JSON.
I usually dont use editor, I have downloaded Visual just to get out these dll.
Then I have copied them inside my Web ASP.NET application.
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="live" />
<add name="connectionTimeout" value="360000"/>
<add name="requestRetries" value="1"/>
<add name="clientId" value="xxx" />
<add name="clientSecret" value="yyy" />
</settings>
</paypal>
And then I have translated the c#.net script sample to vb.net, this is the code
<%# Page Language="VB" Debug="true" aspcompat=true%>
<%# Import Namespace="MySql.Data.MySqlClient" %>
<%# Import Namespace="PayPal.Api" %>
<%
' Initialize an APIContext object with a fresh access token.
' The config will be populated with values set in the Web.config file.
Dim config = ConfigManager.Instance.GetProperties()
Dim accessToken = New OAuthTokenCredential(config).GetAccessToken()
Dim apiContext = New APIContext(accessToken)
Dim abc = Payment.Get(apiContext, "6N135681R73257100")
%>
I have put the ID of the transaction and I have this kind of error
PayPal.HttpException: The remote server returned an error: (404) Not Found.
If I try to do a payment so to do like this
<%# Page Language="VB" Debug="true" aspcompat=true%>
<%# Import Namespace="MySql.Data.MySqlClient" %>
<%# Import Namespace="PayPal.Api" %>
<%
' Initialize an APIContext object with a fresh access token.
' The config will be populated with values set in the Web.config file.
Dim config = ConfigManager.Instance.GetProperties()
Dim accessToken = New OAuthTokenCredential(config).GetAccessToken()
Dim apiContext = New APIContext(accessToken)
' Initialize Payout object
Dim payout = New Payout() With { _
.sender_batch_header = New PayoutSenderBatchHeader() With { _
.sender_batch_id = "batch_" + System.Guid.NewGuid().ToString().Substring(0, 8), _
.email_subject = "You have a payment" _
}, _
.items = New List(Of PayoutItem)({ _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "0.99", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-one#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_1" _
}, _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "0.90", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-two#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_2" _
}, _
New PayoutItem() With { _
.recipient_type = PayoutRecipientType.EMAIL, _
.amount = New Currency() With { _
.value = "2.00", _
.currency = "USD" _
}, _
.receiver = "shirt-supplier-three#mail.com", _
.note = "Thank you.", _
.sender_item_id = "item_3" _
} _
}) _
}
' Create the payout
Dim createdPayout = payout.Create(apiContext, False)
%>
I have this kind of error, Did I forgot to copy inside my project anything? How could I fix it? Thank you very much
PayPal.HttpException: The remote server returned an error: (403) Forbidden.

How to convert PDF pages to PNG using Ghostscript Wrapper VB.NET?

I'm trying convert from digitally signed PDF to PNG using this solution: Simple VB.Net Wrapper for Ghostscript Dll. It doesn't work for me too. I'm using Ghostscript 9.18 32bits.
First, the source code goes to InOutErrCallBack method in this part:
gsapi_init_with_args(InstanceHndl, NumArgs + 1, Args)
When this occurr, the execution freeze. After this occurs, the next calls to RunGS method returns false in this part:
If gsapi_new_instance(InstanceHndl, IntPtr.Zero) <> 0 Then
Return False
Exit Function
End If
The return value of gsapi_new_instance is -100:
Ghostscript API - Return codes
The gswin32.dll is in C:\Windows\System32 and BIN project folder.
My parameter sequence:
Dim outputImgPath As String
outputImgPath = "C:\Download\DocumentosV2\Protocolo\Pronunciamento\" + Guid.NewGuid.ToString("N") + ".png"
Dim args() As String = { _
"-dNOPAUSE", _
"-dBATCH", _
"-dSAFER", _
"-dQUIET", _
"-sDEVICE=png16m", _
String.Format("-r{0}", resolucao), _
"-dTextAlphaBits=2", _
"-dGraphicsAlphaBits=2", _
String.Format("-dFirstPage={0}", pageNumber), _
String.Format("-dLastPage={0}", pageNumber), _
String.Format("-sOutputFile={0}", outputImgPath), _
"-f", _
pdfPath _
}
UPDATE
#kens advise me for some arguments. So, I remove it to test.
My Complete code:
Imports PdfSharp
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports PdfSharp.Drawing
'''
''' http://www.geekscrapbook.com/2009/11/16/c-method-to-add-an-image-to-a-pdf/
'''
Public Class PDF2Image2PDF
Inherits Simp.Net.Infra.SimpComponent
Private SyncRoot As New Object
'Converte cada página do PDF em imagem
Public Function Pdf2Png(ByVal pdfPath As String, ByVal resolucao As Int32) As Image()
Dim outputImgPath As String
Dim pageCount As Integer
Dim objPdfReader As New iTextSharp.text.pdf.PdfReader(pdfPath)
pageCount = objPdfReader.NumberOfPages()
Dim objImages As New ArrayList
For pageNumber As Int32 = 1 To pageCount
outputImgPath = "C:/Download/DocumentosV2/Protocolo/Pronunciamento/" + Guid.NewGuid.ToString("N") + ".png"
Dim objFileStream As FileStream
Dim objMemoryStream As MemoryStream
'Dim args() As String = { _
' "-dNOPAUSE", _
' "-dBATCH", _
' "-dSAFER", _
' "-dQUIET", _
' "-sDEVICE=png16m", _
' String.Format("-r{0}", resolucao), _
' "-dTextAlphaBits=2", _
' "-dGraphicsAlphaBits=2", _
' String.Format("-dFirstPage={0}", pageNumber), _
' String.Format("-dLastPage={0}", pageNumber), _
' String.Format("-sOutputFile={0}", outputImgPath), _
' "-f", _
' pdfPath _
' }
Dim args() As String = { _
"-dNOPAUSE", _
"-dBATCH", _
"-sDEVICE=png16m", _
String.Format("-dFirstPage={0}", pageNumber), _
String.Format("-dLastPage={0}", pageNumber), _
String.Format("-sOutputFile={0}", outputImgPath), _
Replace(pdfPath, "\", "/") _
}
If GhostscriptDllLib.RunGS(args) Then
If File.Exists(outputImgPath) Then
objFileStream = New FileStream(outputImgPath, FileMode.Open)
Dim length As Int32 = objFileStream.Length
Dim bytes(length) As Byte
objFileStream.Read(bytes, 0, length)
objFileStream.Close()
objMemoryStream = New MemoryStream(bytes, False)
objImages.Add(Image.FromStream(objMemoryStream))
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Next
Return CType(objImages.ToArray(GetType(Image)), Image())
End Function
'Converte cada imagem do vetor em uma página do PDF
Public Function Images2PDF(ByVal imagens() As Image) As PdfDocument
Dim pdf As PdfDocument
Dim gfx As XGraphics
Dim ximg As XImage
pdf = New PdfDocument
For Each img As Image In imagens
pdf.AddPage(New PdfPage)
gfx = XGraphics.FromPdfPage(pdf.Pages.Item(0))
ximg = XImage.FromGdiPlusImage(img)
gfx.DrawImage(ximg, 0, 0)
ximg.Dispose()
gfx.Dispose()
Next
Return pdf
End Function
End Class
The Caller code:
Public Sub DownloadPeticionamento(ByVal sender As System.Object, ByVal e As System.web.UI.ImageClickEventArgs)
Dim imagem As ImageButton = DirectCast(sender, ImageButton)
Dim pdfPath As String = imagem.DescriptionUrl
Dim objPdfPeticionamento As New Simp.Net.Negocio.PDF2Image2PDF
Dim objImages() As Image
Dim objPdfDoc As PdfDocument
objImages = objPdfPeticionamento.Pdf2Png(pdfPath, 600)
objPdfDoc = objPdfPeticionamento.Images2PDF(objImages)
objPdfDoc.Save(Me.Page.Response.OutputStream, True)
End Sub
I test this in command line to:
gswin32c -dNOPAUSE -dBATCH -sDEVICE=png16m -sOutputFile=C:/Download/DocumentosV2/Protocolo/Pronunciamento/fb21872746b64f8fb31b3764b5444e2e.png C:/Upload/DocumentosV2/Protocolo/Pronunciamento/3_0_404702190_2016_10081288_230_0_f1f09b4b38ac49a8a3e5576f6041eea3.pdf
Via command line, the pdf is converted. The command line output:
C:\Documents and Settings\leandro.ferreira>gswin32c -dNOPAUSE -dBATCH -sDEVICE=png16m -dFirstPage=1 -dLastPage=1 -sOutputFile=C:/Download/DocumentosV2/Protocolo/Pronunciamento/fb21872746b64f8fb31b3764b5444e2e.png C:/Upload/DocumentosV2/Protocolo/Pronunciamento/3_0_404702190_2016_10081288_230_0_f1f09b4b38ac49a8a3e5576f6041eea3.pdf
GPL Ghostscript 9.16 (2015-03-30)
Copyright (C) 2015 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
Can't find (or can't open) font file %rom%Resource/Font/Arial-BoldMT.
Can't find (or can't open) font file Arial-BoldMT.
Can't find (or can't open) font file %rom%Resource/Font/Arial-BoldMT.
Can't find (or can't open) font file Arial-BoldMT.
Querying operating system for font files...
Didn't find this font on the system!
Substituting font Helvetica-Bold for Arial-BoldMT.
Loading NimbusSan-Bol font from %rom%Resource/Font/NimbusSan-Bol... 4047240 2487522 8937716 7603550 3 done.
Can't find (or can't open) font file %rom%Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Can't find (or can't open) font file %rom%Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Didn't find this font on the system!
Substituting font Helvetica for ArialMT.
Loading NimbusSan-Reg font from %rom%Resource/Font/NimbusSan-Reg... 4080352 2580805 9014744 7662839 3 done.
C:\Documents and Settings\leandro.ferreira>
-100 is simply 'fatal error' ie something really bad happened. More information is generally printed to stdout or stderr, of course setting -dQUIET will suppress much of this....
Since you are getting -100 returned its almost certainly the case that your arguments to Ghostscript are incorrect in some way.
The absolute first thing you should do when debugging problems is to try and simplify the problem, so remove any switches that you don't unquestionably require.
So the first thing to do is to remove the -dQUIET, capture all the stdout/stderr output and tell us what it says.
Further to that, note the following:
You don't need '-f' because the only purpose of that switch is to terminate -c which you haven't used.
You haven't given the values of 'resolucao', 'pageNumber', or 'pdfPath' or so there's no way to know if those are valid (or sensible). The path you have specified for outputImgPath is quite long, and includes the backslash character. I would advise using the forward slash '/' instead, as backslash is used to begin an escape and can give results you may not expect.
You've also used -dSAFER, do you understand the implications of specifying this ? If not, remove it and try again.
When you have created the string 'args' print it out. At the very least this will give you something you can try from the command line, and may mean that other people have some chance of reproducing your problem.
Finally; please note that Ghostscript is distributed under the Affero General Public Licence, please be sure to read the licence and ensure that you are conforming to the terms contained therein.
To do this work, I modified the Simple VB.Net Wrapper for Ghostscript Dll CallBack:
Private Function InOutErrCallBack(ByVal handle As IntPtr, _
ByVal Strz As IntPtr, ByVal Bytes As Integer) As Integer
Dim objString As String
objString = Marshal.PtrToStringAnsi(Strz, Bytes)
System.Diagnostics.Debug.WriteLine(objString)
Return Bytes
End Function
This wrotes the Ghostscript output into the Output window's Visual Studio 2003. I removed the extra "needless" arguments to Ghostscript, like -dGraphicsAlphaBits. The asp.net user does not access the Path.GetTempDir, so, I need a different "temp" dir.
'Converte cada página do PDF em imagem
Public Function Pdf2Png(ByVal pdfPath As String, ByVal tempDirPath As String, ByVal resolucao As Int32) As Image()
Dim outputImgPath As String
Dim pageCount As Integer
Dim objPdfReader As New iTextSharp.text.pdf.PdfReader(pdfPath)
pageCount = objPdfReader.NumberOfPages()
Dim objImages As New ArrayList
For pageNumber As Int32 = 1 To pageCount
outputImgPath = tempDirPath + Guid.NewGuid.ToString("N") + ".png"
Dim objFileStream As FileStream
Dim objMemoryStream As MemoryStream
'Dim args() As String = { _
' "-dNOPAUSE", _
' "-dBATCH", _
' "-dSAFER", _
' "-dQUIET", _
' "-sDEVICE=png16m", _
' String.Format("-r{0}", resolucao), _
' "-dTextAlphaBits=2", _
' "-dGraphicsAlphaBits=2", _
' String.Format("-dFirstPage={0}", pageNumber), _
' String.Format("-dLastPage={0}", pageNumber), _
' String.Format("-sOutputFile={0}", outputImgPath), _
' "-f", _
' pdfPath _
' }
Dim args() As String = { _
"-dNOPAUSE", _
"-dBATCH", _
"-sDEVICE=png16m", _
String.Format("-dFirstPage={0}", pageNumber), _
String.Format("-dLastPage={0}", pageNumber), _
String.Format("-sOutputFile={0}", outputImgPath), _
Replace(pdfPath, "\", "/") _
}
If GhostscriptDllLib.RunGS(args) Then
If File.Exists(outputImgPath) Then
objFileStream = New FileStream(outputImgPath, FileMode.Open)
Dim length As Int32 = objFileStream.Length
Dim bytes(length) As Byte
objFileStream.Read(bytes, 0, length)
objFileStream.Close()
objMemoryStream = New MemoryStream(bytes, False)
objImages.Add(Image.FromStream(objMemoryStream))
File.Delete(outputImgPath)
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Else
Throw New InvalidOperationException("Erro ao converter páginas do PDF em imagens PNG")
End If
Next
Return CType(objImages.ToArray(GetType(Image)), Image())
End Function

How to add an addition Of T to a System.Linq.Iqueryable

I was in the middle of writing this post, but to the great help of stackoverflow I found a hint that helped me solve my issue, but I wanted to post this in order to help other developers if they come accross this issue and are new to VB.NET, ASP.NET and MVC5.
I have a variable of type faqs declared as System.Linq.IQuerable(Of ViewModels.FaqViewModel) 'Note I created a FaqViewModel to pass the Model data that is needed to view.
However, there might be times when the query results are null, but I need to pass at least one item back to the view in order to show some results and return the original search query back to the search box.
Here is my code, what am I missing?
VIEW
--- #ModelType IEnumerable(Of CompanyName.ViewModels.FaqViewModel)
CONTROLLER
Function SearchFaqs() As ActionResult
Dim url As String
Dim txtSearchTerm As String
If Request("txtSearch").IsNullOrWhiteSpace() Then
txtSearchTerm = ""
Else
txtSearchTerm = Request("txtSearch")
End If
url = Request.UrlReferrer.ToString()
Dim faqs = (From f In _db.Faqs _
Where Not f.Hk_DeletedDt.HasValue _
And f.Question.Contains(txtSearchTerm) _
Or f.Answer.Contains(txtSearchTerm) _
Or f.Hk_DeletedDt = New DateTime(1900, 1, 1) _
And f.Active = 1 _
Order By f.CategoryId Descending _
Select New FaqViewModel With {
.Question = f.Question,
.Answer = f.Answer,
.SearchTerm = txtSearchTerm
})
If Not faqs.Any() Then
faqs.Union(Of FaqViewModel)(IEnumerable)
'(New FaqViewModel With {
' .Question = "Your Search did not contain any results please try again.",
' .Answer = "",
' .SearchTerm = txtSearchTerm
' })
End If
Return View("Faq", faqs)
End Function
What I found to fix the problem.
**CONTROLLER UPDATED, simply converted to a .ToList !!! **
<HttpPost>
Function SearchFaqs() As ActionResult
Dim url As String
Dim txtSearchTerm As String
If Request("txtSearch").IsNullOrWhiteSpace() Then
txtSearchTerm = ""
Else
txtSearchTerm = Request("txtSearch")
End If
url = Request.UrlReferrer.ToString()
Dim faqs = (From f In _db.Faqs _
Where Not f.Hk_DeletedDt.HasValue _
And f.Question.Contains(txtSearchTerm) _
Or f.Answer.Contains(txtSearchTerm) _
Or f.Hk_DeletedDt = New DateTime(1900, 1, 1) _
And f.Active = 1 _
Order By f.CategoryId Descending _
Select New FaqViewModel With {
.Question = f.Question,
.Answer = f.Answer,
.SearchTerm = txtSearchTerm
})**.ToList**
If Not faqs.Any() Then
**Dim noResultsFaq As New FaqViewModel
noResultsFaq.Question = "Your Search did not contain any results please try again."
noResultsFaq.Answer = ""
noResultsFaq.SearchTerm = txtSearchTerm
faqs.Add(noResultsFaq)**
End If
Return View("Faq", faqs)
End Function

Asp.Net Linq and XML query

I'm trying to grab some data using LINQ and a "WHERE" function within my "SELECT" function
Here's my sample XML
<Items>
<Extras>
<Extra Code="TEST1" Quantity="1" />
<Extra Code="TEST2" Quantity="1" />
</Extras>
<Options>
<OptionalExtra Description="Test 1" Code="TEST1" type="TESTING1" />
<OptionalExtra Description="Test 2" Code="TEST2" type="TESTING2" />
</Options>
</Items>
And here's my LINQ query
bookingsInfo = xel.Descendants("Extras").Descendants("Extra") _
.Select(Function(f) New With { _
.Code = f.Attributes("Code").First.Value, _
.Type = f.Parent.Parent.Descendants("Options").Descendants("OptionalExtra") _
.Where(Function(g) g.Attributes("Code").First.Value = _
f.Attributes("Code").First.Value).Attributes("type").First.Value, _
.Quantity = f.Attributes("Quantity").First.Value _
})
The "TYPE" is the problem I'm having trouble getting and I'm not really sure what the issue is.
I don't have any control of how the XML is laid out but I can edit the LINQ query no problem.
Does anyone have any suggestions?
Thanks in advance
I think it will be easier to use Join instead of Parent.Parent:
Dim bookingsInfo = From e In xel.Root.<Extras>.<Extra>
Join o In xel.Root.<Options>.<OptionalExtra> On e.#Code Equals o.#Code
Select New With {
.Code = e.#Code,
.Type = o.#Type,
.Quantity = e.#Quantity
}

Resources