VB.NET switching from ADO.NET to LINQ - vb.net

I'm VERY new to Linq. I have an application I wrote that is in VB.NET 2.0. Works great, but I'd like to switch this application to Linq. I use ADO.NET to load XML into a datatable. The XML file has about 90,000 records in it. I then use the Datatable.Select to perform searches against that Datatable. The search control is a free form textbox. So if the user types in terms it searches instantly. Any further terms that are typed in continue to restrict the results. So you can type in Bob, or type in Bob Barker. Or type in Bob Barker Price is Right. The more criteria typed in the more narrowed your result. I bind the results to a gridview.
Moving forward what all do I need to do? From a high level, I assume I need to:
1) Go to Project Properties --> Advanced Compiler Settings and change the Target framework to 3.5 from 2.0.
2) Add the reference to System.XML.Linq, Add the Imports statement to the classes.
So I'm not sure what the best approach is going forward after that. I assume I use XDocument.Load, then my search subroutine runs against the XDocument. Do I just do the standard Linq query for this sort of repeated search? Like so:
Dim people =
from phonebook in doc.Root.Elements("phonebook")
where phonebook.Element("userid") = "whatever"
select phonebook
Any tips on how to best implement?

This video shows you how to enable intellisense from XML documents. I use this extensively. Hopefully it helps:
http://www.asp.net/learn/linq-videos/video-216.aspx
Then you can use a list of items already selected to exclude those from the result set.

First, I should mention that var is used with C# and not VB.Net (use dim). Next, you can reuse you linq queries against the xml as often as you want. Unless something modifies the xml in memory, you should be ok.

Related

Access Queries in Visual Studio with Devexpress

I have recently decided to re-develop an access VBA application in VB .net with DevExpress.
I have managed to figure out databinding with the raw tables. However, I am struggling with the queries.
I have tried the query builder, but I dont have the option to save them and bind object to it. I assume it works this way? As it did in access? Or is the query builder there simply to help you format the SQL text?
I am trying to bind a DataGrid to a simply join query without any luck.
Can you someone point me in the right direction?
Thanks.
There are two main approaches that I can think of. One is to use datatables, and the other is to use domain objects.
Datatables are quick to write, can easily handle most of the heavy lifting for you (including CRUD operations) and are pretty scalable, as changes to the underlying object can be handled relatively easily.
DataTable dt = new DataTable();
Domain Objects (aka POCOs) take a lot of up-front work but typically in the log run make for a more bulletproof and robust solution. Plus, there are frameworks and even Micro ORMs that will do much of the heavy lifting for you, if you choose to use them.
List<DomainObject> do = new List<DomainObject>();
These work with tables, views or queries. You mention you have this figured out for a table, so I'm guessing you have already sort-of gotten this far.
So, first step -- figure out which direction you want to go. (pick domain objects)
Second step -- I recommend using a binding source (System.Windows.Forms.BindingSource). Make your data table / collection the DataSource for the binding source.
Third step, make the binding source the data source for your grid. If you are using a Domain Object, you'll see the columns populate automatically.
From there, once the datatable or collection is populated, you can assign it as the data source for the binding source, and .NET and Dev Express will take care of the rest for you.
bindingSource1.DataSource = dt;
or
bindingSource1.DataSource = do;
Now if you're talking CRUD operations -- that's a horse of a different color. You still use these as building blocks, but this is in no way a comprehensive answer for that.
By the way, the code above is C#, so you need minor tweaks to get this to be VB. I don't speak VB, otherwise I would have just done it like that to begin with.

Extract labels from serialized array using SQL

I do not have control of how this data is stored (I know as normalized data would be better for sql), because it is saved via the WordPress GravityForms plugin. The plugin uses a serialized array to define the question id (field_id), question label (label). My goal is to extract these three values in the following format:
field_id label
1 1. I know my organization’s mission (what it is trying to accomplish).
2 2. I know my organization’s vision (where it is trying to go in the future).
Here is the serialized array.
Can anyone please provide a specific example as to how to parse these values out with sql?
A specific example, no. This kind of stuff is complex. If your are working with straight json-formatted data, here are several options, none of which are simple.
You can build your own parser. Yuck.
You can upgrade everything you have to just-released SQL 2016, and hope that the built-in json tools do what you need (I've heard iffy things about them, but don't know what their final form is like. Too, updating all your database servers right now, oh sure.)
Phil Factor over on SimpleTalk built a json T-SQL parser (https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/). It looks horrible and may run poorly, but it would do the needful.
Buried in the comments of that article are links to a CLR tool that John Galt built (at https://github.com/jgcoding/J-SQL). I have used this successfully, though I haven't done anything too complex. (If you're json is relatively simple, this could do the trick.)
There are other json parsers for SQL out there, some free, some for sale. The key thing would be to not try and write your own, but rather find and use someone else's solution that addresses your requirements.

When to use DataBinding with SQL in WPF

I have a table in SQL that I want to read into a DataGrid.
When I insert a new element I would like the DataGrid to update automatically.
Currently I manually do a SQL query and create a custom object that represents the objects in my SQL.
I am wondering whether I could use DataBinding but also maintain some control over how the data is read in? Because I'd like to have a local model to work with. Or is it just simpler to manually redownload the table after every insert?
Thanks
Yes of course. Using Entity framework, to pull the data, and then bind it to a control (or a complex form with many tabs) - and allowing the EF to do all the hard work for You is the way to go ...
Just imagine - if You have a complex model with a lot of controls, and when You hit save.. it just does that and generates as many inserts or updates for you.
with just one line of code. Context.SaveChanges :)

VB.NET: Properly manage data from XML

Good morning all.
I'm relatively new to the Visual Basic realm (although a traditional web based script developer), i've come to ask you a question. I am reading data from an XML file. This local XML file will be updated by another application, and I will need to periodically re-evaluate the XML file, and only import new data into a list box. Furthermore, I want to be able to click on a particular item in the listbox, and display the other values about that particular XML entry.
So, I suppose this is a multi part question. What is the proper way to import only NEW data into the program, what is the proper way to store the data, and how do I associate a value in a listbox with the data stored elsewhere?
I've considered multidimensional arrays, but have been told that strings to char arrays and then back to strings is a terrible way to manage the data, but was never offered an alternative.
I will be satisfied with a list of topics to study up on and/or an example for an answer to this question.
I would probably use classes that implement INotifyPropertyChanged and a BindingList. Then you just need to listen to ListChanged events off of the list and update the list box then.
I have a blog post that discusses binding classes and interfaces if you want to learn more about them: Data Binding Classes, Interfaces, and Attributes in Windows Forms 2.0. It might be a little dated by now, I haven't reviewed it since I wrote it in March, 2007.
As a start look at the XmlDocument and XmlReader classes.
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx
XmlDocument helps load a document into memory and allows you to look at the document in any way you desire, depending on the size of the file there may be implications as to how long pulling in the file takes
XmlReader allows access on the fly, and gives you access very much like a DataReader. I.e. keeping track of your position in the dataset and not retaining any data once you have inspected it.
For keeping a track of updates, it depends where the XML is stored.
If it is in a file a FileSystemWatcher may help in determining when you need to update....
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

Generate LINQ query from multiple controls

I have recently written an application(vb.net) that stores and allows searching for old council plans.
Now while the application works well, the other day I was having a look at the routine that I use to generate the SQL string to pass the database and frankly, it was bad.
I was just posting a question here to see if anyone else has a better way of doing this.
What I have is a form with a bunch of controls ranging from text boxes to radio buttons, each of these controls are like database filters and when the user hits search button, a SQL string(I would really like it to be a LINQ query because I have changed to LINQ to SQL) gets generated from the completed controls and run.
The problem that I am having is matching each one of these controls to a field in the database and generating a LINQ query efficiently without doing a bunch of "if ...then...else." statements. In the past I have just used the tag property on the control to link to control to a field name in the database.
I'm sorry if this is a bit confusing, its a bit hard to describe. Just throwing it out there to see if anyone has any ideas.
Thanks
Nathan
When programming complex ad-hoc query type things, attributes can be your best friend. Take a more declarative approach and decorate your classes, interfaces, and/or properties with some custom attributes, then write some generic "glue" code that binds your UI to your model. This will allow your model and presentation to be flexible, without having to change 1000s of lines of controller logic. In fact, this is precisely how Microsoft build the Visual Studio "Properties" page. You may even be able use Microsoft's "EnvDTE.dll" in your product depending on the requirements.
You could maybe wrap each control in a usercontrol that can take in IQueryable and tack on to the query if it is warranted.
So your page code might go something like
var qry = from t in _db.TableName
select t;
then pass qry to a method on each user control
IQueryable<t> addToQueryIfNeeded(IQueryable<t> qry)
{
if(should be added)
return from t in qry
where this == that
select t;
else
return qry
}
then after you go through each control your query would be complete and then you can .ToList() it. A cool thing about LINQ is nothing happens until you .ToList() or .First() it.
I don't know about the performance here, but if you set up the LINQ to SQL data context class you should be able to query a database table with a .Select(...) or .Where(...). You should be able to build lambda expressions for either of these dynamically. You might look into dynamic generation of lambda expressions for this purposes. I have done everything up to the point of the dynamic lambda generation, but it is possible.
I'm not 100% sure how to achieve this but I know where a good place to start would be, in the ASP.NET MVC source. In recent versions it is capable of taking the form response and pass it into a helper method which does the writing to a LINQ data source.
I believe MVC is C# so if you're looking for a VB translation you could try using .NET Reflector and converting it back to VB.
I think you are searching how to create a "Dynamic" Linq Query, Here is an example about how to do it with a library of extension methods. Those methods take string arguments instead of type-safe language operators.
I don't mind sfusco's method by using attributes. The only thing that i'm not sure of is where to attach the attributes to because If I attach then to the controls declaration which is in the designer code it will get regenerated when the form changes.
Or am I completely misunderstanding sfusco's methods?
I think perhaps the right way to do this would be an extender provider: MSDN documentation
Then, you can use the editor to provide the field names to hook up with, and your extender provider can be passed an IQueryable<T>, add the criteria, and return an IQueryable<T>.