using csvhelper writer with shouldquote in vb.net - vb.net

I can see how shouldquote works with c# but does anyone have an example in vb.net?
I need to wrap every field with chr(34)

Private Sub Main()
Dim records = New List(Of Foo) From {
New Foo With {
.Id = 1,
.Name = "one"
}
}
Dim config = New CsvConfiguration(CultureInfo.InvariantCulture) With {
.ShouldQuote = Function(args) True
}
Using csv = New CsvWriter(Console.Out, config)
csv.WriteRecords(records)
End Using
End Sub
Public Class Foo
Public Property Id As Integer
Public Property Name As String
End Class

Related

How can I look for certain words in a file and then do something?

How can I look for certain words in a file then do something if any of the words were found?
I would like to do something if for example any of these words banana horse window whatever is found within a file.
Here is my last attempt
Dim thefile As String = "C:\application\thefile"
If File.Exists(thefile) Then
Using reader As New StreamReader(thefile)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains("Banana") OrElse line.Contains("horse") OrElse line.Contains("window") OrElse line.Contains("whatever") Then
msgbox("Word(s) found " & line)
Do_this_and_that()
Else
MsgBox("Word(s) not found")
Exit While
End If
End While
End Using
Else
msgbox("File not found")
End If
There seem to be so many variations of doing this, but I can't get them to work when its multiple words instead of just one. What is the easies and cleanest way of doing this?
You need to tokenize the line and use a HashSet. That is the fastest method. Put all the words in the HashSet and then check if each word is init:
static void Main()
{
var file = #"C:\application\thefile";
var hashSet = new HashSet<string>(new[] { "banana", "horse", "window", "whatever" }.Select(x => x.ToLower()));
foreach (var word in GetWords(file))
{
Console.WriteLine(word);
if (hashSet.Contains(word))
{
//DoSomething();
Console.WriteLine("\tFound!!");
//Continue or Break;
}
}
}
private static IEnumerable<string> GetWords(string file)
{
var rg = new Regex(#"[^\p{L}]");
const int bufferLen = 512;
using (var reader = File.OpenText(file))
{
var word = new StringBuilder();
while (!reader.EndOfStream)
{
var buffer = new char[bufferLen];
var readChars = reader.ReadBlock(buffer, 0, bufferLen);
for (int i = 0; i < readChars; i++)
{
if (rg.IsMatch(buffer[i].ToString()))//end of the word
{
if (word.Length > 0)
{
yield return word.ToString();
word = new StringBuilder();
}
}
else
word.Append(Char.ToLowerInvariant(buffer[i]));
}
}
if (word.Length > 0)
yield return word.ToString();
}
}
and here in VB
Imports System.Text.RegularExpressions
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Dim filename = "C:\application\thefile"
Dim words() As String = {"banana", "horse", "window", "whatever"}
Dim bagOfWords = New HashSet(Of String)(words.Select(Function(x) x.ToLower()))
For Each word As String In GetWords(filename)
Console.WriteLine(word)
If bagOfWords.Contains(word) Then
'DoSomething();
Console.WriteLine(vbTab & "Found!!")
'Exit For if you need to terminate here;
End If
Next
End Sub
Private Iterator Function GetWords(filename As String) As IEnumerable(Of String)
Dim rg = New Regex("[^\p{L}]")
Const bufferLen As Integer = 512
Using reader As New StreamReader(filename)
Dim word = New StringBuilder()
While Not reader.EndOfStream
Dim buffer = New Char(bufferLen - 1) {}
Dim readChars = reader.ReadBlock(buffer, 0, bufferLen)
For i As Integer = 0 To readChars - 1
If rg.IsMatch(buffer(i).ToString()) Then
'end of the word
If word.Length > 0 Then
Yield word.ToString()
word = New StringBuilder()
End If
Else
word.Append([Char].ToLowerInvariant(buffer(i)))
End If
Next
End While
If word.Length > 0 Then
Yield word.ToString()
End If
End Using
End Function
End Module
This might be a bit of a performance issue, but you can try using a List(Of String) :
Dim thefile As String = "C:\application\thefile"
Dim toCheck as New List(of String)
'You can fill up your list by whoever you want
toCheck.Add("banana")
toCheck.Add("horse")
'...
Dim FoundWords As New List(Of String)
If File.Exists(thefile) Then
Using reader As New StreamReader(thefile)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
'We check our list to see if it matches
For Each item in toCheck
if line.Contains(item) then
FoundWords.Add(item)
End If
Next
End While
End Using
If FoundWords.Count > 0 Then
msgbox(FoundWords.Count.ToString() & " Word(s) found")
Do_this_and_that()
Else
MsgBox("Word(s) not found")
End If
Else
msgbox("File not found")
End If
Now this can be improved but if you don't have thousand of words to look for that should do the trick...

How do I change the code from using Google.GData.Client to Google.Apis.Auth.OAuth2

I have this code from obsolete dll's,
It works, but I know there are new dll's Google.Apis.Auth.OAuth2 - Can I still use it?
Public sub Activate
_parameters = New Google.GData.Client.OAuth2Parameters With {
.ClientId = CLIENT_ID,
.ClientSecret = CLIENT_SECRET,
.RedirectUri = REDIRECT_URL,
.Scope = "https://docs.google.com/feeds/ ",
.State = "documents",
.AccessType = "offline"
}
Dim url As String = Google.GData.Client.OAuthUtil.CreateOAuth2AuthorizationUrl(_parameters)
context.WebRoot.Response.Redirect(url, False)
End Sub
Public Sub CallBack()
Dim state As String = context.WebRoot.Request.QueryString("state")
If Not state Is Nothing Then
_parameters.AccessCode = .WebRoot.Request.QueryString("code")
Google.GData.Client.OAuthUtil.GetAccessToken(_parameters)
End If
End Sub

Parsing in Json not in XML . VB.Net

At the moment I am using VB.Net.
I build my string, post it out and then parse the results.
Parsing Example for XML
Dim xml As New MWXMLDocument()
Dim sReason As String = "Unknown"
Try
xml.LoadXml(sresult)
If xml.SelectSimpleNode("AcceptedLead").InnerText = "true" Then
app.Outcome.RedirectURL = xml.SelectSimpleNode("result/redirecturl").InnerText
AcceptLead()
Return True
End If
sReason = xml.SelectSimpleNode("Reason").InnerText
Catch ex As Exception
sReason = "Error: " & ex.Message
End Try
DeclineLead(sReason)
Return False
End Function
How would I parse a result sent back in JSON, here is an example of the result I want to parse in using VB : Can i not just get the data from the string and parse as normal XML.
{"RedirectUrl":"www.test.com","Commission":5.0000,"Status":"accepted"}
You can use the JSON.NET Library
Example in C#:
var result = JsonConvert.DeserializeObject<RootObject>(string json);
The RootObject should be your own class.
You could use the .Net built in JavaScriptSerialiser
First add a reference to System.Web.Extensions and then
Imports System.Web.Script.Serialization
Followed by...
Dim sExampleJSON As String = "{""RedirectUrl"":""www.test.com"",""Commission"":5.0000,""Status"":""accepted""}"
Dim MySerializer As JavaScriptSerializer = New JavaScriptSerializer()
Dim MyDictionary As Dictionary(Of String, Object) = MySerializer.Deserialize(Of Dictionary(Of String, Object))(sExampleJSON)
If MyDictionary.ContainsKey("RedirectUrl") Then
Console.WriteLine(MyDictionary("RedirectUrl"))
End If
in global.asax.cs
using System.Data.Entity;
namespace RpManticSolAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
}
}
The complete Answer
sResult = sResult.Replace("""", String.Empty)
If sResult.Contains("Status:accepted") Then
Dim parts = sResult.Replace("{", String.Empty).Replace("}", String.Empty).Split(",")
For i As Int16 = 0 To parts.Length - 1
If parts(i).StartsWith("RedirectUrl") Then
app.Outcome.RedirectURL = parts(i).Substring(12)
End If
If parts(i).StartsWith("Commission") Then
lendertier.LenderComm = CDec(parts(i).Substring(11))
End If
If parts(i).StartsWith("ApplicationRef") Then
app.Outcome.LenderReference = parts(i).Substring(15)
End If
Next
AcceptLead()
Return True
End If
If sResult.Contains("Reason:Duplicate") Then
sReason = "Duplicate"
ElseIf sResult.Contains("{Error:invalid credentials") Then
sReason = "Error: Invalid credentials"
ElseIf sResult.Contains("ValidationErrors:") Then
sReason = "Invalid call:" + sResult.Replace("ValidationErrors:", String.Empty).Replace(",Status:rejected", String.Empty)
Else
sReason = "Rejected"
End If
DeclineLead(sReason)
Return False

Create own data examples in LinqPad

I have a class (vb.net) with some data that I want to query in LinqPad. I already worked with some examples as the one from "Linq in Action" so they work with some kind of classes with data as well to explain queries. But I just cannot find anything about how to import or write your own classes. Could anyone help me here?
My Class looks like:
Public Class Employee
Public Property ID As Integer
Public Property Salery As Integer
Public Property Name As String
Public Property Department As String
Public Property Gender As String
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .Department = "HR", .Gender = "Male", .Salery = 12000},
New Employee With {.ID = 2, .Name = "Sandra", .Department = "IT", .Gender = "Female", .Salery = 2000} _
}
End Function
End Class
You might be missing a couple things about using LINQPad:
Set the Language to "VB Program" and put classes where the comment says to.
Use the Dump method to output an expression. (For "VB Expression", Dump is called automatically.)
Here is an example. (Note, you might be using that SQL-looking syntax.)
Sub Main
Employee.GetAllEmployees() _
.Where(Function (employee) employee.Department = "HR") _
.Dump()
Dim hrEmployees = From employee In Employee.GetAllEmployees()
Where employee.Department = "HR"
hrEmployees.Dump()
End Sub
' Define other methods and classes here
Public Class Employee
Public Property ID As Integer
Public Property Salery As Integer
Public Property Name As String
Public Property Department As String
Public Property Gender As String
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .Department = "HR", .Gender = "Male", .Salery = 12000},
New Employee With {.ID = 2, .Name = "Sandra", .Department = "IT", .Gender = "Female", .Salery = 2000} _
}
End Function
End Class

Multiple Parameters in LINQ to SQL

I am trying to pass several search parameters to an LINQ expression to retrieve all entries that contain one of the search items.
Example:
Dim query = From p In db.BEW_PROFIL
For Each searchItem As String In searchItems
Dim item As String = searchItem
query = query.Where(Function(p) p.NAME = item)
Next
Problem here is I don´t get any results because the Where clause looks with that code something like this.
... Where p.NAME = item1 AND p.NAME = item2
What i need is an OR between the parameters, but I don´t get it how I can achieve this.
Any help would be greatly appreciated.
Got it...
void Main()
{
var searchItems = new string[] { "test", "past", "most", "last", "fast", "feast", "yeast", "cast" };
var query = from p in searchItems select new MyClass { Name = p };
Predicate<MyClass> whereClause = _ => false;
foreach (var item in searchItems)
{
var searchItem = item;
Predicate<MyClass> oldClause = whereClause;
whereClause = p => p.Name == searchItem || oldClause(p);
}
query = query.Where(p => whereClause(p));
query.Dump();
}
public class MyClass
{
public MyClass() { }
public string Name { get; set; }
}
The code was ran in LINQPad, and that returned every element.
Here is that code translated to Vb.Net
Private Sub Main()
Dim searchItems = New String() {"test", "past", "most", "last", "fast", "feast", "yeast", "cast"}
Dim query = From p In searchItems Select New [MyClass]() With { .Name = p }
Dim whereClause As Predicate(Of [MyClass]) = Function(element) False
For Each item As String In searchItems
Dim searchItem = item
Dim oldClause As Predicate(Of [MyClass]) = whereClause
whereClause = Function(p) p.Name = searchItem OrElse oldClause(p)
Next
query = query.Where(Function(p) whereClause(p))
query.Dump()
End Sub
Public Class [MyClass]
Public Sub New()
End Sub
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
End Class