Introduction

Introduction

 This is the first topic Next topic

Introduction

 This is the first topic Next topic

These eNotes, published in 'CHM' format, are designed to be ONLY for the attendees of 'DevShare13', or

registered folks - we have the odd 'virtual' attendee!

The session(s) presented by PHH at the event will be based on a set of 'Power Point' slides - one for

LINQ and one for Metro. Both these will refer to 'Phone8' when it makes good sense to do so, simply

because there is often a lot of overlapping of underlying skills and technologies.

After the Conference / Event :

I suggest that any guy wishing to use LINQ and Metro stuff in their app development, go back home to

their office and work through the slides first, then work through the subsections of these eNotes - for the

two main sections, on LINQ and Metro.

There are three 'bare-bone' sections which were added a long time ago, and which for many reasons did not

get filled out.

Since LINQ is such and over-riding topic in itself, the 'LINQ' section became an 'umbrella' section which

then incorporated many ideas which were previously planned to be presented in the other sections.

Anyway, for good or bad, the bare-bone sections remain as 'bullet' points, to help you structure your learning.

Deeper Learning and more Detailed Development :

Although a lot can be learned from the details within the subsections of these 'Event' notes, there is also a

much fuller 'walk-through' style, more detailed set, in the 'ClickStart' library itself.

There are now many 'growing' eVolumes within the 'ClickStart' library, and the main menu URL is as below :-

http://www.winclickstartvulcan2.net/ClickStartExec2.html?introduction.htm

The subsection entitled 'Quick Links to Volumes' is as follows at this moment in time :-

===================================================================================================================

As you can see above there are eVolumes existing which are targeted at most of the FIVE sub-topics of

these CHM 'event' notes.

It is my intention to keep the web notes fully up to date as I come across new topic areas within any volume, and

when my research and development work here in my office means that I am doing new stuff, not previously

well documented in my eNotes.

What have you got 'Special' in the conference material ? :

You do need to realise that although the general details are available to all web users, these 'Event' eNotes in CHM

format are a special attempt by myself to make a lot of 'overview' summaries and comparisons, not at any other

place in my 'walk-through' eNotes.

For this main reason it should serve you well as a start to understanding just what is going on with LINQ, Metro,

Phone8 and SQL data support in WPF, Metro and Phone8.

For WCF you need to go straight to the 'ClickStartMETRO' eNotes, as well as the 'WCF' ones third from the bottom of the

above list.

Good Luck with your learning ...........

PHH - 23rd. September 2013.


ClickStart web site material

ClickStart web site material

 Previous topic Next topic

ClickStart web site material

 Previous topic Next topic

In some form or another, all of my research and development efforts end up on my web site called

'ClickStart'.

At the moment the main entry point for this is with the link shown below - at URL 'winClickStartVulcan2.net' :-

http://www.winclickstartvulcan2.net

To gain access to the separate 'volumes' of the eNotes use the main menu page below :-

http://www.winclickstartvulcan2.net/ClickStartExec2.html?introduction.htm

The main eVolumes you need, to support what I have been studying for 'DevShare13' are as follows :-

LINQ :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartLINQ/ClickStartLINQ.html

Metro / WinRT :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartMETRO/ClickStartMETRO.html

Entity Framework 4, and beyond :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartEF/ClickStartEF.html

Windows 'Phone 8', and beyond :

http://www.winclickstartvulcan2.net/webNotes/ClickStartPhone8/ClickStartPhone8.html

WCF - Communication Foundation :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartWCF/ClickStartWCF.html

MVVM and Prism :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartPrism/ClickStartPrism.html

XAML 'mark-up' scripting - across WPF, Metro, and Phone :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartXAML/ClickStartXAML.html

WPF and desktop related app 'stuff' :

http://www.winclickstartvulcan2.net/WebNotes/ClickStartWPF/ClickStartWPF.html

You may like to look at others, like T-SQL, its up to you ;-0))

See you in the next sub-section ......................

PHH - 23rd. September 2013.


PowerPoint slides to accompany these eNotes

PowerPoint slides to accompany these eNotes

PowerPoint slides to accompany these eNotes

 Previous topic Next topic

For 'DevShare13' which starts on October 10th. 2013, I have prepared two Power Point

slide presentations.

These PPPs are really a smaller 'summary' of the material I have prepared for this CHM format

file for the event.

This CHM detailed file has lots of working material, much of which is in the 'walk-through' style, where

Visual Studio 2012 is used to make demo and trial apps from the very beginning.

So using the CHM file, section by section, will hopefully teach you a lot about VS use, and XAML scripting

as well, as you move through the mini projects.

Here is how the PPPs look when they are opened, and available from the task bar - check this out :-

==================================================================================

The reason I spent quite some time making the PPPs, even though the detailed material is all there in

the CHM file, is that it is CRUCIAL to get an overview of a lot of this stuff - LINQ and Metro in particular.

If you gain a solid understanding of the 'overview', then it will be much easier to fit in all of the specific small

details which come along with the topic areas involved.

Here is another file view of the two PPPs :-

==============================================================================================

I am to make a 'DropBox' folder for all attendees to share with me, after the completion of the event.

Here is how it looks on my desktop at the moment - some guys like Alwyn, Paul and Willie have helped

me do some initial testing. Check this :-

======================================================================

And within the 'DevShare13' folder we will have a sub-folder for each speaker - like this :-

====================================================================

The older image is now updated with Fabrice's name :-

=====================================================================

And the current contents of my sub-folder looks like this :-

======================================================================================================

In the above image we can clearly see the two PPPs as well as my CHM file.

Yes, the CHM file is what you are reading now ;-0)) If you have done things correctly !

Lets move on .....................

PHH - 23rd. September 2013.


PP slides with video functionality

PP slides with video functionality

PP slides with video functionality

 Previous topic Next topic

What to Look out for :

Just so that you know what you could be missing ;-0) I will inform you now that a few of the slides within the PPPs

contain video playback controls, linked to some trial applications, running as either Desktop, Tablet or Phone apps.

When you hover the mouse pointer over the bottom part of such a video playback control / image, you will see that an

extra control bar comes into 'existence' - or is shown.

Here is an example - check the bottom section :-

=================================================================================================================

As you can see above we get a pause and play icon displayed, as well as a progress bar. Below is shown a larger

image / view of the same control - (yes, it is in edit screen mode .... )

===================================================================================

And when we toggle the play / pause we see :-

====================================================================================

Finally a shot and screen capture, of the real thing when the PPP is is 'Show' mode :-

========================================

*** late NOTE ***

I have tried to find and 'mark' in the title, each video slide as seen in the image below - check this :-

========================================================

Moving on a pace ...................

Why have a Video at all ? :

Well the answer to this is both easy for me to tell, and also easy to understand by yourselves ;-0)

There are great limitations with showing developed apps running, either from the previous EXE status,

or from the build and run environment of VS 2012.

These days the IT world is complex compared to 5 years ago, and it is a time wasting diversion to have

presenters going in and out of apps, running and showing, and then going back to prepared notes.

It gets increasingly difficult to move over platforms with demo / trial apps, and it is now almost impossible to

provide working apps to attendees, now that Metro and Phone licences are required etc., etc..

EXE files can't be passed for Metro & Phone8 as we did for WPF. The user has to have VS installed, and

they also must have a licence.

So the simple and effective answer is to make an on-screen video of parts of apps running, and show the

user input by mouse pointer or finger touch.

Then this means that attendees only need to be able to run PowerPoint, to see SQL apps working, and also

Metro apps with the Simulator, as well as Phone apps with the Emulator - running under 'Hyper-V' and a

Virtual machine.

All you need is 'PP Viewer' - free download :

As well as removing all the complexity of requiring development 'heavy' software to be able to see apps

running, with my PPPs you don't even need to have a copy of Office installed.

Microsoft provide a FREE download of a 'Viewer' application - see the following detailed images :-

======================================================================================

And now this one :-

===============================================================================================================

And finally, this one :-

==================================================================================================

I have not continued with running the install simply because I don't with to mess with my installed full

version of Office.

Good Luck with your downloads - if you need it that is !

Lets move on ...................

PHH - 23rd. September 2013.


other Learning Material

other Learning Material

other Learning Material

 Previous topic Next topic

Information on Books and eBooks is supplied in the following half a dozen sub-sections.

I have used eBooks a GREAT deal in the last year or so and vastly prefer them to paper copies for

the purpose of learning at the keyboard. The search facility is particularly helpful and useful.

However, there is an increasing amount of useful material available on the web as short training

web casts - even from the large corporations like Microsoft..

Look for quality material of this type (web cast) and be aware of LOTS of low grade published articles

on newer technology - where the authors just do not know enough. Their backgrounds are shallow !

Usually they don't seem to have an 'overview' of the technology.

I have come across plenty of poor material in my searching. The problem with short articles from

Tom, Dick, and Harry, is that they make what should be straight forward stuff look quite complicated

and complex - which is just not the case :((

LINQ is a great example of this - something that is overcomplicated, and confused in the many articles

available on the web. But it does not have to be like that.

TAKE CARE !!!

PHH - 23rd. September 2013.


LINQ

LINQ

LINQ

 Previous topic Next topic

I include in this subsection details of the three books and eBook which I used to learn LINQ.

They seem to be serving me very well as currently I am over half way and going along nicely.

The first two publications I got in hard copy format - i.e. 'Books' to you and me. The third one

I got in eBook (PDF) format only, as I find it easier to work on my three screens that way.

I bought this next book a while back but it is still most useful :-

ISBN 13 : 978-0-7356-2391-0

Now the eBook format :

I got my eBook from O'Reilly - an on-line purchase.

ISBN : 978-0-735-64057-3

Now move on to 'Metro' books ........................

PHH - 23rd. September 2013.


Metro / 'WinRT'

Metro / 'WinRT'

Metro / 'WinRT'

 Previous topic Next topic

Books & eBooks :

There are a few useful books and eBooks on the market - each seems to bring

'something to the party'.

I find eBooks far preferable to paper books when working at a PC and developing

code, script, and applications.

[ Good for 'SQLite' database work ]

With Early Release ebooks, you get books in their earliest form — the author's raw and unedited

content as he or she writes — so you can take advantage of these technologies long before the

official release of these titles.

You'll also receive updates when significant changes are made, new chapters as they're written,

and the final ebook bundle. This early release update is for chapters 11 and 12.

If you want to build Windows 8 applications for desktops and the forthcoming Microsoft Surface

tablet PC, this book will show you how to work with the Metro design language and the Windows RT

operating system.

You’ll learn this new landscape step-by-step, including the minute system details and design

specifications necessary to innovate and build a variety of Windows 8 apps.

It’s ideal for .NET developers who use C#.

================================================================================

Windows® 8 Apps with XAML and C# Unleashed

Copyright © 2013 by Pearson Education

All rights reserved. No part of this book shall be reproduced, stored in a retrieval

system, or transmitted by any means, electronic,mechanical, photocopying, recording,

or otherwise, without written permission from the publisher. No patent liability is

assumed with respect to the use of the information contained herein. Although every

precaution has been taken in the preparation of this book, the publisher and author

assume no responsibility for errors or omissions. Nor is any liability assumed for

damages resulting from the use of the information contained herein.

ISBN-13: 978-0-672-33601-0

ISBN-10: 0-672-33601-4

Library of Congress Cataloging-in-Publication Data is on file.

Printed in the United States on America

First Printing December 2012

=========================================================

ISBN :- 978-1-4302-1-4302

Source Code On-Line :

http://www.apress.com/9781430244912

PHH - 23rd. September 2013.


Phone 8

Phone 8

Phone 8

 Previous topic Next topic

=====================================================

https://skydrive.live.com/view.aspx?resid=2CD1217F16DF98FD!42997&app=WordPdf

PHH - 23rd. September 2013.


Entity Framework

Entity Framework

Entity Framework

 Previous topic Next topic

Book and eBook - Julia Lerman :

Make sure you get at least the 'second' edition of this book.

Julia Lerman is quite a recognised Guru and author / speaker on this subject, so I am not sure if you need

any other reference text after her edition two eVolume of this title.

I will see how I go myself, and let you know if I feel a definite need to another input source of any note.

==========================================================================================

===================================================================

PHH - 23rd. September 2013.


WCF

WCF

WCF

 Previous topic Next topic

PHH - 23rd. September 2013.


XAML

XAML

XAML

 Previous topic Next topic

A useful book to have to hand is as shown :-

PHH - 23rd. September 2013.


SQLite

SQLite

SQLite

 Previous topic Next topic

SQLite :

For our database work in Metro / Modern we need 'SQLite'.

Here is a very suitable book and eBook to purchase and use.

Here is some useful information on this work by the man himself - D. Richard Hipp :-

And a snip about the author :-

Now we need to see the other details of the publication :-

PHH - 23rd. September 2013.


LINQ - 'Objects from the start'

LINQ - 'Objects from the start'

LINQ - 'Objects from the start'

 Previous topic Next topic

"Full meaning of LINQ is ‘Language Integrated Query’, which replaces the traditional

sql query execution process. "

==========================================================================

This is what Ian Griffiths (author of Programming C# 5.0 - O'Reilly) says :-

"LINQ’s introduction in 2007 significantly changed the way I write C#, and that’s entirely

because of LINQ to Objects.

Although LINQ’s syntax makes it look like it’s primarily a 'data access' technology, I have

found it to be far more valuable than that.

Having LINQ’s services available on any collection of objects makes it useful in every part

of your code."

==========================================================================

Simply put - this (LINQ) is the BEST thing I have discovered, or come across, in the world of ICT in

the last 18 months, and that includes other things like SSD devices, Windows 8, and Metro

(Modern) and Phone 8 app development.

LINQ makes the lives of all .NET developers more like the dream that it should be.

LINQ does more to making the world of 'Object Coding' a full and 100 % reality since WPF

and XAML, and data binding.

LINQ allows us to process all of our data in a declarative fashion, and one with is object oriented.

Now with LINQ, we can make our whole app solution an 'object experience'. LINQ at one end, and

Data Binding at the other.

If we are using data from a back-end data source, we can sift our focus from the database with

its tables, rows and columns, into the application itself, when we start using objects from the word

go - and I mean 'go'.

LINQ applies to C# and its memory objects, as well as collections made by other technologies, like

Code First, Entity Framework 4+, and even ' sqlite-net ' in Metro.

*** WARNING *** SQLite in Metro is NOT very LINQ compliant :((

"Rule 1" - LINQ is all about 'Collections'.

Basically collections are lists - lists with certain special properties.

Collections can be in memory, or brought into memory by other technologies.

Other technologies like 'LINQ to SQL' Entity Framework, and ' sqlite-net' provide the collections on

which the LINQ syntax can then work. Any Microsoft product tends to be fully LINQ friendly / compatible.

'LINQ to Objects' is simply when we use LINQ standard syntax of memory resident collections.

Microsoft technologies do, but third party stuff like ' sqlite-net ' does not, and leaves a lot to

be desired - luckily we can get around most of these shortcomings ;-) But it is not an ideal

situation.

Lets take a peep :

In the image below I have used an example from my working samples written for ClickStart. The example

finds all the objects of type 'StatesOftheUS' which have data stored in the DB table of the same name.

=======================================================================================================

It is customary to use ' var ' as shown on line 61.

However, we do NOT need to be using a collection derived from a back-end data source, we could be

using an in-memory collection. RAM resident, like the List<T> and ObservableCollection<T> classes.

The LINQ syntax works on all collections as loon as the technology being used provides a suitable one.

By this I mean that the code " from X in WHATEVER " part of our LINQ query, needs the collection type

of the "WHATEVER" object to be suitable to the C# compiler.

The reason I warn about this is because Microsoft technologies are always correct in this respect, but

give us a false feeling of security when we need to reach for freely available alternatives like 'SQLite'.

I have found that 'SQLite' is not a good citizen of the LINQ world, although I can make it work well enough

within the Metro/WinRT environment.

It seems to me that as soon as M$ give me their alternative to SQLite for the Surface RT tablet, then that

is what I will use, simply because it it be 100% LINQ compatible.

I wish to do things the new, clean, and easy way, not the older fashioned way I show later in these eNotes.

Lets move on ........................

PHH - 26th. June 2013.


" No comment ! "

" No comment ! "

" No comment ! "

 Previous topic Next topic

If you search Charles Petzold's new book on "Programming Windows - Sixth Edition" for the

text string "LINQ" you get three hits - one of which is in the standard directives at the head of a sample.

Needless to say that SQL has no hits at all.

Adam Nathan's Win 8 book gives us 5 with two being in directives, and therefore not counting, as they

are meaningless.

However, his book gives eight hits for a search on SQL, and are all for 'SQLite' comments in tips boxes.

His comment is, if you are interested in using a local database then go find it out for yourself :((

Matthew Baxter-Reynolds gives us nine (9) hits for LINQ - six of which are in two related shortish paragraphs.

However, on the bright side, M B-R had '155' reference search hits to SQL - and it was he who got me into

SQLite with Metro / Modern.

It was new to me, completely, and I now have it working VERY well in WinRT.

So although MB-R is into SQL he has obviously NOT discovered the joys of LINQ - shame really.

My Windows Phone 8 eBook gives me 93 hits for LINQ - that's a whole lot better. This is by Andrew Whitechapel

and Sean McKenna.

And 127 is the total hits in the same book for a 'SQL' search. Needles to say they cover "LINQ to SQL" as part

of their most useful text.

On the other hand when I searched the "Programming C# 5.0" eBook by Ian Griffiths I found a healthy 477 hits.

(Yes, four hundred and seventy seven.)

Pages 335 - 389, quite a reasonable 'chunk' I feel.

Unfortunately, on the down side, we see that all the content is Lambda expression based, and therefore more

'Procedural' than 'Descriptive :((

The text presented in the above book does NOT look as interesting, and exciting, as LINQ really is!

Shame :((

PHH - 12th. September 2013.


Cross-Platform Considerations

Cross-Platform Considerations

Cross-Platform Considerations

 Previous topic Next topic

You may be interested in this URL / web link as it is well written and researched by a knowledgeable woman,

however, she does not consider the existence of LINQ within C# and the benefits that gives us as developers.

I suggest you take a few minutes of your time to check out her article.

The question is - can Xamarin provide us with LINQ - I would guess not - BUT - I could well be proved wrong on this.

Yep! - I am wrong ;-0) Check out the following link :-

http://xamarin.com/how-it-works

==========================================================================================

And here is what is specifically said about LINQ :-

[ .. note that it refers to SQLite .. ]

=====================================================================================================================================

So there you have it 'Xamarin' and LINQ - LINQ for Cross-Platforms - Wow !!!

But how does this affect the process of publishing with Microsoft for Store Apps, and others of course !?

============================================================================================

http://msdn.microsoft.com/en-us/magazine/dn385713.aspx

============================================================================================================================

========================================================================================================================

*** WARNING *** - if the LINQ support for SQLite in Xamarin is like that for SQLite in WinRT then it is minimal to say the least.

This would mean grabbing all Table records and then when they were in "In-Memory" objects (collections) process them

again using LINQ - which is there because C# has full capability.

For LINQ to work with the SQLite the capability is outside of the Xamarin compiler - as with WinRT and SQLite for the

Surface tablet.

At the moment Xamarin is very new to me and I need more time to explore the depths of its 'possibilities' !

See you in the next section ................

PHH - 11th. September 2013.


LINQ is not SQL in .NET code !

LINQ is not SQL in .NET code !

 Previous topic Next topic

LINQ is not SQL in .NET code !

 Previous topic Next topic

Okay then guys, time to explore the urban myth that LINQ is a code form of SQL.

LINQ has nothing really to do with SQL per-say, but both technologies have a querying syntax

which is what we call 'declarative' in nature - or descriptive.

The syntax, or way we write the code, is more related to the problem we are trying to solve than the

way the computer and software has to go about solving it.

Microsoft has been trying to make more aspects of its C# object oriented .NET framework 'declarative'

for quite some time now.

The ADO.NET namespace was quite old fashioned in this respect, and certainly not 'declarative' in nature.

I used it to good effect, but it did not feel right as a modern solution to programming.

Although ADO.NET is undoubtedly used 'under the hood' in LINQ technology, we as coders do not have to

dig any deeper than the LINQ standard syntax that we study in a few sub-sections time. Thank GOD !!!

So LINQ has many similarities to what we put into SELECT statements for T-SQL, and also the features it

possesses - like set operators.

Because the T-SQL script, and the SQL database engine, was designed to handle data issues, and solve data problems,

then we must have in LINQ a good way of dealing with data. This is why LINQ is so useful to the app designer.

Lets move on a pace ...........

Another Difference :

SQL query statements deal with tables, but LINQ deals with Collections of object items, or items for short.

So SQL is very much row and column oriented, but LINQ is fully custom (or business) object related.

Do you have to be a SQL Server expert ? :

The answer to this is no, you can start straight away with LINQ, and you don't have to create a database either ;-)

But don't start falling off your chair until you read the next part, just below this.

Do you need to worry about possessing any SQL 'skills' or having SQL 'expertise' ? :

Arhhh ! This is different, since many SQL skills are skills associated with the declarative way of solving data

related problems, then the answer to this is probably YES !!!

In fact if we ignore setting up databases using the manual way, then the rest of what guys may learn form past SQL

experience is probably very much an asset when we come to LINQ.

Despite what colleagues say who are inexperienced with SQL, the LINQ technology does not mean the coder needs

to know nothing or very little of SQL- that is an urban myth !

In fact my thoughts after a few years experience are that LINQ will serve you best if you have a wide experience with

using declarative select querying statements, Joins, Inner and Outer, Grouping, and set operators like Union, Intersect,

and Except. The more real experience you have with SQL the better a LINQ coder you will be.

What makes LINQ different to SQL ? :

One simple thing springs to mind. In SQL we have 'one go' at forming and sending a SELECT statement, so everything

needs to be included and incorporated into it.

However, with LINQ, we can use multiple queries, one using another, so we can write simpler queries each time. Only

when the data is required does the system send the compiled 'complete' query to the SQL database engine. So at that

point it uses the 'nested' queries of ours, to compose a single more complex SELECT query to send to the Server.

It would appear that the underlying 'system' uses our many simpler queries to compile (or build) one much more

complex statement, which is then sent in one go via the underlying ADO.NET stuff to the server.

This is the aspect that non-SQL guys should relish, in fact I use it happily myself. If we design and write simpler code

then we have far less chance to make mistakes - usually we are thinking of logical ones with 'queries'.

LINQ is about data selection, and getting returned object collections from our query which is sent to the Server.

There are other SQL statements which may be required which need to be sent directly to the Server, and by-pass LINQ.

A great example of this is the text statement which makes a back-up copy of the database.

Out of interest I will include a image shot below - note lines 129 - 131 where the statement is composed :-

==================================================================================================

In the above image line 137 is where we send the text statement to the SQL database engine (the Server).

Notice that the extension method called 'ExecuteCommand' is effectively passing the script straight through

to the server, and the C# compiler is not making a statement for us, as it does with LINQ.

Lets move on .........

Do Remember :

Because we are often working with persisted data sources, it is easy to forget that LINQ works with in memory collections.

When we do access SQL and other back-end data sources, the first thing that happens is that a supporting technology,

like 'LINQ to SQL', makes a suitable collection upon which the rest of the query statement works.

If we are using LINQ with any collection other than List<T> and ObservableCollection<T>, then the 'DataContext' of the

supporting technology is what generates the collection ready for use - or 'DbContext' for EF4.

'DataContext' / 'DbContext' :

We will look in detail at 'DataContext' and 'DbContext' classes later, in section "source of the possible Collections".

For now lets just get the idea in our head the if we are using something other than RAM based 'LINQ to Objects' as

out technology for providing a collection, then we do need a special class to provide our collection.

'DataContext' belongs to "LINQ to SQL" (L2S) and 'DbContext' belongs to "LINQ to Entity".

These are both classes.

'SQLite' does it slightly differently, and in any case is a poor LINQ Citizen, so we look to work-arounds :((

Let us see DataContext is action - for L2S. Below we are sub-classing to be able to specify our our Table property :-

=====================================================================================================

Above we use the base class to define our own sub-class, this is needed when we are using Code First,

rather than and existing database with the 'Data First' approach.

Once we have a DataContext object we can apply our LINQ code / syntax to it - check this out :-

==================================================================================================

So in the above code we have on line 113 an object called 'OurStates' which is a suitable collection type

made by the L2S technology from Microsoft.

Just to lighten the tone of this section, lets see some nice results, even if they are a bit black / white :-

=======================================================

This is live output from an app which gets data returned from a SQL database. It is actually a Phone 8 app.

Before we move on and leave this section take the following into your mind ..............

*** CARE *** - LINQ to XML is something different - it is NOT a LINQ provider !!!

So happily that is one less thing to worry about ;-)

See you in the next section ................

PHH - 29th. August 2013.


Collections

Collections

Collections

 Previous topic Next topic

To put it quite simply, if you are to use LINQ then you have to use 'collections'.

There are two collections that I have used successfully with WPF, WinRT and Phone8, and these

are List<T> and ObservableCollection<T> (OC).

And it is easier than that since an OC can be instantiated from a List<T> object.

Both these collection bind well with UI element in the XAML mark-up.

Let us look first at the code for creating the 'List' flavour of a collection.

And obviously, before we have a collection of similar object items, we need to have a suitable class of

custom objects.

Below is a simple class definition and a static method to create a test object List - check this out :-

====================================================================================================

So in the image above we have a simple class called 'myContacts' which has four properties of varying

data type.

We have both an empty constructor, and also one which takes four parameters, one for each property.

The static method member makes a list collection of hard coded 'myContacts' objects.

In order to use this list we need to call on just a few .NET code lines as shown in the following image :-

==================================================================================================

In the above code, line 27 retrieves the data collection, and line 29 binds it to the XAML UI control.

The control happens to be an LLS ('LongListSelector') on the Windows Phone 8 platform.

This is all the .NET code which is necessary to produce the following output at runtime :-

====================================================

The fundamental parts of the XAML script required is shown below :-

===============================================================================

Okay, I hear your complaints, we need to be able to read the data, not the object types.

So we need to add a 'DataTemplate' which we can do right now - check this out :-

===================================================================================================

Since we have been tidy and put the data template script in the Resources section, then we need to

script the 'ItemTemplate' attribute association, with a value, as seen below :-

===================================================================================

And when we get every detail right we see the following rather nice display :-

======================================================

However, I lost some time while doing this - read on below ..................

Tips & Tricks - WARNING :

If by mistake you leave off the 'Public' from the properties, then the default value of 'Private' is used.

This seems to have no other effect on our code and script - here in this example - but we do get a

confusing screen output display :((

First look at the code that we should NOT use - check below :-

==============================================================================

And now see what we get is this is the case, and our properties are set to 'Private' :-

===========================================

There are no issues thrown up at the XAML editor or designer surfaces - but it can take a while

to get ones mind off the fact that the 'DataTemplate' is wrong in some way or another ;-0))

Moving on a pace or two ..................

'ObservableCollection' class and use :

Because I have been using a Phone 8 app to illustrate the above detail, we now need to add another

namespace to the head of our main page code file :-

===========================================================

This may well be different for Metro and also WPF - *** apparently not, I have just checked in Help Viewer 2.0

and this must be a rare occurrence indeed - all are the same !

Below we see how an existing List<T> may be used to instantiate an OC, and how it binds in a similar manner

to the list - check this out :-

====================================================================================================

And the result of the code changes can be seen in the following image :-

================================================================

I changed the background colour to be a check with myself that I have indeed got the correct image.

Lets move on ...................

Differences between List<T> and ObservableCollection<T> :

Lets talk briefly about data binding, and what we expect to so on the UI display at runtime.

As you can see above, it is very easy to bind a collection to a UI control, however, if you wish the display

to respond / react to changes in any property of the collection objects which are used in binding, and hence

displayed, then we need to add extra code to our defined 'item class'.

The big test for this is when we change in code a property of a particular item which is in focus on the UI surface,

and whether the value is seen to be displayed as the change occurs.

We handle property changes by adding an event to our custom item class of type 'INotificationChanged'.

If we set the binding mode correctly then these two things will cause our code and app to shown any changes

in the appropriate manner.

So then what of the OC ? Well, an 'ObservableCollection' is effectively a wrapper around the List<T> and

handles the changes in the collection itself - so it causes notification of changes to the collection, not the item

property values.

So in code, if we add or remove items from the collection which is already bound, then these will be reflected in

the displayed collection, as long as we have the binding mode set correctly.

'INotifyCollectionChanged' is the event which is handled by the OC for us. It is easy to implement and use an OC.

Differences in item order of the collection can be handled in a couple of ways, but this comes at a level above

that which we are talking at the moment.

Demonstration of OC responsive behaviour :

Before we can build and run our app we need to add some lines of code.

We need to make some class properties (variables) of our required List<T> and ObservableCollection<T>.

Then we need to add a Button to our GUI so that at a click we can remove the last collection item by code.

Here is what we need :-

============================================================================

So let us now use these properties in our Initialise method :-

=================================================================================================

Okay then, the above code sets up the UI control of the 'LongListSelector' with an OC.

So what does our Button and its 'click' even handler look like ?

Check these out thoroughly :-

==================================================================================================

And now the handler code itself :-

=================================================================================================

As you can see above, nothing startling or difficult, it all seems to make good sense.

Yes, I know, we could have set things up so the length of the list was a bound property to the message box,

or similar - BUT - we need to keep some things simple so that we can see what is really going on.

Let us now see some images of the app being run and how it looks as collection items are removed.

Check these images :-

==========================================================================================================

As you can see above, the click of the button removes the last collection item - then shows the new state

of the collection in the UI element.

I do not know what will happen if I keep going till nothing remains ;-)

I shall try this out now ............... yep! eventually the app crashes - not surprising !!

Lets stop the crash and trap the 'empty' condition on the collection :-

==========================================================================================

And here is the screen capture proof of it working :-

===================================================

Lets move on ...........

Summary :

So if you have a collection as List<T> and you do not intend to have it change, then just bind the List.

If in doubt, because you do not know how the app will develop with time, then us an OC just in case.

I suggest you read the next sub-section in which the aspect of 'INotificationPropertyChanged' is dealt with.

See you in the next sub-section .....................

PHH - 28th. August 2013.


Suitable Classes - 'Notification' of property changes

Suitable Classes - 'Notification' of property changes

Suitable Classes - 'Notification' of property changes

 Previous topic Next topic

So guys, what are we after in this subsection ?

Well, quite simply put, if we change a property in code during app execution, then if this property is

bound to a UI element, and is on display, we expect the change to be immediately shown in the GUI

surface.

So lets get to work ..................

We need to add another namespace to the head of our code file - this is for Phone 8 so you may need

to use the Help Viewer 2.0 search facility if you are doing WPF or WinRT/Metro.

Check this out :-

================================================================================================

And now the changes to our classes. Below I have changed our very simple sample class called 'myContacts'

to have all the parts necessary for carrying any property changes from code through to the GUI.

The first big change is on line 39 where the class needs to 'implement' the interface shown below :-

==========================================================================================

In the above code I have done things just as the SDK docs suggest, with private data fields and

public properties. That can be changed by the user is they so wish - I am showing the 'basic' way.

Note the each private field - marked with a leading underscore so we the developer can easily distinguish -

has an accompanying public property and as things stand we have Get/Set for each - once again the

coder/developer can modify that.

The BIG thing is that when any property is set it calls the 'NotifyPropertyChanged' method with the name

of the property being set, as the input parameter.

You don't need to call the method for every property - only those which are used for binding and display.

Now then, we need to see how to code and use the Event and its calling method - checkout below :-

===================================================================================================

The same code syntax and format is usable in every class, no need to change it.

And now we need a Button to allow us to try and change by code a property on the last item in the

collection - the 'Name' property will be used, so we need to change 'Test Dummy' to something much

more appropriate ;-0)

Check the following code to handle the Button's click event :-

===========================================================================================

Yep! 'Might Mouse' it is - will we see it change ?

Here is what I have just generated on my screen - the button is being held down by my

mouse button press :-

===============================================================

It happened straight away, no time delay, just what we were after.

So to round all this up, we now have suitable collections (OCs) and suitably coded item classes,

which handle the GUI interaction well, while they are bound in the XAML script.

Changes in both collection item properties, and collection contents, will be displayed and reflected in

the GUI surface.

Time to move on ...............

PHH - 29th August 2013.


C# compiler syntax - WPF, WinRT, and 'Phone 8'

C# compiler syntax - WPF, WinRT, and 'Phone 8'

C# compiler syntax - WPF, WinRT, and 'Phone 8'

 Previous topic Next topic

Remember at all times that the format of the LINQ standard syntax is consistent across all Microsoft

coding platforms.

I have used the same LINQ style code in all three of WPF, WinRT and Phone 8. And Silverlight users

may well be using the same 'stuff' as well.

Any limitations come from the collections used in in the first line of a LINQ query statement. I found this

out while researching SQLite with Metro apps.

The easier and most appropriate way to see LINQ in action is to study how it is written and used with

collections in memory (RAM).

We tend to call this 'LINQ to Objects' as 'Objects' are seen as constructs in memory.

Once we get to using LINQ to Objects then we can apply the same approach to other collection sources.

Other we will look at are 'LINQ to SQL' (only applies to Microsoft SQL Server), LINQ to Eniity', and also

LINQ to SQLite or more correctly "LINQ to ' sqlite-net' ".

Be warned, only the Microsoft products / offering provide full LINQ support. So my advice is whenever possible

stay clear of third party products.

Let make a start ...............

"LINQ to Objects" - standard LINQ syntax :

Lets start out as simple as we can - lets take our OC object 'myOC' and apply some LINQ syntax to it :-

============================================================================

So what type of class / object is our 'query' - let use IntelliSense to find out, check this below :-

=======================================================================================================================================

It is not as we may have expected, a List<myContacts> type. We will come back to this in just a few seconds.

First lets see what happens if we bind this collection to our UI element :-

================================================================

In the next image we see nothing - check this out :-

=========================================================

Oh! dear, what can be done to improve this situation ? :((

Well it is very easy, we just convert the query collection back into a standard List<T> one using

a provided method - check below :-

================================================================================================================

by adding an extra line of code, and amending another, we now see this at runtime :-

=========================================================

And here is the extra class property we needed to add, so that we could have the collection

available throughout out test code sample :-

==============================================================================

Please note we have broken our code for the 'change buttons' and we will need to revisit this later

and make suitable changes to make it work once more.

First lets look at some more LINQ syntax on our Object in RAM.

===================================================

We can use a 'where' clause to filter on a variety of conditions.

Here is the result of this filtering :-

===============================================================

Or we can add a further line (or clause) to our query so that we can arrange the results into a set order.

Check out the next image - seen below :-

=================================================

And the results are as follows :-

===========================================================

Notice that the names are in order Z through A (z to a).

And we can further complicate our ordering clause as seen in the next image - check this :-

==========================================================================

Notice line 39 above, it is what we used to call a 'multi-key sort'.

And we can see that the results clearly reflect this - as seen below :-

=======================================================

Notice that the international guest (not local) are in order 'W - D' and the remaining local guys

in order 'T - A'.

Combining filter conditions :

We can obviously apply a number of filter conditions, not just one, but we do have an option or

two as to how to apply them.

First we will do something which is probably more intuitive for us coder folks - check this out :-

=========================================================================

And here are the results after running the new code :-

===============================================================

However, we can do something which is most surprising to us SQL guys, for us who have spent

long periods in Management Studio here is a nice surprise - study and think on this :-

================================================

And to prove it works study the following runtime display details :-

================================================================

Well, the above is in order by 'Date of Birth' ascending - oldest guy first.

And the filtering is the same as it was when we used the '&&' syntax.

Lets keep our filter clauses similar (although I have changed the value(s) ) and now try

a different reordering of the code sections - check this out :-

=================================================

Yes, T-SQL guys will be horrified, or at least flummoxed !?

It is bad enough having the select clause at the end, but also the equivalent of the 'order by' clause

at almost the beginning :((

This is more evidence that the compiler takes our code and then from it makes a sensible query 'statement'.

We will see more of the 'statement' when we come to 'LINQ to SQL', but for now lets see the results of our

'strange' code order - here we have it, see below :-

================================================================

Yep ! DoB descending all right, and only guys between 45 and 65, and that is NOT a -T-SQL 'between'.

For non-SQL folks the T-SQL 'between' includes the limit values.

Lets move on ...................

Thinking ahead :

Obviously, when we are using 'LINQ to Objects', the compiler does not have to generate a SELECT statement,

which it then sends to the SQL Server engine for processing.

So if we ask to turn our above 'query' into a string we get "not much" of any use to us, really.

Here is what we get at the moment :-

================================================================

And the code that generates the above string is seen below :-

=============================================================

To answer a question that you may have in mind, "No, you can't have the 'select' clause anywhere

but at the end. There has to be a closing semi colon after the 'select' clause."

You will get used to the LINQ syntax by using it, as indeed I did. I now like it a LOT and can get

good results with it.

To help you get acquainted, just read through the rest of these eNotes on LINQ.

Good Luck ............

PHH - 29th. August 2013.


Civil Engineering Data Logging App

Civil Engineering Data Logging App

Civil Engineering Data Logging App

 Previous topic Next topic

About two years ago I had the opportunity to start developing an application for logging data from

a civil engineering site in South Wales (UK).

The huge amount of data started to trickle in every 15 minutes starting 18 months ago in Spring of 2012.

The 120 sensors monitored mainly temperatures of the soil, but a few did general weather stuff for rain and

wind conditions, and air temperatures as well.

===============================================================================

====================================================================

=====================================================================

The data as retrieved over a digital phone link, came from the multiplexor and data logging system in a CSV

format. Not ideal - BUT - that is what we had :((

==============================================================================================

The first 'prototype' application was written in Vulcan 2 and used my two Static Classes for the data access

layer, based firmly on ADO.NET.

Because of complex local situations, and working with the University at a distance, I had little choice but to

move the final version over to C# and .NET 4.5 - using the new SQL Server 2012 version of MSSS.

=======================================================================================

It just so happened that I was looking into LINQ at that time, and so to keep guys like Nick Friend happy, I

decided to re-write the app in C# using LINQ and no ADO.NET whatsoever.

Nick had been complaining that all my eNotes were based on non-real life solutions, demo apps etc.. So I

decoded to prove him wrong and went for the " real deal".

================================================================================

So before I came to Metro/WinRT and even Phone 8, my LINQ skills had been tried and tested in WPF with

.NET 4.5.

Because we had had a 'prototype' in VN we already had a SQL database and Tables created. So we did not

use 'LINQ to SQL' in a Code First way, but a 'Data First' manner.

This meant that I made my .NET classes to fit the Tables I already had in the SQL DB.

Some classes were very long but a compressed (part collapsed) view of the class code lines still makes

sense to a viewer, so here is one for dumping into the SQL DB the almost raw data before the app processed

it to create separate readings, and store those in a different table.

Check out the following :-

==================================================================

You should recognise the similarity with what we have seen previously.

The class for the single reading looks like the following :-

========================================================================

The next image will make more sense when you have read a few more sections just after this one.

What you are looking for is how we have one query calling on a previous one, using the first query

as a collection and bases for a further query.

Also there are a few joins, and multiple 'where's, and grouping and aggregating. All done in standard

LINQ syntax and NOT Lambda expressions.

Lambda expressions are used, but only for the aggregate functionality - Min, Max, Sum and Average -

line 5617 - Check out the following VERY thoroughly :-

====================================================================================================================

Also note that I chose to return an Array of Objects. These days I would define and make a class for the task.

Still, I have learned a lot since those days - when I code this lot ;-0)

And now for a real need for FIVE joins and the use of one query by another.

Check out the following VERY thoroughly :-

=================================================================================================================

It may interest you to know that when we use 'LINQ to SQL' - either Code First or Data First - when we choose

to use 'ToString' on our query, we get a string of the SELECT statement which will be sent to the SQL Server.

Obviously, this is not so when we use LINQ to Objects !

Here is an example :-

=====================================================================================

If we choose to use 'ToString' on query2, which uses a query one, then we get a complex 'compound'

query which the system generates for sending to the Server.

Above we see such a compound query, even though it is less complex that that which we get for the

FIVE join example above it.

Here is how an early prototype app display looked :-

================================================================================================

Time for some processed results - check this out :-

================================================================================================

And the same results set in a different format :-

====================================================================================

After these early results there was a huge amount of Fortran number crunching to produce other

sorts of data output and comparisons - all model based stuff ! Out of my depth ;-0)

Summary of where we are at :

Okay folks, you may be thinking that all this seems complicated - BUT - I can assure you that this is

far better than what I had to deal with when we were using ADO.NET with Vulcan 2.

It was not the VN2 that was the issue but the ADO.NET code - voluminous and easy to make a mistake

within its complex 'body'.

Give me 'LINQ to SQL' any day of the week.

Actually, once you have working examples of LINQ to cover much of what you require, it is easy to copy

and adapt it to your specific needs.

My problem was that I could not fine eBooks and web articles that were up to date enough, and also

which coped with more than trivial, or 'Mickey Mouse' type examples.

Also It was by chance that I found the multiple 'chained' query approach - then that made life a lot easier.

Time to move on - see you in the next subsection .....................

PHH - 30th. August 2013.


What to select in the 'select' clause

What to select in the 'select' clause

What to select in the 'select' clause

 Previous topic Next topic

Okay guys, this can be both easy and complex - almost at the same time ;-)

It all depends on how we go about it.

Let us start with a very easy example, one we used earlier in our notes. Check this out :-

=============================================

By using ' i ' in line 40 we are saying to the compiler that we want all of the properties of the

collection item class included in our return collection.

Here is what this code produces :-

======================================================

Now then, we can take take advantage of some supporting new technology to LINQ, the inclusion

in C# of the anonymous type - yep, an unknown 'Type'.

Check this out :-

====================================================

When we proceed to use this 'query' as our return collection (keeping the rest of the code the same)

we end up with a restricted output as seen in the following image :-

===================================

Because we have only two property values per collection item, we only get those being bound in the XAML.

Remember, if a XAML attribute is bound to something which at runtime does not exist, we get no runtime

error, it is just ignored.

We can change the 'select' clause to use another anonymous type, but include all of the properties.

Check out the next image shown below :-

=======================================================================

Take my word for it that the displayed details return to what they were previously.

Note the order does not matter, as the display is determined by the XAML script and the availability

of property values.

Lets move on .........

An alternative - Using a Defined Class :

If we happen to have a suitable class defined we can use it as the item Type.

Here is something to ponder deeply upon :-

==============================================================

Yes, this also gives the same results as using 'select i; ' , simply because it is the same class as the

default used by the code.

However, there are times when we get complex joins and grouping, when we need to define a class

just to hold the return properties in a collection that e can then pass back, out of the method in focus.

Anonymous types are fine, and handy at times, but they have limitations when we wish to do anything

fancy it seems.

Here is another example, from a recent Pearls posting :-

We are wanting the aggregate information from a traditionally grouped data set - traditional as in the

SQL world (not CollectionSourceView).

Because we wish to have as much flexibility as possible for where we use the returned collection, I have

defined the class called 'WordCount'. Check below :-

==========================================================

Remember that it is always a good idea to have an empty constructor, the system needs these at times.

Lets move on and see some other examples from my other eNotes ...............

Studying some other Variations with Selecting :

What if we do not specify one of the properties of our chosen type ? See below :-

===============================================

Well see for yourself the display results :-

And now can you work out for yourself what code produces the next runtime display :-

Yep! a bit silly, but it does compile and run :-

============================================================

Moving on a pace .........................

More Complex Examples :

This next example is interesting as it show us we can include in the return set anonymous type

properties from a number of different source collections.

Study the following carefully :-

The four collections used above are Customers, Orders, OrderItems and Products.

This means that we have an anonymous output type which has four properties, and these are compound

in nature - four 'class' properties, of Type C,O, OI and P.

By compound we mean that there is a difference wit the above and the following, where each property value

is included in a 'flat' anonymous type - check this out below :-

When we specify an anonymous type in our LINQ query we can actually set the name of the property

as well as specifying its value - here is an alternative syntax - check out thoroughly :-

=================================================================================

It is obvious which are the property name ... 'CustId', 'OrdId', etc.

Here is another working example :-

===============================================================================

The comment on line 106 simply means that the filter condition was also placed in the LINQ

'query' code.

And finally for this sub-section, an example showing a Left Outer Join (LOJ). And please remember that

joins and inner / outer joins are to do with data and declarative style rather than SQL.

There are certain business problems (tasks) which can only be solved easily with LOJ. The example shown

is when we wish to find out products which are not selling. Check this out :-

There are other common scenarios like finding Customers who did not order. For this we need to LOJ Customer and

Order collections.

Enough for now, it takes time to try this stuff and get a feel for it.

Good Luck .............................

PHH - 30th. August 2013.


Filtering with 'LIKE' equivalents

Filtering with 'LIKE' equivalents

Filtering with 'LIKE' equivalents

 Previous topic Next topic

Guys who are familiar with SQL and using T-SQL script for composing query statements, to send

directly to the Server for evaluation and processing, may at first mourn the loss,or absence of the

popular 'LIKE' operator.

Before we get into real details we ought to look at what the SDK docs have to say from Help Viewer 2.0

so check these out guys :-

============================================================================================================

And we also have some further details in the SDK about the pattern, and matching - see below :-

===========================================================================================================

By now you are probably thinking like me, and this all seems VERY similar to Regular Expressions - if it isn't

RegEx itself under the hood - BUT - at our coding 'surface' the use of the '%' is quite different, so be aware !

Here is more useful 'blurb' from the SDK docs - give it a read :-

=============================================================================================================

So how about looking at a simple 'LIKE' example from the ClickStart eNotes on T-SQL - check below :-

=====================================================================================

As we see above, the LIKE can take the % symbol, but 'RegEx's don't use this at all.

Let us explore a few possibilities of how we can use RegExs in .NET with a suitable STATIC member in our C#

class library and a RegEx object passed as a parameter from a Vulcan 3 main code module.

Here is a result of a simple pattern on which our RegEx object is based - check this out :-

================================================================================================

So the above returned data set - or collection - is for only objects where the 'FirstName' property starts

with a 'B' - note the capital - upper case.

And if we go a little more complex, or ambitious, then we see the following example working just fine :-

=================================================================================================================

And if we are to look into the class library I am using to compile and run the test app we are developing,

we see the following .NET code in C# and using LINQ - check this thoroughly :-

=================================================================================

Notice that we have to apply the filter condition after we have had returned the queried collection.

So above we are getting back the full customer set and then applying the filter condition.

This works OK as it is shown, but for large data sets this approach would need adapting.

We can now make an experiment to see what happens when we try to include the the RegEx condition

within the query itself - check this out :-

=============================================================================================================================

And don't think you can be clever and beat the system - by placing the filtering condition in a

second query - see below for what I tried out :-

=================================================================================

The code actually does produce the right results at the data grid control, however, it does not

apply the filter until the collection is returned back into memory.

The above image shows that the printed query is a LINQ to Objects query, and not a L2S.

If we change the code slightly and print out the 'query' on its own, you see below that we get a

standard type SELECT statement - check this out :-

==================================================================================

So this proves that the whole collection of customers must have been returned before our filter

condition using RegEx was applied - otherwise the printout of 'query2' would be a 'super' version

of this query - with other bits added.

Before we move on to something new, lets just see what a slightly amended version of the above

RegEx pattern does to our results. We will replace "J[a-z]{3}" with "J[A-Z]{3}" to see the effect of

upper / lower case in our pattern matching - here is the result :-

=============================================================================================

Yes, the regular expression 'stuff' is case sensitive and so we must use it with care, and understanding.

Time to move on a pace ............

.NET 'Contains', 'StartsWith' & 'EndsWith' :

There are some useful .NET string methods which can be applied as filter conditions, and which will reduce

the size of the returned data set / collection.

We will look at three in particular, the first of these is 'StartsWith' and can be seen in action below :-

========================================================================================================

The result of this is as shown :-

===================================================================================

And in a similar fashion we can try out the second of these 'EndsWith' as seen below :-

================================================================================================================

The "ie" condition means that 'Mike' does not get through the filter.

Now finally for these three useful methods, we will examine the 'Contains' member, the one that allows

us to stipulate what is somewhere within the text string - and that includes start and end as well.

Check out this test filter condition, in which we also apply a negation to our condition - study this carefully :-

==============================================================================================================

So we get returned only objects with a property of 'FirstName' NOT containing and 'e' or an 'a'.

And the beauty of this is that when we try to print out the query string, we see that behind the scene the

system has made a SQL statement which incorporates LIKE ;-0))

Check this out fully :-

==============================================================================================

Yes, the above was a good trial, from which we can learn a lot.

Now we need to move on, and learn some other 'stuff' ..................

PHH - 9th. September 2013.

Addendum :

We can see if in fact we can get LINQ to Objects 'L2O' to accept directly a RegEx filter condition.

Study the following details carefully :-

First the call from the Vulcan side of the app / class library :-

==========================================================================================================

And now the edited code within the C# library static member :-

==================================================================================================================================

Well, as you can see, we can get this to work when we use L2O technology, it is worth us remembering that.

See you in the next section ................

PHH - 10th. September 2013.


Lambda expression - do we need them? what are they?

Lambda expression - do we need them? what are they?

 Previous topic Next topic

Lambda expression - do we need them? what are they?

 Previous topic Next topic

An extremely important part of the underlying technology of LINQ is the LAMBDA expression.

It would appear to me that LINQ uses a lot of Lambda expressions behind the scenes !

Without Lambdas we can't have LINQ, I think that is the simple case of the matter.

However, at the same time, Microsoft wish developers to NOT use the Lambda syntax whenever possible.

I have read this in their SDK docs more than once.

There may be a few times where we simply have to use it BUT at the moment I can't recall any.

Microsoft is trying to make all of its .NET languages far more declarative, and are moving away from procedural

code and code that does not read in a way closer to the business problem being solved.

Some guys (unfortunately) just don't see the 'declarative' approach :((

Let us start with a simple example of Lambda expressions - check this out :-

Basically, after lines 33-36, we end up with a collection in order of Surname values A-Z.

This collection is then set as the source of a CVS (CollectionViewSOurce).

The Lambda expressions above are "c => c.Surname" and "c => c".

Here is another query, with a more complex Lambda expression, which also has an extension method applied (at the end)

to find only single occurrences.

[ .. care - the single occurrence is for the whole record, all fields compared .. ]

See line 224 below, in particular :-

=========================================

However, not getting our Lambdas mixed up with our Extension Methods (EMs), let us see

another way of using the 'Distinct' EM - check this :-

In the above example it is line 248 which uses the 'Distinct' EM to good effect.

Many Extension Methods (EMs) take a Lambda expression - BUT - not all EMs take a Lambda expression.

Here is a clear example of the same sort of thing (see two images above) - BUT - where we apply the EM at the query

finding stage - line 244 shows the EM being applied.

We need to look into what is Distinct - for a bunch of properties (values) the whole item needs

to be the same to be excluded.

You can do your own testing and checking on that one ;-0)

Here is some useful information on Lambda Expressions from the SQK docs of HV2 :-

========================================================================================================================

Not exactly 'easy' reading - BUT - the mention of LINQ is clear.

Remember, Lambda expression are important, and are probably used under the hood by M$ quite extensively,

however, we need to use them only when we have not LINQ alternative.

To make your LINQ standard syntax coding as clean and as clear as possible, use Lambdas sparingly !

Time to move on ....................

PHH - 30th. August 2013.


Extension Methods

Extension Methods

Extension Methods

 Previous topic Next topic

We need to know about these, what they are, where they came from, and just how often we will

use them, sometimes without realising it ;-)

Let us start with the SDK docs in Help Viewer 2.0 :-

=========================================================================

So I would say that EMs allow Microsoft a lot of leeway when maintaining and updating their frameworks.

Here is some more useful blurb on EMs :-

============================================================================================================================

As I said, we will often use EMs without realising it - but they are easy to use ;-)

Now check out this, as it concerns us LINQ guys :-

======================================================================================================================

Yes, we will see plenty of these as we do our coding !

Below is an example from our IntelliSense :-

=========================================

Now study this :-

=======================================================================================================================

Yep! so Lambdas and EMS often go together - just as we thought previously.

Read on :-

=====================================================================================================================

Here are the directives I have at the head of my Phone 8 code file :-

==============================================

And if you are a "deep dude" this next bit of information may interest you :-

===========================================================================================================================

Moving on ....................

Let us now use the IntelliSense to find out the Extension Methods (EMs) we can have on our LINQ query object.

Study these images shown below, and look for something familiar :-

[ .. these are for my Phone 8 app and WPF has more available .. ]

==============================================================================================

===========================================================================================

Of all of these shown above, 'ToList' is the one I use regularly, and Distinct' now and again.

However, most others I don't need to use since I use the standard LINQ syntax for the vast majority

of the time that I do LINQ.

We may have to use Union, Intersect, and Except however, when it comes to doing 'Set Algebra'.

Also be well ware that the EMs on offer differ depending on the type of collection the technology

you are using provides. So L2S on Phone will be a different list to LINQ to Entity on WPF.

Enjoy using your EMs .....................

See you in the next section.

PHH - 30th. August 2013.


Set Algebra - Operators & their Use

Set Algebra - Operators & their Use

Set Algebra - Operators & their Use

 Previous topic Next topic

Okay guys, this is a more important section than you make realise at first.

Often guys coming new to SQL underestimate the true value of set based arithmetic, or set base algebra.

This therefore will be true for guys coming new to LINQ if they have not had some extensive experience with

SQL before hand.

Although the examples I use below to show the code and script use of Set Algebra, are rather simple or 'tame',

in fact we can solve some interesting business problems by apply the 'set' approach. More on this later.

When using set algebra we need to realise that we need to get two results sets before we can use the operator.

This as true for standard SQL as it is for LINQ.

The set operators we will study are Union, Intersect and Except.

First the UNION operator : [ .. UnionAll is done by 'Concat' see at end of here .. ]

To start with, lets see how it works for us with SQL Server, check this SQL query in Management Studio :-

===========================================================================

Note that for set operators the structure of the records in the sets MUST be similar - numbers of fields (columns)

as well as their order and data type.

The above was the way I did it before LINQ, now we can see just what is required in code - check below :-

==========================================================================================================

And the results look a bit like this shown below :-

===========================================

And now to prove that if we don't compare like with like we get problems and errors - even

in SQL we see a problem trying to compare an integer with a string because we have the columns reversed :-

========================================================================================================

Believe it or not the this 'similarity' constraint is NOT a hindrance to using the set operators to solve really

useful and difficult problems.

Now the INTERSECT operator :

Once again we need two sets or collections before we can 'act' - check this :-

========================================================================================================

And if we get our code to examine what LINQ actually has created by way of a SELECT statement to send

to the server we see this below, with no INTERSECT within it :-

For the above example the very clever LINQ system knows it can make a better (more efficient) query

statement based on sub-queries, but this is not always the case as we can see below :-

==============================================================================================

And, we need to remember while doing this that Set Operators work with collection in memory too.

We do not need to have a SQL back-end data source, we can use these with LINQ to Objects too.

Now the EXCEPT operator :

By now you are getting the idea of how to use and apply set operators, so just a look at the VERY useful

one called 'EXCEPT' is probably enough for these eNotes - check this :-

====================================================================

So in the above, customer with ID of 3 was the only guy to NOT order in both time periods, before

and after Sept. 1st. 2006.

In fact customer '3' ordered in the first time period as set 'A' has set 'B' removed from it leaving a result.

The other way around would leave us with nothing - and empty set or collection.

Out of interest I have been paid to solve some quite complex problems in a business environment, and used

EXCEPT in a multiple way to get really good results - I think I applied it about 13 times in all, on the one query.

The 'Concat' operator - as 'UNIONALL' in T-SQL :

In T-SQL we can use 'UnionAll' to join two similar sets of records.

When we use extension methods we use a new one to me, called 'Concat'.

I will leave it to you to try our this simple enough to use operator ;-)

Moving on ....................

What types of Problem can be best solved with Sets ? :

For guys new to Set Operators we may need to try and specify a few examples of how we can use this technology

to solve a particular type of problem, ones which are not intuitive when dealing with tables, rows and columns

and coding FOR loops etc..

A little while back I found some extremely use information for a local company in Cardiff. They make and sell

medical appliances to the NHS patients, on a National basis - all UK, and a few international ones too.

They had plenty of data from previous years of supplying patients, and needed to answer a basic few questions

on patient consumption of products for the NHS guys (them in control).

After some thought, and studying their data, I decided to get the results by writing many queries to return data

sets (collections) which in fact excluded those patients returned from the active list of original patients.

I considered ALL patients active, or in my 'answer' until I excluded them for one reason or another.

The main way we excluded patients was by the products they used and by how many and frequently they ordered.

We wished to exclude those who were infrequent users, those with multiple 'conditions' and hence who order

combinations of products, as well as those who had only started to use a type of product.

Basically, we needed regular users of a single type/range of product, not recently new patients, then we needed

to look at how the amounts varied across the group.

Yes, I know, at first I was quite alarmed with what they wanted, because our data was NOT structured in a way

I thought very suitable to answer this question.

Well, the upshot was that Set Operators came to my rescue.

It was easy to design and write queries to return smaller groups of patients which were to be excluded, and take these

one by one away from the total patient group, that it was to even think of doing it another way ;-)

The queries themselves were quite different, and as long as I returned a simple customer ID list, could happily

use the EXCEPT operator to successively remove patients groups.

Obviously I started with a 'Distinct' set of all patient ID. Removed all those marked as inactive in the database, and then

went on to apply specific filtering select statements for all of the other logical conditions above.

Once I had a reduced set of Patient Ids I could then go on to find their product use and make grouped aggregate details,

by doing some nifty JOINs of patient group with order tables, and specific ordered product Ids.

I can't show you the details but you will get some idea of how useful this approach was to us.

I think I even made a UDF - user defined function - so that we could do all of the above, but just vary the start and end

dates as input parameters. Oh! and now I recall, also the frequency and level of product ordering / use.

Personally, I was delighted with the outcome, and made sure the client manager knew what a smart piece of coding

he was enjoying when reading the results.

Time to move on, Good Luck with your Set Operators ;-0))

PHH - 4th. September 2013.


Vulcan 3 - use with C# data access layer

Vulcan 3 - use with C# data access layer

Vulcan 3 - use with C# data access layer

 Previous topic Next topic

For guys who want to work with Vulcan (and VN3 is just out) then we have to realise that LINQ is

very much part of the compiler, and it uses some other technologies which are also part of the

compiler.

So I have been using C# to do all my explorations and experimentation.

However, all is not lost, as we can write an assembly in C# which acts as the data access layer,

and then use this and its classes, and their members, directly from our VN3 code.

Remember, VN3 is a very well behaved .NET citizen, so let it work with C# for you ;-0)

In fact, if we have a C# (or VB) data access layer assembly, we can not only have members in the

classes which read and write data to the back-end database, but also members which filter and

re-order collections. However, there may be a suitable alternative using 'CollectionViewSource'.

Do NOT use 'CollectionView' in your code - WARNING from Microsoft.

=====================================================================================================

As you can see in the above image we need to have a reference at the head of our code file as shown in

the next image :-

==================================================================================================

It is as well to read the next SDK docs section if you are wishing to use VN3 and LINQ together.

Check this out in detail :-

==========================================================================================================================

*** WARNING *** The 'LongListSelector' in Phone 8 takes a different class of collection for binding purposes.

Views can be used with 'ListBox' but not with LLS. We need to build a new list from the 'View' items.

Lines 52-57 below show this in action.

Let us now see CVS in action .....................

Note that for Vulcan users, where the code below shows 'query' being used as the initial collection,

this will actually come back from the Data Layer - where C# and LINQ is used to retrieve the data.

Sorting with 'CollectionViewSource' (CVS) :

First some success, the order is False the True and within these Z-A on 'Name' :-

==============================================================

The .NET code which generates the above order is seen below - check it thoroughly :-

===================================================================================================

Notice that the SortDescription is a multi-key sort, with each condition applied separately.

The first condition applied is taken as the 'course' sort, then others in progressively 'finer' sorting.

So how do we do filtering wit CVS ? .................

Filtering with 'CollectionViewSource' :

We have to set an event handler for the Filter event. The code to set the event handler association as

well as the handler method itself, are shown in detail in the following image :-

==================================================================================

Here are the results of this filtering code when applied to our example :-

==========================================================

As you can see, only folks between 50 & 70 (inclusive) - just as our code required.

Lets move on .............. grouping is not quite what SQL guys may think it is ............

Grouping with 'CollectionViewSource' :

In the following .NET code we will group our data items by the property 'isLocal'.

Lines of code numbered 55 - 57 seem to do as we require :-

===========================================================================================

And the runtime display is seen in the next image :-

=========================================================

Okay then, we have seen enough of how the CVS class may help Vulcan users process and present their

collections, on the VN3 side of the Data Access layer - which will be written in C# for the LINQ capability

of the compiler.

See you in the next sub-section ..................

PHH - 29th. August 2013.


Moving to a separated data layer C#

Moving to a separated data layer C#

Moving to a separated data layer C#

 Previous topic Next topic

If we are to be able to use LINQ in some way with our VN3 applications, then we need to separate

out the LINQ and "LINQ to SQL" (L2S) stuff from the business logic.

We need to construct a Data Access Layer (DAC) and place it into a C# class library.

Once we have a DLL to handle the data access for us, we can the reference it from our VN3 apps.

It will be best, or at least most instructive, if we build up to this, by making separated version of our

app in C#, and then moving on one step at a time.

Lets start by making a new solution / project in VS 2012.

Starting a New App - WPF style :

Open VS 2012 and close any open project and files.

From the menu bar select File, New, Project ... as seen below :-

=======================================================================================

When the dialog screen appears, fill it out and select options as shown below :-

=============================================================================================================

Make sure you check the 'source control' if you have TFS (Team Foundation Server) available

to you on your development platform - here is what you will get if you do :-

==========================================================

Select and make the correct folders as seen above, or similar, and click OK.

You will now see an 'un-checked-in' version of the new app in the SE pane.

Here is what I have - check this out below :-

==================================================

The small icons show that we have yet to check-in the project for the first time.

Right click the project node (or item) within the SE pane. This brings up the following

context menu so you can select to 'Check-In' :-

=========================================

When the dialog screen shows, fill out a comment and click the 'Check In' button :-

================================================

The icons now are a different shape / symbol, as seen below :-

=================================================

So the source control has started. 'DALfullCS' stands for Data Access Layer full C# version.

Now let us add a new project - right click the solution node in the SE pane and choose to add a new

project which brings up the following dialog screen :-

===============================================================================================

Select as shown the C# Windows, Class Library template, and provide a suitable name as shown above :-

IF all goes well then you should see the following details :-

=====================================

Right click the 'Class1' node and rename it - here is what we have before renaming :-

========================================

Rename it 'Customer' - see the next image :-

=====================================

Then make your new code file look like this below :-

==================================================

Time to move on .........................

Starting our Library Classes :

Now that we have a class library project, even though it is empty, we can reference this

in our main project.

Expand the References node in the E pane and see the following :-

=========================================

Notice that the first entry alphabetically by A- Z is 'M'.

Now right click the References node and bring up the References manager screen.

Check these out - first this :-

==================================================================

And now this - select and check the library item, then press OK :-

================================================================================================

You will now see a new entry in the References list, right at the very top - check this :-

============================================

Now collapse the node and compile and run the app to see all is well,

Here is what I have on my PC system :-

====================================================

You may have to make sure that the start-up project is set to 'DALfullCS'.

If this is not showing in bold type, and 'DALclassLibrary' is, then right click the relevant node

and change it accordingly.

Lets move on a pace ...............

Planning and Designing our Class Library :

Before we rush ahead and start adding code into our library project, we need to think carefully about

where we are headed and what we are trying to do.

Let us start simply, and say we need to have a class entry in our library which is required for use with

accessing data within the SQL database.

We are to use L2S (LINQ to SQL) and the Code First approach to create both a DB and also its Tables.

So any class related to the Table making and access, will need to be in our library,

We will also need members (static methods) for populating our table(s) and also for retrieving data, either

the whole table, or by restricting the returned set in some way - by using a filter condition.

We will need a static member to insert new and update existing table records - from object collections.

As well as the custom class oriented members, we need one or tow for the DB as a whole. For creation

and Back-up for example.

Finally, on the planning stage, we need to make our classes with full built-in response to properties

changing, so INotifyPropertyChanged needs to be taken good care of ;-)

There will be other things which 'fall out' as we move along, but for now we have enough to allow us to start.

Moving along our App design :

Before we go to child sections from this one, and look at single classes in full detail, we need to see what we

can add into our SE pane to be ready and prepared for the code which is to follow.

Here are some code file additions made to our Class Library - check these out :-

================================================

Although all but the Customer file is just an empty stub at the moment, I have copied in a whole

bunch of directives, and the using statement section at the head of the class files looks similar

to this one from that for 'Logistics'.

========================================================================================

I strongly suggest at this point you visit the child sub-section from here entitled 'Library Classes - 'Customer'

to see all the details we need to include to make the class 100% compatible with LINQ to SQL (L2S) as

well as making it responsive to property changes - so that data binding will work correctly when we come

to that part of the app.

See you in 'Customer' ...........................

Checkout the making of the DAL and the fleshing out of the C# class library.

PHH - 4th. September 2013.


Library Classes - 'Customer'

Library Classes - 'Customer'

Library Classes - 'Customer'

 Previous topic Next topic

Since this is our first class to be created for this Class Library, we need to make sure we do everything

required to make it fully functional and responsive to both L2S and data binding with WPF and XAML

technologies.

In the image shown below I have collapsed the Properties section so that only one is displayed in detail,

the others are similar - since we need to get an overall 'shape' of what the class looks like.

Check this out - private fields, and public properties :-

========================================================================================================

In the code above you will see that we have included the code lines to handle the notification of when

properties change. Previously, in some earlier sections of these eNotes we have excluded them for

clarity - so that guys could focus on other aspects of the L2S.

Because this will be a fully working class library, to support a real live and working Vulcan app., we need

to include the notification code.

Here, in the following image, are all the various properties, quite a useful variety of basic data types :-

=====================================================================================

The above code will be copied in a very similar manner to other different classes for this demo app.

Before we move on we need to make a few observations of what we have above.

Normally, for most SQL databases we would allow the server to generate unique IDs, but because

we are going to manually generate our own coded data we need to have a knowledge of which IDs

are what etc. - so this will also be done for Order, and other classes like Contact and Supplier.

In a demo and learning environment we have to make a few simple compromises - we can't be adding

data live, in an interactive way :((

Any property marked with a 'Column' attribute will end up in our Table when the DB is created - Code First!

Moving on ........................

Creating Static Methods for Data Population and Retrieval :

Okay then folks, what we now need to do is make a STATIC method to supply a collection of Customer

objects. We have seen similar static members used previously, so there is no big deal.

The following code provides us with a STATIC member which is typically used to populate the Table called

'Customers' just after it is created at the time the DB (database) is created - check this out :-

==============================================================================================================

You will see similar Static methods for each of the Tables within the DB, in this exploratory sample app.

In reality, the data is all likely to be provided by interactive screen input.

However, this approach is useful to us developers as when developing apps for the Phone 8 we are using

a virtual machine which is created at the start of a session, and destroyed at its end, so all data is NOT

persistent - when we come back next time / session, the data is clean - Tables are empty, unless we

pre-populate them.

Lets move on ........

See you in the next section.

PHH - 5th. September 2013.


working code

working code

working code

Previous topic Next topic

=================================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//----- added for LINQ -----
using System.Data.SqlClient;
using System.Data.Linq.Mapping; //----- needed for Table & Column .....
using System.Data.Linq;
using System.Data.Sql;
//==================================
using System.Collections;
using System.Collections.ObjectModel; //----- ObservableCollection .....
using System.ComponentModel; //----- INotifyPropertyChanged .....

namespace DALclassLibrary
{
[Table(Name = "Customers")]
public class Customer
{
//----- fields -----
int _customerId;
string _salutation;
string _firstName;
string _lastName;
Nullable<DateTime> _firstOrder;
Boolean _isLocal;
Double _creditLimit;

//----- events -----
public event PropertyChangedEventHandler PropertyChanged;

//----- properties -----
[Column(CanBeNull = true)]
public string Salutation
{
get { return _salutation; }
set { _salutation = value; NotifyPropertyChanged("Salutation"); }
}
[Column(IsPrimaryKey = true, CanBeNull = false)] //----- IsDbGenerated = true,
public int CustomerId
{
get { return _customerId; }
set { _customerId = value; NotifyPropertyChanged("CustomerId"); }
}
[Column(CanBeNull = false)]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; NotifyPropertyChanged("FirstName"); }
}
[Column(CanBeNull = false)]
public string LastName
{
get { return _lastName; }
set { _lastName = value; NotifyPropertyChanged("LastName"); }
}
[Column(CanBeNull = true)]
public Nullable<DateTime> FirstOrder
{
get { return _firstOrder; }
set { _firstOrder = value; NotifyPropertyChanged("FirstOrder"); }
}
[Column(CanBeNull = true)]
public Boolean IsLocal
{
get { return _isLocal; }
set { _isLocal = value; NotifyPropertyChanged("IsLocal"); }
}
[Column(CanBeNull = false)]
public Double CreditLimit
{
get { return _creditLimit; }
set { _creditLimit = value; NotifyPropertyChanged("CreditLimit"); }
}
//----- constructors -----
public Customer() { }

public Customer(int nI, string cS, string cF, string cL,
Nullable<DateTime> dtFO, Boolean lL, Double nCL)
{
this.CustomerId = nI;
this.Salutation = cS;
this.FirstName = cF;
this.LastName = cL;
this.FirstOrder = dtFO;
this.IsLocal = lL;
this.CreditLimit = nCL;
}

//----- methods -----
public void NotifyPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//---------------------------------------------------------------------------
//----- static methods -----
public static List<Customer> GetaBunchOfCustomers()
{
List<Customer> aList = new List<Customer>();
aList.Add(new Customer(1,"Sir","James","Bolam", new DateTime(2004,01,17), true, 0));
aList.Add(new Customer(2,"Miss","Mary","Malone", new DateTime(2006,03,11), false, 125.0));
aList.Add(new Customer(3,"Mr","John","Parker", new DateTime(2005,05,23), true, 250.0));
aList.Add(new Customer(4,"Mrs","Bev","Frances", new DateTime(2008,09,07), true, 180.13));
aList.Add(new Customer(5,"Prof","Nick","Friend", new DateTime(2007,11,02), true, 90));
aList.Add(new Customer(6,"Mr","Paul","Piko", null, false, 0));
aList.Add(new Customer(7,"Dr","Dan","Logan", null, false, 350.0));
aList.Add(new Customer(8,"Ms","Laura","Hepburn", new DateTime(2013,4,24), true, 50.13));
aList.Add(new Customer(9,"Dr","Mike","Stein", null, false, 150.0));
aList.Add(new Customer(10,"Mr","Ben","Hepburn", new DateTime(2012,01,14), true, 0.13));
aList.Add(new Customer(11,"Dr","Paul","Ryan", new DateTime(2013,09,04), true, 190));
aList.Add(new Customer(12,"Mr","Willie","Moore", new DateTime(2011,06,06), false, 450.0));
return aList;
}
//--------------------------------------------------------------------------------------------
}
}
=================================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//----- added for LINQ -----
using System.Data.SqlClient;
using System.Data.Linq.Mapping; //----- needed for Table & Column .....
using System.Data.Linq;
using System.Data.Sql;
//==================================
using System.Collections;
using System.Collections.ObjectModel; //----- ObservableCollection .....
using System.ComponentModel; //----- INotifyPropertyChanged .....
using System.Text.RegularExpressions;

namespace DALclassLibrary
{
[Table(Name = "Customers")]
public class Customer
{
//----- fields -----
int _customerId;
string _salutation;
string _firstName;
string _lastName;
Nullable<DateTime> _firstOrder;
Boolean _isLocal;
Double _creditLimit;
int _contactId;

//----- events -----
public event PropertyChangedEventHandler PropertyChanged;

//----- properties -----
[Column(CanBeNull = true)]
public string Salutation
{
get { return _salutation; }
set { _salutation = value; NotifyPropertyChanged("Salutation"); }
}
[Column(IsPrimaryKey = true, CanBeNull = false)] //----- IsDbGenerated = true,
public int CustomerId
{
get { return _customerId; }
set { _customerId = value; NotifyPropertyChanged("CustomerId"); }
}

[Column(CanBeNull = false)]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; NotifyPropertyChanged("FirstName"); }
}

[Column(CanBeNull = false)]
public string LastName
{
get { return _lastName; }
set { _lastName = value; NotifyPropertyChanged("LastName"); }
}
[Column(CanBeNull = true)]
public Nullable<DateTime> FirstOrder
{
get { return _firstOrder; }
set { _firstOrder = value; NotifyPropertyChanged("FirstOrder"); }
}

[Column(CanBeNull = true)]
public Boolean IsLocal
{
get { return _isLocal; }
set { _isLocal = value; NotifyPropertyChanged("IsLocal"); }
}
[Column(CanBeNull = false)]
public Double CreditLimit
{
get { return _creditLimit; }
set { _creditLimit = value; NotifyPropertyChanged("CreditLimit"); }
}
[Column(CanBeNull = false)]
public int ContactId
{
get { return _contactId; }
set { _contactId = value; NotifyPropertyChanged("ContactId"); }
}
//----- constructors -----
public Customer() { }

public Customer(int nI, string cS, string cF, string cL,
Nullable<DateTime> dtFO, Boolean lL, Double nCL)
{
this.CustomerId = nI;
this.Salutation = cS;
this.FirstName = cF;
this.LastName = cL;
this.FirstOrder = dtFO;
this.IsLocal = lL;
this.CreditLimit = nCL;
}

//----- methods -----
public void NotifyPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//---------------------------------------------------------------------------
//----- static methods -----
public static List<Customer> GetaBunchOfCustomers()
{
List<Customer> aList = new List<Customer>();
aList.Add(new Customer(1,"Sir","James","Bolam", new DateTime(2004,01,17), true, 0));
aList.Add(new Customer(2,"Miss","Mary","Malone", new DateTime(2006,03,11), false, 125.0));
aList.Add(new Customer(3,"Mr","John","Parker", new DateTime(2005,05,23), true, 250.0));
aList.Add(new Customer(4,"Mrs","Bev","Frances", new DateTime(2008,09,07), true, 180.13));
aList.Add(new Customer(5,"Prof","Nick","Friend", new DateTime(2007,11,02), true, 90));
aList.Add(new Customer(6,"Mr","Paul","Piko", null, false, 0));
aList.Add(new Customer(7,"Dr","Dan","Logan", null, false, 350.0));
aList.Add(new Customer(8,"Ms","Laura","Hepburn", new DateTime(2013,4,24), true, 50.13));
aList.Add(new Customer(9,"Dr","Mike","Stein", null, false, 150.0));
aList.Add(new Customer(10,"Mr","Ben","Hepburn", new DateTime(2012,01,14), true, 0.13));
aList.Add(new Customer(11,"Dr","Paul","Ryan", new DateTime(2013,09,04), true, 190));
aList.Add(new Customer(12,"Mr","Willie","Moore", new DateTime(2011,06,06), false, 450.0));

//Regex r = new Regex("e");
//var query =
// from i in aList
// where r.Match(i.FirstName).Success
// select i;

//var aList2 = query.ToList();
//return aList2;
return aList;
}
//--------------------------------------------------------------------------------------------
}
}
=================================================================================

PHH - 5th. September 2013.


Library Classes - 'Contact'

Library Classes - 'Contact'

Library Classes - 'Contact'

 Previous topic Next topic

The second class I am creating / designing / constructing, is that for 'Contact', and this class is

required for a number of other types of data - Customer, Supplier, and Logistics.

To get us going we will just stick with the extra Foreign key being for 'CustomerId' and we will add

the others later, when we have all three of these we will need to make the data optional.

Here is the sort of things we need - check this out as I have it working in Management Studio (MS) :-

=================================================

And when we use the context menu option for the first 1000 records we see this :-

======================================================================================================================================

Yes, it works fine - but just two records as we saved just two objects from our STATIC collection method.

Lets see what the 'DataContext' class now looks like when we need to make two Tables :-

===========================================================================================

Yes, line 39 has been added, and the new 'Contact' class as it stands at the moment looks like that below.

Check out both the part collapsed and then the expanded form of our code :-

================================================================================================

*** Notice *** that the value of the identity for added Contact (primary key) is generated by the database engine.

We did not supply a value and yet in MS we see the following :-

=====================================================

Although we don't need to specify anything with L2S, the 'CustomerId' column is actually a Foreign key.

Only the Primary key is generated by the server.

Now checkout a couple of the expanded properties :-

===========================================================================================

And importantly, we need to see both the new population method, along with the previous one

which I have changed - for good reason.

In the images below we need to distinguish the class type of the supplier of the 'collection'.

In L2S we use 'DataContext' and so I am using 'dC' - more on this later, fist check it out :-

================================================================================================

*** Note *** that I have changed the 'db' we see in the SDK, or web notes, to be 'dC' to reflect the correct

underlying type of 'DataContext'

When we come to Entity sections I will use 'dbC' to reflect the 'DbContext' underlying type fro EF4. This

helps us a great deal when we are comparing all these technologies at one go.

Now we can view the 'Contact' class after inclusion of the other two 'Id' fields etc. :-

==========================================================================

The above is really an 'old style' as we have int values needing no values, but we are NOT using 'nulls' as yet !

Lets follow through this OLD way before we see the enlightened way :-

================================================================================================

If we do things the 'old way', using default values we can do the following :-

============================================================================================================

Using NULLs - in code and in the DB :

Now the new way - check this out thoroughly :-

==========================================================

Line 24 through 26 have been changed to accommodate the 'NULL' approach.

We also need to change a couple lines in the property definitions too - see below :-

==========================================================================================

================================================================================================================

======================================================

==================================================================================================================================

PHH - 10th. September 2013.


working code

working code

working code

 Previous topic Next topic

=====================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//----- added for LINQ -----
using System.Data.SqlClient;
using System.Data.Linq.Mapping; //----- needed for Table & Column .....
using System.Data.Linq;
using System.Data.Sql;
//==================================
using System.Collections;
using System.Collections.ObjectModel; //----- ObservableCollection .....
using System.ComponentModel; //----- INotifyPropertyChanged .....

namespace DALclassLibrary
{
[Table(Name = "Contacts")]
public class Contact
{
//----- fields -----
int _contactId;
int _customerId;
string _address;
string _phone;
string _mobile;
string _email;
Nullable<DateTime> _whenAdded;
Boolean _isActive;
Nullable<DateTime> _whenDeactivated;

//----- events -----
public event PropertyChangedEventHandler PropertyChanged;

//----- properties -----
[Column(IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
public int ContactId
{
get { return _contactId; }
set { _contactId = value; NotifyPropertyChanged("ContactId"); }
}

[Column(CanBeNull = false)]
public int CustomerId
{
get { return _customerId; }
set { _customerId = value; NotifyPropertyChanged("CustomerId"); }
}

[Column(CanBeNull = false)]
public string Address
{
get { return _address; }
set { _address = value; NotifyPropertyChanged("Address"); }
}

[Column(CanBeNull = true)]
public string Phone
{
get { return _phone; }
set { _phone = value; NotifyPropertyChanged("Phone"); }
}

[Column(CanBeNull = true)]
public string Mobile
{
get { return _mobile; }
set { _mobile = value; NotifyPropertyChanged("Mobile"); }
}

[Column(CanBeNull = true)]
public string Email
{
get { return _email; }
set { _email = value; NotifyPropertyChanged("Email"); }
}

[Column(CanBeNull = false)]
public Nullable<DateTime> WhenAdded
{
get { return _whenAdded; }
set { _whenAdded = value; NotifyPropertyChanged("WhenAdded"); }
}

[Column(CanBeNull = false)]
public Boolean IsActive
{
get { return _isActive; }
set { _isActive = value; NotifyPropertyChanged("IsActive"); }
}

[Column(CanBeNull = true)]
public Nullable<DateTime> WhenDeactvated
{
get { return _whenDeactivated; }
set { _whenDeactivated = value; NotifyPropertyChanged("WhenDeactivated"); }
}

//----- constructors -----
public Contact() { this.ContactId = -1; }

public Contact(int nCust,string cA, string cP, string cM, string cE,
Nullable<DateTime> dtA, Boolean lA)
{
//this.ContactId = nI;
this.CustomerId = nCust;
this.Address = cA;
this.Phone = cP;
this.Mobile = cM;
this.Email = cE;
this.WhenAdded = dtA;
this.IsActive = lA;
//this.WhenDeactvated = dtD;
}

//----- methods -----
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//---------------------------------------------------------------------------
//----- static methods -----
public static List<Contact> GetContactsList()
{
List<Contact> aList = new List<Contact>();
aList.Add(new Contact(1, "43, Side Street, Bristol.", "123 45678", "0789 3456 324",
"info@somewhere.co.uk",new DateTime(2004, 01, 17), true));

aList.Add(new Contact(3, "15, Back Alley, Newport.", "", "0789 6345 111",
"contacts@myfirm.com",new DateTime(2007, 04, 23), true));

return aList;
}
//--------------------------------------------------------------------------------------------
}
}

=====================================================================================

PHH - 10th. September 2013.


Library Classes - 'Product'

Library Classes - 'Product'

Library Classes - 'Product'

 Previous topic Next topic

PHH - 6th. September 2013.


Library Classes - 'Order'

Library Classes - 'Order'

Library Classes - 'Order'

 Previous topic Next topic

PHH - 6th. September 2013.


C# class library - making, for 'Data Access Layer'

C# class library - making, for 'Data Access Layer'

C# class library - making, for 'Data Access Layer'

 Previous topic Next topic

'DAL' is "Data Access Layer".

Please be aware that there are numerous way of structuring the DAL so that we provide suitable functionality

for the Vulcan business logic layer to have as much LINQ capability as possible.

For many guys they wish to do as much coding as possible in the Vulcan syntax, but at the same time also

wish to have a bunch of useful classes and members which handle data access with the latest technology.

Also, like all .NET projects and solutions created in VS we need to plan and create a well organised node and

item structure within the SE pane - some call this a 'folder' structure'.

As you will see below, I started out as most guys with some classes in my Class Library folder, before I realised

that I needed a much better, or tighter, 'structure'.

I will show you a bit later how to improve what we started with - but first let us see what Classes we need.

Suitable Data Classes :

For a DAL from which we wish to use LINQ to access a SQL database, we need a minimum of a single class to

go with each Table we have in our database (DB).

For use with Entity Framework 4 (and above) we have a slightly more complex mapping from Table to Object class.

However, we can get a long way be studying a DAL for a basic "LINQ to SQL" (L2S), where the mapping is 'one to one'.

My choice of structuring started like that shown below, a set of class related files in the root of the 'class library' folder.

Check this out below :-

=================================================

This was OK for some initial trials and testing, but beyond that it proved to be messy and slightly confusing.

With a little thought of where we are headed (with our app development) and a few clicks of the mouse, we can

do a lot better and have a new structure for our class library (CL) as shown below :-

============================================

In the above folder structure we will place files according to their general function, so all STATIC members which

allows our code to add / insert new objects into Tables as rows, are together in one folder called 'Add'.

I prefer this personally that having grouping by Table name, and including the whole set of functional STATIC members

within a named Table folder.

You may differ, and like to do things differently.

So before we move on to look at functionality in more detail, lets see an expanded view of what I now have :-

====================================

The general folder can most probably improve somewhat, it is just where I placed all the 'stuff' that

I had used in my initial trials etc..

In fact, in the above image only the Customer file in 'Classes' has any real content.

Lets now move on to sort out the functional STATIC members ............

STATIC members / methods to Access and Maintain Table data :

Okay guys below is shown the rather messy folder where I have previously had some test

STATIC functional methods - those that do an 'active' task regarding Tables in our DB.

Lets take a look at what I have before we tidy things up, and introduce some sort of order or

structure to the SE pane entries.

Check this out - study the details carefully :-

=================================================================================

Many of the above were done as part of my trials and exploration for DevShare13, so we see

some duplication of 'purpose'.

We can see members for retrieving data, as well as filling Tables, both initially and adding items

afterwards.

Also we see a definite 'General' member which makes a Back-Up copy of our database. And the

'CreateLibDB' is also a general classification of static member.

Moving on .................

Okay you guys, so far we have made the basic 'shell' or structure of our DAL or Data Access Layer,

restructured it, and now we need to move some of the above members into the suitable folders we

made two images above.

Major Re-structuring of the SE pane - Folders Added :

Okay guys, let us realise right from the start that getting a well organised, and structured, SE pane right

from as early as possible is a GOOD idea. Do it sooner rather than later !

The reason is simple, if we are to create and use a bunch of STATIC members in the class library file,

then when they are 'structured' correctly the calling code changes - so there are code editing tasks to do.

I will explain as we go along, and it is probably best to start with the final SE pane as it is collapsed

and on my desktop, in VS 2012 - check this out :-

=====================================

Notice that we now have an extra folder, that for 'Enums'.

But first, let us look at what we now have in the Populate folder. The following image shows that

within the folder we have a similarly named code file - check it below :-

=========================================================

Notice that the STATIC method (member) called 'FillTableWith BunchCustomers' is now within the

Populate code file, and also part of the 'Populate' class.

Here is the present state of the 'SQL_General' code file and class - the above member is no longer to be see :-

=================================================

Yes, viewing the above image we see that list of members is much shorter - after our reorganisation.

We can see that the members left - STATIC methods - are generally applicable to the database, like that

to create the DB and Tables, and another to make a database full 'Back-up'.

Yes, there is also a class which is our sub-classed 'DataContext' one called 'OurLibraryAndVN3'. Once

again this is a to be generally available.

Now then, lets look in details at the 'Populate' class, within the Populate.cs code file - check this :-

====================================================================================================

In the above code line 26 is still applicable - and OK - because the static member is still within the

class called 'SQL_General', however, in the next image we see we have had to make a change to the

code because of our restructuring - check this out :-

============================================================================

Line 40 above has been inserted to replace the older line 41.

There will be quite a few changes to make like this, simply because of our restructuring, and as

I said earlier, a VERY good reason to make sure we all get some organisation and folder structure into

our apps before we go very far - at all.

With a well thought out, and implemented structure, it will be easier to code our business logic, and also

for us (and others) to make changes afterwards / in the future.

There are many out there who struggle with VS and the SE pane, and blame VS for their troubles and woes,

when in fact it is their poorly structured solution which is causing most of the issues and problems.

Don't be one of these, don't get caught out ;-)

Now we need to take a quick look at the greatly reduced, and tidied up 'SQL_General' class and code file :-

======================================================================================================

Okay, no surprises above, except as to how tidy it looks.

Let's move on ...................

A note about Namespaces, and Directives :

Because most of the new code files for the added folders are still basically empty, I have just copied

the same bunch of directives to the head of the file, as were making my working and tested file compile

and run.

We can always reduce this later if it bothers you - personally I find it a bigger nuisance to be short of

a required namespace reference (directive) than to have to live with an untidy list - which after all may

be collapsed to be out of sight.

Here below is the sort of thing I am referring too - check it out :-

===========================================================================================

In the empty code file shown above we will eventually place any STATIC method which is used to

remove (or delete) one or more records from a specific Table. Obviously we would supply the

member with a collection of existing objects - ones with Primary Keys that exist in the Table.

Finally - before we go, and move on :

Let us now turn our attention to the main Vulcan calling module, that which consumes the Class

Library based on LINQ and L2S.

Lets see a couple of interesting lines - check this out first :-

===============================================================================================

In line 53 see that we now have our STATIC method being called with 'Query' and not 'SQL_General'.

Since getting back a collection of custom objects is the result of a query statement, then this static

member is placed in the 'Query' folder, code file, and class.

The second of our points to consider is on line 51, where from our Vulcan code we are sending a bunch

of custom objects (in this case customers) to the SQL database and Table called 'Customers'.

Lets take a peek at what this looks like - study the following :-

======================================================================================================================

Yes, it is as easy as that - make a list (collection) of the customer objects we require, then pass this

collection as a parameter to the STATIC method on line 189.

And the Class Library code will make sense to you by now - check this out below :-

================================================================================================

Lets move on, see you in the next subsection ..............................

[ .. I suggest you take a look at the subsection three ahead of this, entitled 'Adding functionality to the C# class library' .. ]

PHH - 10th. September 2013.


Making a VN3 project to consume the C# DLL

Making a VN3 project to consume the C# DLL

Making a VN3 project to consume the C# DLL

 Previous topic Next topic

Well folks, this section material has come on much faster than I anticipated. Which is good!

It seems as easy to add a Vulcan project to my growing and developing solution on a Data Access

Layer in C#, as pie, and so we may as well do it sooner rather than later.

Also we can probably add and test it at the same time as we add to and test from our C# project.

So right click the solution node in the SE pane and select from the context menu to add a new project.

Here is the dialog screen :-

============================================================================================================

We do not get any check boxes for 'Source Control' as that happens only with a new App. The class library did

not have these either, and when we click OK here we see that we will have TFS support a-okay !

Here is what comes up next, see the new Vulcan project at the bottom part of the SE pane ?

Check this out :-

=============================================

Note that we have TFS icons but that they have not as yet changed shape to

show that we have checked-in the project. Lets do that now.

======================================================

And so we now see some new icons - view details below :-

============================================================

As with the C# project earlier, we need to add a new reference to the References section / node.

Here is what we start with :-

==============================================

Right click in the Vulcan project node to bring up the next screen - the Add Reference dialog :-

================================================================================

The dialog is different to that for C#, but it works just fine.

Select the class library item and click the OK button.

Here is what I got :-

========================================

Yes, I know, this looks a bit short compared to the C# one earlier, we may well have to

add a couple more later, but since we are not going to be using LINQ then we may get away

without any - time will tell.

Okay then guys, time for the BIG test ! Lets make the Vulcan project the 'start-up' one and

then go build and run. here are some screen shot details :-

========================================

And now something good to smile over :-

==============================================================================

Yep! it actually compiles and runs - not much to look at through the Window however !

Lets move on a pace .............

Adding Namespaces :

So that we can add suitable classes to our Vulcan main window app we need to include the following

directives at the head of our code file - check these :-

==========================================================================================

Make your Vulcan code file look something like that shown below - making the Initialise() method

just an empty member for the moment. (Ignore the collapsed lines.)

===========================================================

Now go to the XAML editor for file Window1.xaml, and add a couple of controls that we will use

quite soon for testing.

Here is what I have, make your app similar :-

==========================================================================================================

Lets move on and use the class library to make our database and table.

Making the Database (DB) :

Okay then folks, it is quite an easy task to now add some code lines to our VN3 main window so that we

cause the DB to be created each time we build and run.

We also need to make and populate the Table for holding customer data.

Study the following details carefully :-

================================================================================================

In the Constructor we now have on line 30 a call to a new method, this member handles the calls to

the class library for dropping and creating the database, as well as making the Table and populating

it with suitable data. Look above at lines numbered 37 & 38.

Since we have included a directive in the header we can actually leave out the "DALclassLibrary" as

you can see below :-

====================================================================

Once we have made the calls to create the DB and Table, we can then run the Initialise method, which as

you can see in the next image - on line 49 - calls the retrieval member in the library for providing all the Customer

objects in a suitable collection - check this out :-

===============================================================================================================

Line 50 above is where we bind the collection to the UI element property. Without this we would see an empty

'DataGrid' control.

Here is a useful test / experiment - check out below :-

========================================================================

PHH - 4th. September 2013.


Handling 'nulls' - in and out of the DB

Handling 'nulls' - in and out of the DB

Handling 'nulls' - in and out of the DB

 Previous topic Next topic

Here is a 'Truism' :- "No matter how easy it gets to code .NET objects to SQL Table records, there

will always remain issues with NULLs".

Yes, things have gotten a lot easier - BUT - we still have to be careful how we handle nulls, and their

input to the DB and their extraction from the same.

Yes, I did say data types and matching with LINQ to SQl was far better (and improved) than when we

dealt with ADO.NET, but we still need to consider them and make a few recommendations for the future.

Let us start by seeing some SQL data as viewed from MS (Management Studio) - this is MSSS 2012.

Check this out :-

==========================================================================================================================================

Notice the three NULL entries under the 'FirstOrder' column - with pale yellow background.

This means that for these three data records in the table, the date of the first order for the particular

customer, is unknown. Since it is unknown then we can't enter any value at all, not even a default - it

is unknown.

NULLs can be most useful to us, and our coded solutions - IF - we use them wisely, and correctly.

What comes First ? :

When we are using L2S we need to specify for each column / property whether it is to be able to accept

NULLs - ( do not say 'null values' ! )

This is for both Code First and Data First.

Below we see an image where an attribute is set on the property for 'FirstOrder' - check it out :-

===================================================================================================

Rather than let any default setting take over I prefer to explicitly set this attribute, so we also have this below :-

=========================================================================================

Lets now continue with details which must be applied when we wish the property / column to be able

to accept NULLs.

Lets first of all see how this affects the private fields for out Customer class - study image shown below :-

=============================================================

For the type of a property which we wish to be able to accept NULLs it is best to do as I have above,

and make the particular type a 'Nullable<T>'.

Now when we define a Constructor which accepts a parameter input for this property it looks like

the following, in code :-

=============================================================================================

With this code in place, we can then write some C# code to enter data into a collection as follows :-

===================================================================================================================

Notice above that three data lines have 'null' for the 'FirstOrder' entry.

When I came to code something similar in Vulcan 3 I had a couple of issues and eventually got the

following to work for me - I confess my VN skills were a bit rusty after all my Metro app coding ;-)

Check out this which works :-

============================================================================================================

Whatever the way you prefer, it is best to come to terms with the 'null' and get suitable, and correct, ways of

dealing with them.

The lines numbered 87, 88, 94, and 95 may well come in useful to you.

Time to move on, see you in the next subsection .............

PHH - 6th. September 2013.


working script and code

working script and code

working script and code

 Previous topic Next topic

================================================================================
#using System
#using System.Collections.Generic
#using System.Linq
#using System.Text
#using System.Windows
#using System.Windows.Controls
#using System.Windows.Data
#using System.Windows.Documents
#using System.Windows.Input
#using System.Windows.Media
#using System.Windows.Media.Imaging
#using System.Windows.Navigation
#using System.Windows.Shapes
//-----------------------------------
#using DALclassLibrary
#using System.Text.RegularExpressions
#using System.Windows.Data //----- CollectionViewSource .....
//----- and below for SortDescription too .....
#using System.ComponentModel; //----- INotifyPropertyChanged .....

BEGIN NAMESPACE Vulcan3ConsumerOfLINQ

PARTIAL CLASS Window1 INHERIT Window

CONSTRUCTOR()
SUPER()
InitializeComponent()
SELF:Initialise()
return

method Initialise() as void
try
DALclassLibrary.SQL_General.CreateLibDB()
SQL_General.FillTableWithBunchCustomers()
//----- using a LINQ class library - for our Data Access Layer .....

self:AddMoreCustomers()

//self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetBackAllCustomers()

local aList as List<Customer>
aList := DALclassLibrary.SQL_General.GetBackAllCustomers()

local myCVS as CollectionViewSource
myCVS := CollectionViewSource{}
myCVS:Source := aList

local mySD as SortDescription
mySD := SortDescription{"IsLocal", ListSortDirection.Ascending}
myCVS:SortDescriptions:Add(mySD)

local mySD1 as SortDescription
mySD1 := SortDescription{"LastName", ListSortDirection.Descending}
myCVS:SortDescriptions:Add(mySD1)

//self:dgClassLibrary:DataContext := myCVS
self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetAllCustomersDirect()

//myCVS:Filter += FilterEventHandler{self, @ShowOnly50to200()}

//----- make a full DB back-up ! -----
DALclassLibrary.SQL_General.MakeBackUpCopyDB()

//self:AddMoreCustomers()

myCVS:Filter += FilterEventHandler{self, @RegExTester()}
//self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetBackAllCustomers(Regex{".13"})
//self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetBackAllCustomers(Regex{"e"})

/* self:dgClassLibrary:DataContext := ;
DALclassLibrary.SQL_General.GetBackAllCustomers(SQL_General.fieldPropertyCustomer.firstname, Regex{"[ku]"})*/

////----- groups the items in the view by the property "isLocal" -----
//PropertyGroupDescription groupDescription = new PropertyGroupDescription();
//groupDescription.PropertyName = "isLocal";
//myCVS.GroupDescriptions.Add(groupDescription);

SELF:tblkMessage:Text := "we have SQL data retrieved !! - well done Vulcan 3.0 "
SELF:tblkMessage:Foreground := SolidColorBrush{Colors.Red}
SELF:tblkMessage:FontSize := 18
catch oEX as SystemException
self:tblkMessage:Text := oEX:Message
end try
return

method AddMoreCustomers() as void
local dtNull as Nullable<DateTime>
dtNull := Nullable<DateTime>{}
//--------------------------------
local aList as List<Customer>
aList := List<Customer>{}
aList:Add(Customer{13,"Master","Geoff","Goodage", DateTime{2010,08,23}, false, 123.45})
aList:Add(Customer{14,"Miss","Sally","Spackman", DateTime{2009,03,17}, true, 299})
aList:Add(Customer{15,"Mr","Nully","Able", dtNull, true, 299})
aList:Add(Customer{16,"Mr","Able","Nully",Nullable<DateTime>{}, true, 299})
//--------------------------------------------------------------------------------------
DALclassLibrary.SQL_General.AddMoreCustomers(aList)
return

method ShowOnly50to200(sender as object, e as FilterEventArgs) as void
local oC as Customer
oC := (Customer)e:Item
if (oC != null)
if (oC:CreditLimit >= 50 && oC:CreditLimit <= 200)
e:Accepted := true
else
e:Accepted := false
endif
endif
return

method RegExTester(sender as object, e as FilterEventArgs) as void
local oC as Customer
oC := (Customer)e:Item
if (oC != null)
LOCAL r as RegEx
r := RegEx{"[ku]"}
if ( r:Match(oC:FirstName:ToString()):Success )
e:Accepted := true
else
e:Accepted := false
endif
endif
return

END CLASS

END NAMESPACE

================================================================================

<Window x:Class="Vulcan3ConsumerOfLINQ.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Vulcan 3 and 'LINQ to SQL'" Height="350" Width="535">
<Grid>
<DataGrid HorizontalAlignment="Left" Margin="0,49,0,0" VerticalAlignment="Top"
Name="dgClassLibrary" Height="270" Width="517"
GridLinesVisibility="All" ColumnWidth="Auto"
AlternatingRowBackground="SkyBlue" AlternationCount="2"
HeadersVisibility="All" ItemsSource="{Binding }"
AutoGenerateColumns="True" />

<TextBlock HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap"
Text=".. messages .." VerticalAlignment="Top" Height="44" Width="507"
Name="tblkMessage"/>
</Grid>
</Window>
================================================================================

================================================================================

PHH - 6th. September 2013.


Adding functionality to the VN3 project

Adding functionality to the VN3 project

Adding functionality to the VN3 project

 Previous topic Next topic

PHH - 6th. September 2013.


Adding more new Customers

Adding more new Customers

Adding more new Customers

 Previous topic Next topic

PHH - 6th. September 2013.


Upating existing records / objects

Upating existing records / objects

Upating existing records / objects

 Previous topic Next topic

PHH - 6th. September 2013.


Collections : Sorting, Filtering and Grouping

Collections : Sorting, Filtering and Grouping

Collections : Sorting, Filtering and Grouping

 Previous topic Next topic

"Viewing" - with the 'CollectionViewSource' class :

PHH - 6th. September 2013.

 /* local myCVS as CollectionViewSource

                myCVS := CollectionViewSource{}

                myCVS:Source := aList

                local mySD as SortDescription

                mySD := SortDescription{"IsLocal", ListSortDirection.Ascending}

                myCVS:SortDescriptions:Add(mySD)

                local mySD1 as SortDescription

                mySD1 := SortDescription{"LastName", ListSortDirection.Descending}

                myCVS:SortDescriptions:Add(mySD1)

                //self:dgClassLibrary:DataContext := myCVS

                self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetAllCustomersDirect()*/

                //myCVS:Filter += FilterEventHandler{self, @ShowOnly50to200()}

                /*//----- make a full DB back-up ! -----

                DALclassLibrary.SQL_General.MakeBackUpCopyDB()

                //self:AddMoreCustomers()

                myCVS:Filter += FilterEventHandler{self, @RegExTester()}*/

                //self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetBackAllCustomers(Regex{".13"})

                //self:dgClassLibrary:DataContext := DALclassLibrary.SQL_General.GetBackAllCustomers(Regex{"e"})

               /* self:dgClassLibrary:DataContext := ;

                DALclassLibrary.SQL_General.GetBackAllCustomers(SQL_General.fieldPropertyCustomer.firstname, Regex{"[ku]"})*/

                ////----- groups the items in the view by the property "isLocal" -----

                //PropertyGroupDescription groupDescription = new PropertyGroupDescription();

                //groupDescription.PropertyName = "isLocal";

                //myCVS.GroupDescriptions.Add(groupDescription);


CVS - Sorting with

CVS - Sorting with

CVS - Sorting with

 Previous topic Next topic

"Viewing" - with the 'CollectionViewSource' class :

The first action we will study using the 'CollectionViewSource' (CVS) class, operating on the Vulcan side of

the application using a C# class library for the Data Access Layer (DAL), is that of 'sorting'.

Although we can't use LINQ in VN3 we can use CVS to help process and display our collections of custom

objects, however we create them - or wherever they originate.

In may ways the CVS is an older technology to LINQ and so we should always use LINQ when possible.

However, having said that, it is a VERY useful technology to have to hand for use with Vulcan 3 and on the

business logic side of the DAL.

Lets move on a pace or two, and see sorting in action ..............

Sorting the item Objects in Our Collections :

Before we study the detail of the VN3 code used, let us first see the results which can be achieved using

the CVS class with some correctly set properties.

Check this out :-

=====================================================================================

In the above image notice that the order of the objects (rows in the data grid) is by 'IsLocal' ascending.

Within that the order is by customers 'LastName' property - descending, or Z-A.

Study the details to convince yourself that this is correct.

Now we are ready to see the small changes in the calling code, at the start of the demo app,

so see line 33 for where this is done :-

====================================================================================

And all it leaves to be done is for us to carefully follow through the code lines that are in the

member called 'ViewStuff'. Check out the following :-

==============================================================================================

Once we have instantiated a CSV object we need to add items into the collection property called

'SortDescriptions'. Noting that a new 'SortDescription' object has to have a property name associated

with it as well as a 'ListSortDirection'.

These input parameters to the constructor are of type string and enum - check lines 75 and 79.

Now then, the way this sorting woks is that the first sort defined is the coarsest one (major one), and

then each one provided is the next down in coarseness, so the last sort description is the very finest.

In the old days of Tandy computers we used to call this a multi-key sort.

Our data does not really lend to us trying may more sorts as we do not have enough similarities. But

we can try 'FisrtName' then 'LastName' to see what we get for our "Paul" entries.

Check these details :-

======================================================================================================================================

Note that the above order, in both cases, is ascending (A-Z).

When we come to a subsequent subsection on 'Grouping' we will make the distinction between

'Grouping' and the sort orders set on the collection.

But now its time to move on to filtering collection items - applying a filtering condition.

PHH - 7th. September 2013.


CVS - Filtering with

CVS - Filtering with

CVS - Filtering with

 Previous topic Next topic

"Viewing" - with the 'CollectionViewSource' class :

PHH - 7th. September 2013.


CVS - Grouping with

CVS - Grouping with

CVS - Grouping with

 Previous topic Next topic

"Viewing" - with the 'CollectionViewSource' class :

PHH - 7th. September 2013.


working script and code

working script and code

working script and code

 Previous topic Next topic

====================================================================================
method ViewStuff() as void
try
local aList as List<Customer>
aList := SQL_General.GetBackAllCustomers()
self:dgClassLibrary:DataContext := aList

local myCVS as CollectionViewSource
myCVS := CollectionViewSource{}
myCVS:Source := aList

local mySD as SortDescription
mySD := SortDescription{"IsLocal", ListSortDirection.Ascending}
myCVS:SortDescriptions:Add(mySD)

local mySD1 as SortDescription
mySD1 := SortDescription{"LastName", ListSortDirection.Descending}
myCVS:SortDescriptions:Add(mySD1)

self:dgClassLibrary:DataContext := myCVS

//-----------------------------------------------------------------------
SELF:tblkMessage:Text := "trying 'CollectionViewSource' with Vulcan 3.0 "
SELF:tblkMessage:Foreground := SolidColorBrush{Colors.Red}
SELF:tblkMessage:FontSize := 18
catch oEX as SystemException
self:tblkMessage:Text := oEX:Message
end try
return

====================================================================================

method ViewStuff() as void
try
local aList as List<Customer>
aList := SQL_General.GetBackAllCustomers()
self:dgClassLibrary:DataContext := aList

local myCVS as CollectionViewSource
myCVS := CollectionViewSource{}
myCVS:Source := aList

local mySD as SortDescription
mySD := SortDescription{"FirstName", ListSortDirection.Ascending}
myCVS:SortDescriptions:Add(mySD)

local mySD1 as SortDescription
mySD1 := SortDescription{"LastName", ListSortDirection.Ascending}
myCVS:SortDescriptions:Add(mySD1)

self:dgClassLibrary:DataContext := myCVS

//-----------------------------------------------------------------------
SELF:tblkMessage:Text := "trying 'CollectionViewSource' with Vulcan 3.0 "
SELF:tblkMessage:Foreground := SolidColorBrush{Colors.Red}
SELF:tblkMessage:FontSize := 18
catch oEX as SystemException
self:tblkMessage:Text := oEX:Message
end try
return

====================================================================================
method ViewStuff2() as void
try
local aList as List<Customer>
aList := SQL_General.GetBackAllCustomers()
self:dgClassLibrary:DataContext := aList

local myCVS as CollectionViewSource
myCVS := CollectionViewSource{}
myCVS:Source := aList

//----- now set event handler association -----
myCVS:Filter += FilterEventHandler{self, @RegExTester()}

self:dgClassLibrary:DataContext := myCVS
//-----------------------------------------------------------------------
SELF:tblkMessage:Text := "trying 'CVS - RegEx : filtering' with VN3 "
SELF:tblkMessage:Foreground := SolidColorBrush{Colors.Red}
SELF:tblkMessage:FontSize := 18
catch oEX as SystemException
self:tblkMessage:Text := oEX:Message
end try
return

====================================================================================

method RegExTester(sender as object, e as FilterEventArgs) as void
local oC as Customer
oC := (Customer)e:Item
if (oC != null)
LOCAL r as RegEx
r := RegEx{"[ku]"}
if ( r:Match(oC:FirstName:ToString()):Success )
e:Accepted := true
else
e:Accepted := false
endif
endif
return

method ShowOnly50to200(sender as object, e as FilterEventArgs) as void
local oC as Customer
oC := (Customer)e:Item
if (oC != null)
if (oC:CreditLimit >= 50 && oC:CreditLimit <= 200)
e:Accepted := true
else
e:Accepted := false
endif
endif
return
====================================================================================

PHH - 7th. September 2013.


Reflection to find Tables

Reflection to find Tables

Reflection to find Tables

 Previous topic Next topic

================================================================================================================================

======================================================================================

PHH - 11th. September 2013.


Reflection to find Properties

Reflection to find Properties

Reflection to find Properties

 Previous topic Next topic

====================================================

====================================================================================================================

=================================================================

PHH - 11th. September 2013.


Adding functionality to the C# class library

Adding functionality to the C# class library

Adding functionality to the C# class library

 Previous topic Next topic

What we can to to and for Customer objects - records in the Customers Table - we also do for

other classes with related data Tables in the SQL database.

One set of related tasks which were a 'real pain' in ADO.NET, was adding and updating Table records.

This has changed a great deal with the advent and introduction of LINQ technology - thank goodness ;-)

The volume of boring, basic code, has diminished a whole lot, and it is much easier for us to concentrate

on the business logic required to solve our problems.

Also as we do these data updates in this 'modern world', we are working in .NET classes, and coding with C#,

and so the chances of errors occurring is lessened.

Adding more Customer objects into our Customers Table :

Updating Existing Customers - data from Table to objects and then back to Table :

Removing Existing Customers :

Exercises on the Above :

Adding Members to the 'General' folder :

Adding Queries to the 'Query' folder :

PHH - 10th. September 2013.


JOINs and multiple Tables

JOINs and multiple Tables

JOINs and multiple Tables

 Previous topic Next topic

Okay then guys, lets do something which feels a bit more like the real world and its querying.

Lets us use our C# LINQ data access layer (DAL) to provide back to our calling Vulcan module a

collection based on an inner join of two Tables.

Let us join the Customers table with the Contacts table, on the value of the column 'CustomerId'.

First we can check this out as it is done in MS - see below for query and resultant data :-

=================================================================================================================================

=================================================================================================

Yes, the above query produces a LONG image in Management Studio (MS) ;-0)

Lets move on .................

Making a Start - 'DAL' and Joining :

Let us see our newly coded target static member - even though it is incomplete :-

[ .. the basic structure of the method is fine, we just need to SELECT in a better way .. ]

================================================================================================================

As can be seen in the printed 'query' there looks to be an ominous 'NULL' in Select - not where I had

expected or wished it to be.

The code line 34 seems to be the culprit as there are now columns/properties defined.

Lets see what we get in our display data grid if we continue - check this out :-

==============================================================================================================

Yep! as I thought, apparently two collection items but with no values within them.

The answer is that we have used a new class as the holder of the joined data, and we have NOT set

values for the properties of that class, the 'CustCont' class.

Before we take a look at the code specifying the new 'CustCont' class, let us see an adjusted STATIC

member, coded to set all property values.

Check all these details shown below :-

=================================================================================================

Notice above that we have used all the properties from 'c' and 't' to supply suitable vales for 'CustCont'.

This time when we build and run we see the following printed 'query' - study carefully :-

=====================================================================================

Well now, that looks a bit better than 'NULL' after SELECT, as in the previous print out.

So what do we see in our WPF DataGrid UI element ? - study and 'squint' at the following ;-0)

===================================================================================================================================================

Yes, the above is a little small (font size wise) but get your reading spectacles on !

Notice above that we seem to have handled the 'null' column entries OK, and they show as 'blanks'.

So before we look at the class details, let us see the calling code from Vulcan 3 module :-

================================================================================================

In the above image we see line 35 in Vulcan syntax, this is what calls on the STATIC member from

our DAL - notice too that it comes from the 'Joins' folder and class.

In order to keep our SE pane clean and tidy, I have added a new folder named 'ClassesCompound', as

well as one entitled 'Joins' - check this out below :-

====================================================

We have seen the details in 'Joins.cs' but not that in 'CustCont.cs', so lets do that now :-

[ .. we will need to chop this into parts / sections, as it is so long .. ]

==============================================================

The thing to notice in particular is that the customer ID can't be NULL, it has to be a value,

but that for supplier and logistics may be set to 'null'.

Basically, all fields in both of the Tables have been included in this class.

However, also notice that no attribute exists on line 17, and shown in the image below we see

all the property definitions also without attributes.

This simply means that this class is NOT used to create a Table in the DB, but is used as a containing

vessel for returned data, after the JOIN takes place.

Here are the attribute-less properties :-

============================================================

And then finally, we need to see the other important members, including the VERY simple

constructor - much simpler than out previous classes - check this out :-

============================================================================================

If we choose to make a non empty constructor then we could use a slightly different syntax to

fill it from the 'c' and 't' objects in the way above query code.

Moving on a pace ............................

Let us try to supply only some of the CustCont property values, and also reorder them to be in

order 'c' then 't' - check this out :-

===============================================================

And the view of the results in our data grid are as follows :-

==============================================================================================================================================

Finally, a tidy up of variable names :

I noticed that in the Joins STATIC member I used the old 'db' convention for DataContext class, and not

my newly made one of 'dC' - so I have changed this as seen below :-

===============================================================================================================

So in the above code 'dC' is to remind us that it is based on th DataContext class which we sub-classed to add our

Table properties.

Here is a snap-shot of how our DAL looks in the SE pane :-

==============================================

Time to move on, see you in the next subsection ...............

PHH - 11th. September 2013.

Addendum :

I probably need to add some extra Contact data items so that we can get a better output set !


Direct querying with L2S

Direct querying with L2S

Direct querying with L2S

 Previous topic Next topic

This is one aspect of LINQ which I need to discuss, BUT, one which I also need to ask you to either

not use at all, or only when you have no LINQ way of doing things.

Sending a text script in T-SQL directly to the SQL database engine is 'stepping back in time'.

Having said that, it is very handy indeed to be able to make a Back-Up of the whole DB in a couple of

lines of code.

Any Query Statement or Command :

We can send statements to the DB engine which either change the state of the DB in some way or another,

and these are called 'Command statements', or ones which require data to be returned, and these are usually

termed 'queries'.

Dropping a Table or making a View, is an example of a command statement.

Asking how many customers joined as new customers last month, is an example of a 'data' query.

The problem with any system which allows us to send a text string query to the Server is that there is no

real way of telling if it contains errors before hand, except by testing the string externally with Management

Studio, or similar.

Even then, there could be runtime errors because the general environment of the SQL database has changed.

So take CARE - direct querying is great sometimes, but needs to be handled carefully.

Let us start with something VERY simple, so that we don't make any errors ;-)

Let us try a direct query that should be done using LINQ standard syntax.

Study the following thoroughly, line 136 in particular :-

[ .. notice we need to make a suitable connection first .. ]

===================================================================================================================

===========================================================================================================

===========================================================================================

===================================================================================================================================================================

Making a Back-Up :

============================================================================================

=========================================================================================

============================================================================================================

PHH - 6th. September 2013.


Objects - from start to finish

Objects - from start to finish

Objects - from start to finish

 Previous topic Next topic

Some people would say that LINQ allows us in code to have Objects from start to finish, if we are

using XAML mark-up.

However, when using LINQ to SQL ('L2S'), or similar, we can often have Objects before we start !

With CF (Code First) which is available to us is numerous SQL data providers, we can code our

object classes and then have the system at runtime make the database (DB) and any required Tables.

So we never go 'lower' than dealing in our business or custom objects - nice ;-0)

One restriction of Code First in technologies not as complex as Entity Framework 4 or later, is that

we are then limited to 'flat' objects - classes which just have simple data types, and not collections.

So if we want to define a class of 'Customer' with a property of 'CustOrders' which is a collection of

Order items, and Orders is to be another class, then we need to reach for EF4.

Having said that however, the 'LINQ to SQL' appraoch can do a lot for us, and help solve a lot of problems.

Since L2S is available to us in 'Phone 8' then that's what I will use, quite happily!

Lets move on .......

What is needed in class code to make a Table ? :

This topic section is all about the code we need to provide in our classes in order to be able to use CF

effectively.

In the following image I will provide the basic coding, and not clutter the class definition with the extra bits

that are required to handle the property change notification.

Here is what I have used with success, to make Tables in a local database for Windows Phone 8 :-

===================================================================================================

The above image shows that we need to use attributes, to effective specify the nature of the class and properties.

Basically, I just fund a working example and copied and amended it, so I got working what I wished to have.

I suggest you do the same, and you will soon get the hang of it.

Once we have our class defined, we add an appropriate line to a simple new class based on DataContext.

Here is a working example :-

==================================================================================================

Basically, in the code above, we have sun-classed the DataContext class and added a public property

of type Table, which is based on the class 'StateOftheUS' as we saw defined two images above.

Obviously a suitable connection string has to be supplied.

Notice that the name of the property will end up as the name of the table - I usually like to keep the

Table and the class identical in name. You may wish to do otherwise.

Lets move on further .............

Making the DB and Table :

Here is a working example of "Code First" in action ;-) Check this out carefully :-

================================================================================================

In the above image we have coded things such that we provide a connection string - adapted form a

working example I found - and then instantiated an object of the type of our 'DataContext' class.

Once we use this 'db' object to create a DB everything is done for us. If we have more than one property

of type Table<T> then we get more than one Table, as simple as that.

In fact the small amount of code shown above, does quite a lot.

It makes the database, fills the new Table with 50 rows of data, then reads this table data back into memory

as a collection of custom objects, which it then binds to the List display UI element.

Try comparing that with ADO.NET approaches ;-0)

Even the method to fill the Table is rather small in size - check this :-

===================================================================================================

The only part that is unseen is the code which creates the list from some hard coded data values.

Its a bit long and tedious - BUT - we can hide 48 other similar line entries - check this :-

===================================================================================================================================================

Moving on ...............

So where does all of this leave us ? :

Well guys, if you ever did any ADO.NET on top of an existing database you had to make manually in SQL with

Management Studio, you will appreciate how clean and simple this process above is - wonderful is my simple

comment on it.

I for one will NOT go back to the old ways, so C# and a data access layer it will have to be, when I use VN3.

When I use WPF I will use Entity Framework 4 (or later) as this gives more options on class structure.

BUT - as yet unmentioned, one BIG bonus of going to LINQ to SQL (or others similar) is that the choice of data

types, and thence the conversion back and forth from SQL to .NET code, has all been swept away for us !

Brilliant I say - the time I have spent in the past trying to get my data types correct and compatible, and then also

handles NULLs correctly, is HUGE I am sure, and NOT very productive when it comes to solving business problems,

and writing custom apps.

Al in all, LINQ is a Godsend to the poor developer - so go and use it ;-)

Oh! the word 'Finish' in the subsection title - well that is easy, once we have a suitable collection we just bind

it to a UI element. Either in a simple direct way, or using the more complex standard 'pattern' approach of MVVM.

So we see Objects in our GUI displays.

Lets move to the next subsection - see you there .................

PHH - 29th. August 2013.


Data types - .NET and SQL ?

Data types - .NET and SQL ?

 Previous topic Next topic

Data types - .NET and SQL ?

 Previous topic Next topic

This section applies only to LINQ used with collections based on data from Tables in

a SQL database, either a local datafile, or a database attached to a DB Server, or data engine.

So we are talking of LINQ to SQL and LINQ to Entity - for any Microsoft technology, Phone or WPF etc.

If you are not new to SQL and have tried to write .NET coded apps, you will be aware of ADO.NET

and also how tricky it was to get data types on the SQL side to match up with data types on the .NET side,

and make sure they were always fully compatible, null aware and more.

Basically, it was a bit of a nightmare, and quite time consuming to say the least.

And, on top of that we did often get issues with NULLs and how our code/script boundary handled them.

Even when we thought we knew what we were doing ;-)

One bit for Good News :

We can work in .NET data types entirely. Any need to know about the database data types is not now

required - let the system provided do its own thing - I trust Microsoft.

Having said that, we sometimes have to know what our limitations are on the .NET types we can use.

I seem to remember that 'SQLite' with Metro/WinRT has some restrictions - BUT - it was still very easy

and straightforward to use.

Another bit of Good News :

As long as we include the fact in the attribute for our columns, we can set and control the NULL situation

easily, and in an understood way - for the first time ? Newbies to SQL via LINQ will have no problems.

Check this out :-

===========================================================

We need to explore more fully what can be included in our column attribute list - it seems to vary a little

bit from WPF to Phone 8 and 'SQLite' for Metro. But hey! - not a big deal.

Using IntelliSense with my open Phone8 app I can see these options :-

===========================================================================================

I am sure we will get to both 'know and use' most of these as we get more experience with using

them in our projects and apps.

What if we use the Wrong Type ? :

Well, that is the other good thing about LINQ, because we do everything in code then the compiler and

pre-compiler alerts us to any mistakes we may make, before runtime.

These days I use the pre-compiler and IntelliSense to guide me a lot - in the choices I make while in the editor.

Give up some of the personal responsibility and let the designer tools help you out, they know better than

us, I can assure you of that.

Summary :

Whenever you can, use Code First (CF) technology as this reduces to an absolute minimum any issues

related to matching data types, Table to Custom class. This is because the LINQ system for your chosen

technology (SQL or EF4) takes our class property type and creates the suitable table columns as required.

Time to move on, see you in the next section .........................

PHH - 29th. August 2013.


the use of ' var ' - don't be shy !

the use of ' var ' - don't be shy !

 Previous topic Next topic

the use of ' var ' - don't be shy !

 Previous topic Next topic

Okay guys, yet another 'topic heading' which may prove controversial.

Many folks in the News Groups post about the sloppiness of using ' var ' or the Vulcan equivalent

of 'IMPLIED'.

I used to think like them, but don't any more.

I hear what they said, but after reading and copying a whole host of .NET code related to LINQ apps, I

have decided that there is natural place where using ' var ' seems just right to me. So I now use it quite

a bit in my code, but NOT everywhere and its not over-used.

Now I use ' var ' where it feels right, and don't even think of it in other - more normal - places.

My suggestion is that if you take a "stance" on this, it will hinder your progress.

Quite often with LINQ the type is VERY long and will make our code less clean, and more difficult to read.

And anyway, we can always find out the data type by hovering with the mouse pointer in the editor.

Here is a couple of related examples :-

=================================================================================================

============================================================================================================================================

Yes, we get some long tool-tip boxes, but the information is all there if we so want it..

However, the obvious point shown above is that we can simply use two ' var 's on lines 112 and 118, and

know that whatever, we will get a collection of items of type 'StateOftheUS' which is what we used to make the

Table in the first place.

My Suggestion - the Way Ahead :

Quite honestly, I suggest you do as I did, it seems to work well for me now.

Just copy the code from useful learning and training material, and copy the style of coding shown there.

If you look at a lot of my ClickStart eNotes (and this CHM done for DevShare13) you will see what I have

picked up from such sources of information.

And if you MUST explicitly type your variables, then at least use ' var ' and mouse hover to find the exact

type the IntelliSense reports you ought to use.

Good Luck !!

PHH - 29th. August 2013.


no ADO.NET and no DataTables

no ADO.NET and no DataTables

no ADO.NET and no DataTables

 Previous topic Next topic

An interesting observation :

If we search the latest eBooks from well known authors, on Metro/WinRT and Phone 8 app development,

when we search on DataTable we get no hits at all.

In fact the Charels Petzold eBook gave no hits for 'DataTable', 'DataSet' and 'ADO.NET' - all were not found.

I tried DataTable with a couple more good eBooks and failed similarly.

Samples in the SDK for Metro/WinRT show old friends 'missing' its a feel you get after many, many hours!

Conclusion : - modern coding guys do not need ADO.NET and its related classes, within their own coding.

=============================================================================

This is an interesting subsection as it brings good news, even tough some of us may mourn

the passing of some good friends - like the 'DataTable'. I loved him dearly !

Having done a lot of work in the past with ADO.NET and M$ SQL Server, I got very familiar with

the 'DataTable' class in the associated namespace.

The DataTable was somewhat of a keystone, or cornerstone for the ADO.NET technology.

'ADO' stands for "ActiveX Data Objects" and ADO.NET was a different beast (updated) to 'ADO' apparently.

I started with ADO.NET and got very familiar with using DataTable objects, and even binding them to

Data Grids on the GUI surface - brilliant !!! Made life a lot easier.

However, now that we live in a world of LINQ the data comes back to us in collections of custom objects.

Our own business oriented objects, and NOT a system convenient object like a DataTable.

Now that I have seen the benefits of LINQ I will happily see the DataTable put to one side as far as the

developer is concerned. The choice to me only exists in WPF, as the other technologies from M$ that I use

do not support it at a framework level for the developer.

Consequently, I no longer use DataTables, and gave them up well over a year ago.

'DataTables' are dead, long live the collection !

In the modern world of coding for Surface Tablet (WinRT) and Windows Phone 8, we do not see UI controls

like the old WPF DataGrid, and the ones we do have bind to collections superbly.

So now I have my business / custom object collections from start to finish in my code/script solutions.

And any guy who still uses WinForms can't have seen the glory of the data binding in WPF.

The Way Forward - a Strategy :

This small section could just as easily be entitled make life easy for ourselves, as developers and app designers.

Most of us guys will spend much of our waking time worrying about dealing with all the new ideas that come

to us from ICT companies - Microsoft, Google, Apple ... the list goes on.

So it occurred to me, while I was trying to think my way from VO into the world of .NET (a few years back), that if I

found out what would be in vogue, and used extensively tomorrow, then learning that would probably save me a LOT

of time and effort. Then what I did not learn would soon go away, or become old legacy stuff, quite quickly.

By this I mean that the next step from where we are, or have been, is not always what makes best sense in the

good use of our time.

So far my strategy has worked, and I intend to keep applying it.

Don't spend time learning today what will be out of use tomorrow !!

The Developer's Excuse :

I read the News Group postings a lot, and it seems to me that many guys use the excuse to NOT come to terms with

new technology by hiding behind their customers. They say their customers have this old server or Windows o/s an

don't want to move forward, or spend money etc.

Some of this may be true BUT a lot of it is an excuse for not making the effort to learn new things.

My point on all this is that as Professional guys in ICT we ought to be leading our clients and customers. We ought

to be telling them the problems they will be stacking up for themselves by lagging behind.

We all know that old hardware and old software causes everyone problems in the long run, so why not be up-front ?

Just this morning I read in the NG about developer time and effort being wasted trying to get a newish bit of an app

running across a physical server. It turned out that the only problem was with client's use MS Server 2003 R2 - well

good God, that is a full ten years old. Just how things have changed in those years.

In 2003 I had not even start VO programming - that tells you how long ago that was.

Good Pros in our game will go and tell any client or customer - straight - when it is time to move on from their current

kit, and hardware / software solutions.

It took me two full years to get my customers to move from DBFs to SQL Server - but move they did, thank God!

Suggestion - look yourself in the eye the next time you look in the mirror, and ask if you are using your clients as

an excuse to run away from leaning new things ? Ask yourself if you are scared of failure, and like most of us you

may well hear the answer 'YES' !

However, being scared is one think, listening to me when I say a LOT of things have gotten easier is another ;-0)

Take advantage of new 'things' and move forward to enjoy the easy parts.

History - and the Future :

At any one time both Microsoft and us have to live with legacy stuff. Stuff that most possibly M$ would like to

throw into the trash can of past good ideas.

This includes the old programming styles and models, and that not too long ago everything was certainly not

object based. In fact I only really came to objects in my coded apps, in about 2004.

So the consequences of all that history is that it has taken a while to move into objects completely. And by

objects I mean business oriented 'custom' objects.

Even now, while I write, much of our ICT industry has data sources, data provision, and even data layers which

are NOT object based.

ADO.NET is part of our rich history, and LINQ and custom object collections are here today, and certainly part of

our future for a while to come.

WinRT/Metro and Phone 8 have no ADO.NET and WPF can be written in a modern style without its use.

Its obvious that it is time to move on, journey into today, and give up ADO.NET and even SQL at a surface

level, by embracing LINQ with 'LINQ to SQL' and 'LINQ to Entity'.

I wish you luck with your new ventures ;-)

PHH - 30th. August & 4th. September 2013.


source of the possible Collections - 'DataContext'

source of the possible Collections - 'DataContext'

source of the possible Collections - 'DataContext'

 Previous topic Next topic

Whatever technology we are to use with LINQ, which is over and above 'LINQ to Objects', we

need to have a class which provides the 'bridge' between the back-end database and the .NET code.

Often this class is called something similar to 'DataContext' or .dbContext'.

I have used three varieties (or flavours) of this class so far with my LINQ work with WPF, WinRT and

most recently Windows Phone 8.

They all have much in common, from making the connection to the database itself, to allowing object

reading and writing of data to the back-end DB. This class needs to have all the members required to

provide suitable interaction between our .NET code and the data Tables.

When we have a SQL database 'engine' supporting the 'Context' technology we often have a method

which allows us to have direct contact with the SQL engine, by us sending a text query statement 'string'.

This I have done with WPF and 'SQLite' in Metro, the Phone8 version of LINQ to SQL does not support

direct querying - remember it is a local data file, without a server as such.

'DataContext' with "LINQ to SQL" :

[ .. WPF and Phone 8 .. ]

The 'DataContext' class is effectively the main way 'in' for us developer guys to start using a

back-end data source with our LINQ syntax code, in WPF and Phone 8 technologies at this

current moment (August 2013).

Surprisingly it is not as yet available for WinRT / Metro, and I had to use SQLite with ' sqlite-net '.

I have used both and they are easy enough to use and get good results.

'DataContext' with "SQLite " and ' sqlite-net ' :

[ .. WinRT / Metro .. ]

This third party product seems to be the only alternative we developers have to use SQL techniques and

syntax with Metro store app creation.

dbContext - with Entity Framework 4 (and above) :

PHH - 30th. August 2013.


.NET code (C#) - LINQ to Objects

.NET code (C#) - LINQ to Objects

.NET code (C#) - LINQ to Objects

 Previous topic Next topic

We are using "LINQ to Objects" when we are coding a LINQ query and the collection is already in

memory.

The object type for our memory resident collections are usually just List<T> and ObservableCollection<T>.

So we do not need, or have, any 'DataContext' or 'DbContext' object defined.

Here is a good example, simple enough to see and understand quite quickly :-

====================================================================================================================================

If we use IntelliSense to look at the collection used in the 'from' clause we see this :-

============================================================================

And if we do likewise to check out the type of the returned 'query' object we see this :-

======================================================================

All of these collections are memory resident.

Lets move to another subsection to see how this changes for collections made from data sources.

See you in the next subsection .................

PHH - 3rd September 2013.


WPF - LINQ to SQL - Data First

WPF - LINQ to SQL - Data First

WPF - LINQ to SQL - Data First

 Previous topic Next topic

Well over a year ago I had to move an existing app from an existing SQL database based on MSSS 2008

and Vulcan 2, over to a C# app with the same database nigrated to MSSS 2012 (Denali).

The original Vulcan 2 app was based firmly on my STATIC classes to handle the ADO.NET 'stuff' on which

the whole app was based.

I decided to move the whole thing over to LINQ and drop any use of my ADO.NET static classes, which had

been working so well.

Why did I do this, simply because LINQ makes life so much simpler for us developers;-0)

And quite frankly I am VERY GLAD that I did - no going back for me.

So, since the database design (and some logged data too) already existed, I had to use 'Data First' as my

general approach, NOT 'Code First'.

I did not use the technology available to generate the custom / business classes from the data Tables, but

had a go at manually doing this, simply to gain experience and knowledge - and my number of tables was small.

Let move on to see some of what I did ..................

Example from the GroundProbe12 real live data logging application :-

[ .. remember that the 'corner stone' of L2S is the 'DataContext' class .. ]

=======================================================================================================

In the above image it is the early part that we need to concentrate on ... lines 183 - 185.

Like all SQL related technologies, getting the server instance and data file connection set-up right and used

to make a successful connection is easy in theory but tricky in practise ;-)

Below is a screen I used so that using the app across multiple platforms was easier / possible :-

=====================================================================

Once we had a positive test, we could then move on to process data.

First we need to see what the test did at a code level :-

==================================================================================

If all goes well above, then line 46 opens a connection successfully.

The following shows what we see on screen :-

============================================================================================================

Okay then, once we see above that a connection can be made with the connection string we have as a

property, and at our disposal (for our use), we can use this string each time we wish to query the database.

Here is a typical method I used in this rather complex data logging example - check this out :-

==========================================================================================================

Line 1605 creates a 'DataContext' object, with which we can then query the database in a 'L2S' fashion, and

using any one of the many members on offer to us - see below for the full list :-

===========================================================================================================================================

Notice above the entries of 'GetTable', 'SubmitChanges', 'ExecuteQuery' and 'ExecuteCommand' as just

a few, however they are the important ones for my application.

It seems like time to move on - see you in the next subsection ...................

PHH - 31st. August 2013 & 13th. September.


WPF - LINQ to SQL - Code First

WPF - LINQ to SQL - Code First

WPF - LINQ to SQL - Code First

 Previous topic Next topic

Terminology and Acronyms :

'LINQ to SQL' is shortened to "L2S",

database to DB,

'Code First' to "CF"

'Help Viewer 2.0' to "HV2" ...................

===================================

Well guys, I have to say that this seems like one of the best kept secrets going !

By this I mean using 'LINQ to SQL' in a 'code first' (CF) manner. And by CF we mean that

we define our couple of necessary classes in .NET code, and then use members of 'L2S' to

create both the database and the Tables required within that DB, for those classes. Its all

done for us by the 'system'.

If we take a look at the IntelliSense for a 'DataContext' object we see the following members

available for our use :-

[ .. db is our instantiated object of a 'DataContext' class or sub-class .. ]

=======================================

Notice above that we have a member (method) called 'CreateDatabase', so if we have that defined

for our use, then we must be able to make a DB and hence we must be able to make tables too.

That's only sensible !

Since there is not apparently a 'CreateTable' method, we need to define any table structures in our

sub-classed 'DataContext' class - then creating the DB creates all the necessary tables that we

have defined in our own 'DataContext'.

The SDK docs in Help Viewer 2.0 (HV2) have a section called "How to: Dynamically Create a Database".

Although the language is a little obscure it is worth reading what is written at the start of this section.

We can then (later, below) translate it into simpler words and ideas - check this out :-

==========================================================================================================================

This is about the closest I can find anywhere, which is 'text' to say that with L2S we can create a DB with all its required Tables,

from code written first into our .NET solution.

Basically it says that any Table which is to be created needs to be specified in the sub-classed form of the DataContext we

are setting up for use with our new DB.

It also says that we have to use attributes to help with the mapping - of our coded class to the table(s) to be created.

Lets make a start on our own example, BUT, we will use the SDK simple code to get us going, then we can add our own to

start and make the whole thing more interesting.

Starting a new Application :

Open VS 2012 and close any open projects / solutions.

Start a new project using (from the menu bar) File, New, Project .... as shown below :-

==================================================================================================

This will then bring up the dialog screen shown below :-

==========================================================================================================================

Select the template for C# WPF Application, and name it as shown, and check the 'source control'

if you have TFS (Team Foundation Server).

Here is what I get when using my local TFS installation :-

==========================================================

And after clicking OK we see some icons in our SE pane as seen below :-

=================================================

The above small icons mean that we need to 'Check-In' the project for a first time.

We can do that now - see the following image :-

====================================================

And now that is done for the first time, we see a change of small icon shape

to that seen below :-

===================================================

So now that our project is registered and checked in with the 'Source Control' system, we can

move on to the database and LINQ side of things.

'DataContext' - a class to make it all happen :

In many ways the 'DataContext' class (from the 'System.Data.Linq' namespace) is the centre of

all that can be done to both make our DB in SQL and also to send data back and forth afterwards.

The documentation calls it 'an entry point' for the L2S framework.

Here is what the SDK docs have to say in HV2 :-

=====================================================================

And if we now look into the References section of our WPF app, we see a long list of items,

but nor the assembly stated in the above image.

Check out the following details :-

=============================================

So if we are missing the item 'System.Data.Linq' from the References node/section,

then we need to add it manually ourselves.

Here is what my dialog screen looks like :-

=======================================================================================================================================

Make your selection and then click OK to see the following :-

=============================================

Yes, in the above image we see we have our new, and required, reference item.

So now we can add a line (or two) to the head of our code files, which provide a pointer

to the namespace(s) we will use for LINQ - see below :-

=============================================================

In fact we will need a couple more than this, but at least we are on our way, and doing the

right things ;-0)

==============================================================

Although line 16 above make things seem OK now, once we get into using L2S for real, then we

will need a few more namespaces - like those shown below in lines 17 - 20 :-

=========================================================================================

Fine, now that we can point to the necessary namespaces, we can start to access the required classes.

Let us study the simple beginnings of an app seen below - its is straight out of the SDK docs, but will be adapted

and upgraded very soon.

Check out the three basic parts to this - the definitions of custom class and DataContext, and the code to use these :-

========================================================================================================

Yes, the app as copied from the SDK compiles and runs ! Well, now that I have provided the correct namespaces.

After such a simple start, we can use File Explorer to see that in fact we have been 100% successful, probably

without realising it - check below for the new files :-

==========================================================================================================================

Well, you can see that I am working at 10.45 on a Sunday morning ;-0)

Now then, extra to the fact that we have new files made on disk, we need to see if they are fully SQL compatible.

By this I mean that using the Management Studio (MS) software tool we can open them and examine their structure.

The image below shows me in MS trying to 'Attach' the '.mdf' file after locating it :-

=============================================================================================================================

Well, although all looks good above, when we click OK we get a disappointing message box.

However, don't panic, the problem is easily solved - first check the issue / problem, and its message box :-

=================================================================================================

Yep! not much of a positive or helpful message - BUT - simply, we have left open our app after building

and running it - the window is there somewhere on our desktop - go close it first, then try again.

Good Luck this time ;-0))

Moving on a pace ...............

How to get yourself out of development 'bother' :

There will be times when you seem to get things 'locked up' in some way or another. When the app will not

launch and we get messages which don't seem to be right to us - that often happens with SQL app development,

and using MS with attachments and detachments. Sometimes it seems to take the O/S a while to catch up

with the changes we have made at MDF file level.

For the moment we look look at a few ways or strategies to allow us to move forward when apparently 'stuck'.

First we can delete an existing database from our code - check below :-

===============================================================================================

We can improve the above and add some more table filling code so that we can do a thorough test.

Here is some I have used to comment / uncomment lines 46 through 48 to see that the DB is being

recreated each time - it seems to work a-okay :-

======================================================================================

So after deleting the DB from code we can move on ...................

Oh! before we move on to more interesting data related reading and writing etc., lets also say that

if your development code says the DB already exists etc., and you are stuck and flummoxed, then

just change the name of the DB within the connection string.

In the above code you will see that I am on to version '4', and some of this may have been to do with

me using MS and attaching/detaching.

If I now (a different day) look at the File Manager then I can delete all previous files - which I could not

yesterday.

Here is what I now have :-

==========================================================================

And the 'mydvds4.mdf' can be deleted from code and remade time after time. Just changing its name

got me out of a hole while developing, when I just needed to keep on coding.

Examining the Custom classes and the sub-classed 'DataContext' :

When we make a DB from our code and its custom class definitions (CF), we get Tables in our DB

which have the structure defined in our business / custom classes.

Also the tables made are only those which have a corresponding property in the defined sub-classed

'DataContext' code - check this out below :-

===================================================================================

Yes, the above Customer class is a new one, one that was not in the SDK docs sample from M$.

And now you can see what we need to do to get this Table to be made at build and runtime, when

we get our code to Create the database - see below :-

===================================================================================

So in the above code, our sub-classed 'DataContext' (DC) inherits from the base 'DataContext' class and

we make sure on line 73 that this is called.

Here is some development code which calls the newly defined DC class - we should get two Tables.

First examine in detail the code :-

================================================================================================

So if we make sure that the application of ours is closed before we look to using the MS tool, we get

screen output like the following :-

====================================================================================================

Having browsed to find and identify what we wish to attach in the MS shell environment, we see that the

database appears in the tree pane on the LHS (left hand side).

Notice from the following image just how many Tables we now have - see that for Customer ?

===========================================================================

In the above image you will also see that the name of our new Table is 'DVD_Customer' which

is what we defined in our Table attribute - see below for a reminder :-

===================================================

If we expand the tree for the two Tables we see Column names too - check this out :-

=================================================

Also, as you may expect, the Column names come from the 'named' attribute in our DC class.

More on that later, as we shall see how to map a different class property to a table column name.

Now back to potential issues you may get / have.

If we leave a DB attached in our MS environment, and then try to build and run our app, we may well

get output as shown below :-

==========================================================================================================================

We need to use the MS shell to get the DB in focus in the tree view pane, then using a right click

and the context menu, select 'Tasks' and then 'Detach...'.

Check out this following screen image :-

===========================================================================================

Then see that this produces the next image :-

============================================================================================================

And finally, (maybe after a refresh of the Databases section (right click etc.) you

see that the selected DB is missing from the list.

Because of some latency in the File Explorer system, you may need to close MS as well as wait

some time for the apparent 'lock' to clear itself.

Here is the refreshed list on my system :-

===================================================================

If all that messing around works for you then you can run the following type of code with

obvious success - check this out :-

=================================================================================

Now then, with this working as it does for DB creation, save the version information by

'Checking In' the changes using TFS - right click the Project node to get the context menu :-

First see how it looks before saving / check-in :-

===============================================

And now the context menu :-

===========================================

Follow your nose in the dialog screen for Check-In and then after OK-ing you will see this

shown below :-

========================================================

All red ticks to indicate code changes / editing, have gone.

Lets move on a pace or two .................

Going further - 'hard-coding' some data for inserting :

Okay the guys, we are ready to start getting results and quickly too ;-)

Let us now see how to make a collection of Customer objects and then save them (insert) into

our mapped Table called 'DVD_Customer'.

First we will see the short amount of code needed to do the inserting / saving - check this out :-

=============================================================================================

Once we actually have a collection it only takes two lines to save it into the DB itself.

Lines 54 & 55 above make the changes - in this case bring about insertion of new Table rows.

Now we need to see the slightly more voluminous code section for making a STATIC member

to supply a Customer collection - check this out below :-

=============================================================================================

As you can see above, there is nothing startling with this code - quite straightforward really.

Because the member called 'GetBunchOfCustomers' is a static method, we can use it anywhere in

our code to provide a List<T> object, where 'T' is type Customer. List<T> is a collection.

All we now need do to make this all work for us, and update our database, is the following :-

[ .. note line 39 in particular ..]

=================================================================

Okay then, the operation as it stands is unseen and unproven except for a hopeful message box ;-)

What we need at this stage is to use MS and run a query - I will assume you know how to run a basic

query - here is a screen shot of another small test database to give you a clue on how to do this :-

===================================================

I have a suitable screen capture image from when I had our DB attached in MS - here is is below :-

========================================================================================

Note that the data is displayed in a grid type of table view.

And the query that the context menu selection caused is seen next - check this :-

===============================================================================

PLEASE remember, that once you get the hang of what is going on with L2S we will not go near the

database and MS at all, there is no need to with 'Code First'.

Lets make some more progress ...............

'Mapping' within our Table classes :

Okay then folks, we can make databases and tables, but we need to focus a bit more on the mapping between

our classes and the tables themselves.

The mapping from our classes is done by Attributes on Table and Column in particular - for many guys apps, and

for most of the time that is. There are a few others too - check out the SDK docs :-

============================================================================================================

And here is the full list of possible Attributes, even though some are used infrequently by many of us :-

=============================================================

And now time to move on ................

Using more Attributes :

Let is see how we may use these Attributes more, to improve our apps and the possibilities of

what we do when we code 'stuff'.

In the next couple of images we will explore using the Database, Table and Column attribute in a

more demanding way than we have so far.

We will start by establishing some working (or acceptable) syntax - check this out :-

===========================================================================

[ .. I need to find out how to make this work for us !? .. ]

Checkout below how we can name the Columns differently to the property names from which they

are mapped, or derived :-

========================================================================================

And from the above image code compare lines 157, 160, 163, and 166 with the next image

details - that from within the MS 'shell' :-

==========================================================

It has to be said that being able to map 'differently named' columns in the table with properties in

our custom class, probably makes more sense for the 'Data First' approach rather than 'CF'.

Any guy with some experience is using existing or legacy SQL databases knows the bunch of issues

with poorly named Columns in particular, and inconsistencies from table to table with Column names.

Quite often in existing DBs we have columns of similar / identical data with different column names.

Although my sample I am trying out in this section is CF based, I have tried the differently named column

mapping, just to show you that it works as expected.

Lets now run our code again so that we fill up our Table with new row data, those Columns with the different / funny

names :-

===================================================================================================================

What we now need to do is write some code to retrieve the new data from these mapped columns

and see what effect (if any) it has on the data grid output on our XAML GUI surface.

Lets try this now .............

Retrieving Stored Data - tables to objects :

Let us see what the results look like for one 'fill' of the four record method :-

==============================================

And line 46 in the following image produces the results we were looking for - check this :-

===================================================================================================

Now then folks, we need to focus on the code which queries the SQL database and returns a collection

of all the objects possible, from the records in the database table.

This is where we use LINQ for the first time in anger - so to speak.

Line 60 get a retuned collection from the DB, and lines 61 through 64 are LINQ related, to provide a list

collection which can be bound to our DataGrid control - check this out :-

==================================================================================================================

Now then guys, we have set the DataGrid to have its columns auto-generated, so any header name

comes from the bound collection.

Check the XAML script for this seen below, and figure out why we can't see the names like 'DVD_SaleId' :-

============================================================================================

Well, the answer is VERY simple - any column seen in the .NET part of our app is based directly

on a property of the collection item type, so we see the name of the property and not that of the

Table column.

But having changed the names of the columns, by changing the mapping, and then recreating the DB,

has not stopped the app working and has left our data grid on the UI surface unchanged.

Now let us get an overview of our .NET code - two table, a DC class and some initialising code.

Study the next image carefully :-

==========================================================================

We have achieved a lot in this section I feel, and it is probably best to leave things at

this point - just as they are.

Let us move on to the child sub-section on direct querying.

See you there ......................

PHH - 31st. August 2013.


Direct querying (CF & DF) - possible, but is not LINQ

Direct querying (CF & DF) - possible, but is not LINQ

Direct querying (CF & DF) - possible, but is not LINQ

 Previous topic Next topic

Well then folks, we need to discuss an issue, an important issue I feel.

It is possible with the L2S technology to query the SQL database directly, that is when we

are using WPF technology with L2S.

If we look at what the IntelliSense shows us below then we will be in a position to think and

discuss - check this :-

==========================================

Notice that we have three extension method entries above, all starting with 'Execute'.

These effectively allow us a 'straight through' way of sending a query statement to the underlying

database server. We make up a suitable text string, and then send it directly to the DB Server / SQL engine.

The string may be correct or incorrect.

Before we examine how this may be done, and see that it applies to both DF and CF approaches, we

need to discuss that "the LINQ way" is to have any select query made by the .NET code, so the checking

by the compiler is available to us.

The LINQ way is to do as little as possible of direct querying of the underlying DB.

However, there are times when we may have little, to no choice.

Let us us see working examples of 'ExecuteQuery' and 'ExecuteCommand'.

We will first look at the 'command' variety - where in our example we do not expect any returned data.

Study the following thoroughly, and in full detail :-

================================================================================================================

This is some old code, copied over from ADO.NET days, and even with a different .NET programming language.

Vulcan 2 was used originally with the above command code and text string.

Unless we have tried the exact same query string out with the MS tool, we won't know if it is correct. Also once we

have coded our app method, other things may change which could cause the code to fail at a later time.

However, the 'command' situation is one in which we do not seem to have a LINQ standard syntax alternative.

The next example however, does have a LINQ alternative, and therefore it ought to be used.

Lets check this out in detail, see below :-

=====================================================================================================

In the above code, Okay, in some ways it is a bit special since it is a CTE (Common Table Expression)

which was proven to work in ADO.NET - however, it could easily be re-written in LINQ using a couple

of query statements. We have similar examples to this in earlier sections of these eNotes.

Notice how we can specify the Type of object returned by the query - see line numbered 487 above.

Moving on ..................

The Challenge - re-write as a LINQ query !? :

Okay guys, there is no way that you would let me out of this situation - getting it to work with a

LINQ standard syntax query ;-0))

I accept your challenge !

The following would appear to be a suitable alternative, and all parts should be checked by the compiler before runtime.

In fact we have managed to do this in one query statement, instead of a couple which are 'nested'.

I suggest you try to follow this through line by line, it is a good working example :-

=====================================================================================================================

Okay then folks, direct querying with SELECT text strings - ONLY - when we have no alternative.

So hone your skills with writing LINQ standard syntax - it all works if you get some experience.

Time to move on, see you in the next section ..............

PHH - 2nd. September 2013.

Addendum :

L2S with Phone 8 does not allow direct querying so the Extension methods for 'Execute' are missing.


working script and code

working script and code

working script and code

 Previous topic Next topic

===========================================================================================
<Window x:Class="DS13_LSQ_CodeFirst.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock HorizontalAlignment="Left" Height="87" Margin="10,10,0,0"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"
Name="tblkMessage" Width="285"/>

<DataGrid GridLinesVisibility="All" ColumnWidth="Auto"
AlternatingRowBackground="AliceBlue" AlternationCount="2"
HeadersVisibility="All" ItemsSource="{Binding }"
HorizontalAlignment="Left" Margin="10,116,0,0"
VerticalAlignment="Top" Height="157"
Name="dgL2QcodeFirst" Width="285"
AutoGenerateColumns="True" />

</Grid>
</Window>

===========================================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//-----------------------------------
//----- added for LINQ -----
using System.Data.SqlClient;
using System.Data.Linq.Mapping; //----- needed for Table & Column .....
using System.Data.Linq;
using System.Data.Sql;
//==================================
using System.Collections;

namespace DS13_LSQ_CodeFirst
{
public partial class MainWindow : Window
{
private string cConnect = @"c:\Users\mydvds4.mdf";
//private string cConnect = @"c:\Users\";

public MainWindow()
{
InitializeComponent();
this.Initialise();
}

public void Initialise()
{
this.tblkMessage.Text = "information will be displayed ...";
try
{
MyDVDs db = new MyDVDs(this.cConnect);
if (db.DatabaseExists())
{ db.DeleteDatabase(); }
//-----------------------------------------------
this.CreateDatabase2();
this.FillTableWithBunchCustomers();
this.FillTableWithBunchCustomers();
this.GetBackCustomers();
}
catch (SystemException oEX)
{
this.tblkMessage.Text = oEX.Message;
}
}
//-------------------------------------------
public void GetBackCustomers()
{
MyDVDs db = new MyDVDs(this.cConnect);
if (db.DatabaseExists())
{
Table<Customer> OurCustomers = db.GetTable<Customer>();
var query =
from c in OurCustomers
select c;
var aList = query.ToList();
this.dgL2QcodeFirst.DataContext = aList;

this.tblkMessage.Text = "Object count :- "+aList.Count.ToString();
}
}

//-------------------------------------------
public void FillTableWithBunchCustomers()
{
MyDVDs db = new MyDVDs(this.cConnect);
if (db.DatabaseExists())
{
Table<Customer> OurCustomers = db.GetTable<Customer>();
OurCustomers.InsertAllOnSubmit(Customer.GetBunchOfCustomers());
db.SubmitChanges();
}
}

//-------------------------------------------
public void CreateDatabase2()
{
MyDVDs db = new MyDVDs(this.cConnect);
if (db.DatabaseExists())
{
string cMessage = "Deleting old database...\n";
cMessage += "now we have TWO tables ...";
this.tblkMessage.Text = cMessage;
db.DeleteDatabase();
}
db.CreateDatabase();
this.tblkMessage.Text = "database made / re-made ....";
}

//public void CreateDatabase()
//{
// MyDVDs db = new MyDVDs("c:\\Users\\mydvds.mdf");
// //MyDVDs db = new MyDVDs(@"c:\Users\mydvds.mdf");
// db.CreateDatabase();
//}
}
//=========================================================

[Database(Name="OurDBname")]
public class MyDVDs : DataContext
{
public Table<DVD> DVDs;
public Table<Customer> myCustomers;
public Table<Sale> ourDVDsales;
public MyDVDs(string connection) : base(connection) { }
}
//=========================================================

[Table(Name = "DVDTable")]
public class DVD
{
[Column(IsPrimaryKey = true)]
public string Title;
[Column]
public string Rating;
}
//=========================================================

[Table(Name = "DVD_Customer")]
public class Customer
{
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int CustID { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Address { get; set; }

public Customer() { }

public Customer(string cN, string cA)
{
this.Name = cN;
this.Address = cA;
}
//-------------------------------------------------------------
public static List<Customer> GetBunchOfCustomers()
{
List<Customer> aList = new List<Customer>();
aList.Add(new Customer("James Bolam","Sunderland, N.E."));
aList.Add(new Customer("Mary Malone","New York, USA"));
aList.Add(new Customer("Dan Logan","Romania, Europe"));
aList.Add(new Customer("Paul Piko","Australia"));
return aList;
}
}
//=========================================================

[Table(Name = "DVD_Sale")]
public class Sale
{
[Column(Name = "DVD_SaleId",IsPrimaryKey = true, IsDbGenerated = true)]
public int SaleID { get; set; }

[Column(Name = "DVD_SalesPerson", CanBeNull=false)]
public string SalesPerson{ get; set; }

[Column(Name = "DVD_SaleWhenMade", CanBeNull = false)]
public DateTime DateMade { get; set; }

public Sale() { }

public Sale(string cSP, DateTime dtWM)
{
this.SalesPerson = cSP;
this.DateMade = dtWM;
}
}

}
===========================================================================================
public static Object[] DuplicateStamps_DumpSet()
{
Object[] oResult = new Object[] { };
string cDB = myGlobals.cDBfilePath;
DataContext db = new DataContext(SQLgeneralAccess.GetConnectionStringGP12());
try
{
Table<DumpSetHeaderPlusX> aDSHPXs = db.GetTable<DumpSetHeaderPlusX>();
var query =
from d in aDSHPXs
group d by new { t = d.Timestamp } into p
where p.Count() > 1 //----- 'HAVING' -----
select new { TimeStamp = p.Key.t };

Object[] aDups = query.ToArray();
oResult = aDups;
int nFound = oResult.Length;
MessageBox.Show("Number of 'Dup' objects is :- " + nFound.ToString(), "Duplicates (HAVING) :");
//--------------------------------------------------------------
string cNum = nFound.ToString();
MessageBox.Show("Number found is :- " + cNum, "Two Queries :");
Int32 nNum = Convert.ToInt32(cNum);
}
catch (SqlException oSEX)
{
MessageBox.Show(oSEX.Message,"my 'Dups Array' error :");
}
return oResult;
}

===========================================================================================

public static Boolean DropTempSQLtableOld()
{
Boolean lResult = false;
string cDB = SQLgeneralAccess.GetDbFilenameGP12();

//----- was [C:\USERS\GROUNDPROBE08.MDF] -----
string CRLF = "\r\n";

//----- Table name is 'DataDumpInOld' -----
//----- it is made by the query Script, structure and all !! -----
string cScript = "";
cScript += @"USE [" + cDB + "]" + CRLF;
//GO ----- belongs to Management Studio ! -----
cScript += "IF EXISTS (SELECT * FROM sys.objects" + CRLF;
cScript += "WHERE object_id = OBJECT_ID(N'[dbo].[DataDumpInOld]') AND type in (N'U'))" + CRLF;
cScript += "BEGIN" + CRLF;
cScript += "DROP TABLE [dbo].[DataDumpInOld]" + CRLF;
cScript += "select 'Our DUMP Table - [DataDumpInOld] - was found and DROPPED !!'" + CRLF;
cScript += "END; " + CRLF;
//go ----- belongs to Management Studio ! -----
//==========================================================================
try
{
DataContext db = new DataContext(SQLgeneralAccess.GetConnectionStringGP12());
db.ExecuteCommand(cScript);
//MessageBox.Show("Query to 'DROP' has been done .... SUCCESS !? ", "After DDIO drop :");
lResult = true;
}
catch (SqlException oSEX)
{
MessageBox.Show(oSEX.Message, "my ERROR drop DDIO :");
}
return lResult;
}
===========================================================================================
PHH - 2nd. September 2013.


Metro/WinRT and SQLite

Metro/WinRT and SQLite

Metro/WinRT and SQLite

 Previous topic Next topic

Well guys, for some reason I can't determine at the moment, Microsoft have not made SQL available

to developers on the WinRT platform (Metro).

No 'LINQ to SQL' (L2S) as in Windows Phone 8.

So until they come up with their offering, we will have to make do with the 'SQLite' and wrapper called

' sqlite-net ' - which gives it some LINQ capability, even if it is quite 'small'.

I have to tell you from the outset that although 'SQLite' is mature and works well, it presents us developer

guys with an 'old fashioned' approach, and one from which we have moved on, in LINQ with other M$

technologies.

Ideally, any SQL software tool we use to support our apps, we would like to be able to use the full LINQ syntax,

and approach, as we can for LINQ to SQL on the Phone 8 and WPF platforms.

Although I have tried my best to get SQLite to 'do LINQ' I have found it really limiting.

However, as a SQL database solution for Metro it does work okay.

You are probably wondering what I mean by all this - well I will explain a little bit at a time as we move

through this subsection.

Let us start with seeing how we can open a connection, and either create or just use a database.

Once we have a database (DB) we can then add Tables as we wish - YES ! - it is different to 'L2S'.

Let us examine the code at the head of my code file for a working test app., we are to make a Table of the

States in the USA.

First lets see line 27 and the 65, which set a suitable connection for a database - check this out :-

=============================================================================

And now the 'OpenMake_DB' on line 39, and then 62 :-

==================================================================

Its time for us to see how to create a DB, it it does not already exist.

Opening the code for 'OpenMake_DB' we see this :-

====================================================================================================

The above is simple, if we have a DB of the required name it opens it, if not it creates one.

So we now have a property for our connection to the DB, as well as having supplied it a suitable value.

While we are talking and thinking about connections we ought to use 'IntelliSense' to see just which members

we have available to us on the 'conn' object - or 'SQLiteAsyncConnection' class.

Check out thoroughly the following image detail :-

===========================================================================================================

Yep! for this sort of thing this is quite a small number of members or extension methods.

What we do notice however is that we can make tables (which we could not with L2S) and we can also

send query strings for 'execution' which we could not with L2S in Phone 8.

So instead of having a DataContext to define which tables we need created, we simply add them one by one

as we require them.

We can now see some .NET code which makes a new Table. Below we are to make one called 'StatesOftheUS',

and so we need to study this carefully :-

===================================================================================

In the above image we see that we have to use an asynchronous coding style / approach. This is true for both

Phone and Tablet - any external file access has to be asynchronous - no choice for us !

On line 82 above, the 'InsertAllAsync' method uses a typed list of objects, and that is therefore sufficient

to let the system know which Table it is that we which to insert into. Quite easy and simple.

Now then, lets try to use some simple LINQ standard syntax on our collection fro the SQLite wrapper.

If we try the simplest of queries we get an error some some reason - see below :-

==================================================================================================

And the compiler errors are seen in the following image :-

==========================================================================================================

All we seem to have to do to correct matters, is to add one or both of the lines with a 'where' clause or a 'orderby'

clause.

Then the code compiles and runs. here is one example :-

================================================================================================================

And here another :-

==========================================================================================================

And finally with both clauses - it looks like this, no compiler issues it would seem :-

===========================================================================================================

And just so you know the 'stance' I am taking, this has been the most difficult of all the various 'LINQ to X'

technologies to get standard LINQ syntax to work for me.

For this reason I now often make life simple for myself, and get back the Table collection and then use LINQ to

Objects (L2O) to do the rest of the collection processing.

Study the following image code, to illustrate what I am talking about :-

[ .. lines numbered 144 through 155 are 'L2O' based and should work as all C# .. ]

=================================================================================================

And now we will see a second example, where we return from a 'LINQ to SQLite' query, a collection

of objects of type 'StatesOftheUS' - here is how we make a List :-

=====================================================================================

We had better finish here, as the topic of the eNotes section is about LINQ and not SQLite itself.

I have put plenty of information on SQLite into my eNote called 'ClickStartMETRO' so if you

wish to know more than go and visit my website.

See you in the next subsection .................

PHH - 31st. August & 13th. September 2013.


Windows Phone 8 - LINQ to SQL - Code First

Windows Phone 8 - LINQ to SQL - Code First

Windows Phone 8 - LINQ to SQL - Code First

 Previous topic Next topic

If we understand about L2S with WPF then we can quickly get a feel for what L2S is all about

for Windows Phone 8.

In the Phone 8 scenario / situation, we do not have a powerful database engine working on our database.

However, like with WPF we do have a 'DataContext' class to use for our collections for LINQ querying.

If we look at the possible extension methods to this Phone 8 DataContect class we see the following :-

===================================================================================================================

This is a reduced set compared to WPF technology, and the obvious missing extensions are those

with 'Execute' in their names.

If we do not have the SQL Server, or database engine, then we can't send queries through text statements

to tell it to drop and create tables, views, or other DB objects.

We have to make all our tables in one go via the DataContext class and one 'CreateDatabase' method call.

This still leaves us with plenty of SQL 'power' and flexibility to do lots of useful 'things'.

There is another issue we need to address (or think about) when we deal with Phone 8 and SQL data, and

that is the 'Sandbox'.

Because of the security restrictions for file access in Phone 8 it is most likely that developers will use a

Code First (CF) approach, and build the SQL databases 'in situ'. And even populate them from coded

methods when this is appropriate - as in not huge amounts of data.

We may look at other options later, if we have time.

Lets move on, and see a working example of code which creates a database.

Notice that the DataContext class used is a sub-class of our own making called 'OurDataContext'.

For CF in WPF and Phone 8 we need to sub-class the DC base class so that we can add our Table

properties - so that these Tables get created in our DB.

Check the following code to get a feel for what is going on :-

===============================================================================================

In the above image we see at line 84 an instantiation of the 'OurDataContext' class - we need now to

examine closely what we have in our class definition - check this out :-

========================================================================================

As you can see, at the moment we have only one Table property defined, so our DB will

consist simply of one Table with a name of 'StatesOftheUS'.

Unfortunately, we can't use Management Studio (MS) to see this - because of the Sandbox security

restrictions - so we are working 'blind'.

The class used for the Table creation is the following one - check it out :-

================================================================================================

So that you can more easily see the 'shape' of the class, I have hidden a bunch of properties, but they

are all visible in the next image :-

===================================================================

Notice that we have not mapped the Column 'name' to anything different to the property name.

Since we are doing CF it would not make a whole lot of sense doing that ;-0)

Likewise the Table name - it just takes the default value of the name of the class - which once

again makes a lot of sense under the circumstances.

So then, lets see some LINQ code in Phone 8 to retrieve some already stored data values :-

======================================================================================

And by now the above code should be meaningful to you, and make sense.

Time to move on ...............

See you in the next sub-section when we sort out Entity Framework 4 and above.

PHH - 31st. August 2013.


Windows Phone 8 - LINQ to Entity

Windows Phone 8 - LINQ to Entity

Windows Phone 8 - LINQ to Entity

 Previous topic Next topic

Personally, I have not had time as yet to try out any test apps. However, it is important to let you know that

EF appears to be available to us in Phone 8 development.

Below are a few useful links and snippets :-

http://mobile.dzone.com/articles/using-entity-framework-create

======================================================================================================

http://mobile.dzone.com/articles/using-entity-framework-create-2

====================================================================================================================

http://visualstudiogallery.msdn.microsoft.com/df3541c3-d833-4b65-b942-989e7ec74c87/

============================================================================================

I will follow this up after the DEevShare13 event is concluded.

PHH - 8th. September 2013.


WPF - Entity Framework 4 (and above)

WPF - Entity Framework 4 (and above)

 Previous topic Next topic

WPF - Entity Framework 4 (and above)

 Previous topic Next topic

Sample - 'Olympics2012' :

While explaining about EF4 and the 'DbContext' class, I will use a working app which has data from

the London Olympics in 2012.

I actually made the database in the Code First (CF) way, and it now looks like the following, when viewed

using Management Studio - check out the eight Tables :-

=========================================

Okay, that looks pretty straightforward, now lets see what our sub-classed 'DbContext' class looks like.

In the code shown below we see our own class defined, which inherits from the base 'DbContext' class.

Study this carefully :-

===========================================================================================

As you can see we have eight Table properties, which is to be expected if we are to make 8 Tables

at the time of creating the database (DB).

Notice that our DbContext subclass is called 'OlympicsContext'.

Below we will see some code which creates the DB if one does not already exist :-

====================================================================================================================

Lines 83 and 84 do some important things - particularly the seeding (or initial population) of

the Tables needing data.

There are different options for creation and seeding, but we are not going into those details here.

What we do need to look at in detail is how we use the DbContext subclass to provide a collection

for the rest of our LINQ code - check this out below :-

======================================================================================================================

Line 168 is the crucial one, where we point at the collection based on the 'Nations' table in the DB

referred to in our 'OlympicsContext' class.

The above code is simply checking to see it a specified 'NationName' is to be found in the Nations table.

Before we leave this subsection lets just look at a few related chunks of code.

Below is one of the Table classes - namely that for 'Athlete'. Check it out :-

=================================================================

You might notice in the above code that we have an absence of Attributes - both Table and Column.

Well, as you may expect with EF4 there is another possible layer between the Table and the Custom class.

Another possible layer between stored data and the business class in our code.

We can specify lots of things about our new Table to be, or existing Table, by adding a 'Configuration'.

Study the code below which shows that 'EntityTypeConfiguration' defined for the Athlete class/Table :-

==================================================================================

Notice that we are setting values for things that were previously in the Column, and Table attributes.

Also notice that we can have multiple entries for one object property, where we set more than one Table

column attribute value. Check out 'LastName' where we specify both that it can't be NULL as well as a

maximum length for the data field.

And as you can see from the next image we have one for each Table / custom class pairing :-

=============================================================================================

For some reason I can't remember, we have one more Configuration than we have Tables - or so it

would appear to me coming back to this 12 months down the line after I coded the app.

Lets move on and see how to populate our Tables - (or seed some initial values ) .....................

Finally - Seeding some Data Values :

If we examine the static method called 'CreateAddSeedOlympics' we can see how this then uses

a heap of other static methods to pre-populate out Tables at the point that we create the database.

Lets check out this method as see below :-

=====================================================================================

And now if we look in detail at only one of these above, we see for 'SeedEventsAthletes' we

have the following code details :-

=================================================================================================================

And that is about it for the quick story of an EF4 app design 'shape' or structure.

Remember the point of all this was to show that the 'DbContext' was fundamental class for Entity Framework

application coding.

Lets move on and learn some different, just for a change ;-0)

PHH - 31st. August 2013.


Custom classes with Collections

Custom classes with Collections

Custom classes with Collections

 Previous topic Next topic

Now then guys, just a short subsection, BUT, a very important one !

One big difference between LINQ to SQL and Entity Framework 4 (and higher) is that we can have

more than just a simple mapping of Table to Custom object, with basic data types mapped property

to column.

We can in fact have a property of our business class (or custom class) be a collection type. I will

explain this with aid of a working bit of sample code.

In the next image we see the 'Sport' class and one of its properties is a 'Venue' collection.

For example, the sport of Athletics can have more than one venue and so we need a suitably named

property - in this case 'Venues' - which is a collection of 'Venue' objects.

This class is simple enough for you to be easily able to see what is going on - check this :-

===============================================================

This has the effect of allowing us to access more than one data Table in the SQL database, when

we make our LINQ queries.

Note that in the above code we have to use the Constructor to define our 'Venues' collection property.

Here is a further example, one where an Athlete can have more than one entry - so a guy can run in

the 100m and the 200m.

The multiple entries facility is particularly useful in the swimming, where swimmers VERY often have

many event entries.

Once again we see below that our code needs to define the 'Entires' property within the Constructor.

==========================================================================

I think the above information is quite clear to follow and read.

And so we have one thing left to do, and that is see how we construct a LINQ query so that we

get back details in the collection property of a class type being used for the body of the LINQ query.

It will all make good sense if we see a working example - check this out :-

===================================================================================

It seems obvious that code line 510 shown above would indicate that we have an option to retrieve data

belonging to a collection property of the main class type.

If as seen above we use the 'Include' extension method, we can retrieve entry data from the Entry table

for each of the Athletes returned by the query.

I would imagine that if we do NOT use the extension method in this way - but miss it off - then we will

get Athlete objects returned but with empty property collections for 'Entries'.

This is pretty straightforward to read, do, and understand ;-)

Lets move on - see you in the next section ......................

PHH - 3rd. September 2013.


a Descriptive / Declarative way of dealing with data

a Descriptive / Declarative way of dealing with data

a Descriptive / Declarative way of dealing with data

 Previous topic Next topic

Although this subsection is almost last, it really ought to be first !

The reason I have left it late is because I thought you guys would think of it as having little to no

value - in your understanding of things 'coding'.

Because of my past, I have been thinking of the declarative approach since the early 80's, when

I had a few years writing PROLOG programs. It was a mind opening experience, one which I enjoyed.

Since those early days I have been trying to reduce my reliance of the alternative and OLD approach

which is called 'Procedural' - and usually involves many loops of FOR, WHILE and REPEAT nature.

Unfortunately, the procedural coding style / approach comes about because it is close to how computers

and 'chips' or processors actually work. And when memory was small, chips slow and primitive, then coding

in a procedural style was inevitable I suppose.

It just takes a lot to knock it out of most guys heads.

The procedural approach is based on repetition, and using loops, and repeatedly applying or testing logical

conditions. A lot to do with how the computer works, but like to do with describing a solution to a business

problem.

The descriptive or declarative approach is VERY much more like the real life situation, and a least one 'layer'

above the computer processor, moving data in and out of accumulators, and just how the computer operates.

Whatever examples we use they are bound to be a little subjective, so you will need to study the ones I give below

and not be too critical - try to get the gist of it all ;-)

Here is an elegant solution to finding the extra properties in a sub-class, over the base class properties.

Check this image out VERY thoroughly, particularly line 85 which does all the work for us :-

================================================================================================================

As you can see above, it is a one liner and does find the correct two 'Table' properties.

So effectively we are comparing the lines 85 and 90 shown below, with those required in

an alternative approach.

Here is what we need to compare with the procedural code in an image shown further down the

page - first the elegance :-

=============================================================================

And now we will code things as I have often done in the past - nested loops and condition

checking etc. ..........

Here is the worst of "where we are coming from" - check this out below :-

=============================================================================

Needless to say I had a few attempts at getting the above procedural code correct ;-0)

And looking at the above image, it is hardly readable, clear, or intuitive - to see what is going on.

However, the use of the 'foreach' construct starts to make things a little clearer, even if it is still procedural.

Check this out :-

============================================================================

My advice is drop the use of loops (and 'FOR' loops in particular) whenever and wherever you possibly can.

'foreach' is a good improvement - BUT - I think there are times that we all use 'foreach' loops when in fact

we could code in a more descriptive way.

Certainly set algebra is something to try and embrace to the full, as it cuts out a lot of procedural 'stuff'.

This is a BIG topic, but one we can't spend any more time exploring here.

I just wish you to get the general idea that with LINQ and with collections, and extension methods for

operators which allow us to use 'set algebra' we can start to code BETTER !

Time to move on ..................... see you in the next subsection ....................

PHH - 13th. September 2013.


the use of ' foreach '

the use of ' foreach '

the use of ' foreach '

 Previous topic Next topic

Note that this can be particularly helpful when we have a Vulcan main (and calling) module which is using

a class library based on C# and LINQ technology.

Since we have not got LINQ syntax available in VN3 for our coding, there will be more times that we need

to cycle though our collections to test items and their properties.

=============================================================================

Okay you folk who just love the FOR statement, and LOOPing into oblivion in the past.

When we deal with collections not everything can be done in a declarative of descriptive way.

Sometimes we need to apply a bit of procedural coding approach - but even then the new

world of collections make our lives as developers just that bit easier.

It is the FOREACH code structure to which we turn.

In the following image we see the 'foreach' structure in use - from a very recent example I did

for another part of these eNotes.

Check this out carefully :-

=======================================================================

Above we need to take each item in the the collection and add it into a newly made (and growing) list.

So often you see ' i ' being used to represent 'item', and ' var ' is also commonly used in the 'input', since

it always works.

We probably need to study a few lines previous to the 'foreach' so that we can see just where our collection

has come from.

Here is an image to show us where the 'myCVS' collection object came from :-

==============================================================================

FOREACH is one of those things that you just use when you have to, one of those things that

you pick up by reading other code and copying and adapting.

I have to say I don't use it a lot, but there are times (like that above) when we can't live without it ;-)

Summary :

If we are going to use collections then we will need to use FOREACH sometime in our coding.

Use ' var ' with FOREACH as it makes life easier - AND - keeps the code cleaner and simpler to read.

See you in the next section .....................

PHH - 30th. August 2013.


Metro / Modern app coding

Metro / Modern app coding

Metro / Modern app coding

 Previous topic Next topic

*** At first I thought this was very, VERY, different - but after some research and development work I

found it quite similar in many ways to the world I had come from in WPF and .NET 4.5 coding.

There are few new things to get used to, and a few old things missing (thank God!).

Most of the apparent 'newness' is in the visual impact that WinRT has on most folks.

Under the hood there are a LOT of similarities.

===========================================================================

Much of our 'gained' knowledge, and many of our existing skills, gained with work In WPF technology

and modern .NET coding, can be transferred over to our work in Metro / WinRT.

Yes, there are a few new aspects which we need to get to grips with, but these generally arise from the

fact that Microsoft has addressed issues in the modern real world, and left behind 'stuff' which is obviously

now just out of date.

So all GUI is based on XAML and its mark-up approach, no WinForms, and that is also true for Phone 8.

However, to those who have been in .NET development for some time, this does NOT come as any surprise,

and many of the sensible guys have been creating new desktop app code with WPF for many years now.

*** NOTE *** Make sure you look through the PowerPoint Presentation slide set on 'Metro / WinRT'.

It covers all of the 'bare-bones' sections shown here.

PHH - 26th. June 2013.


the Similarities and the Differences

the Similarities and the Differences

the Similarities and the Differences

 Previous topic Next topic

PHH - 12th. September 2013.


Getting our minds right first !

Getting our minds right first !

 Previous topic Next topic

Getting our minds right first !

 Previous topic Next topic

PHH - 26th. June 2013.


needing a Developer Licence

needing a Developer Licence

needing a Developer Licence

 Previous topic Next topic

PHH - 26th. June 2013.


XAML for the UI description

XAML for the UI description

XAML for the UI description

 Previous topic Next topic

This is certainly one of the bits of good news as far as Metro and WinRT is concerned.

The mature mark-up script of XAML is used in both the Surface Tablet and Windows Phone 8

operating systems.

Although 'WinForms' hangs on in the desktop APIs, it is not present in those for Tablet and Phone.

"Thank God ! " I hear a few guys sigh - not that it has anything to do with WinForms, but a LOT to do

with making developers come to terms with change, and moving on their skill set into today, never

mind tomorrow ;-0)

PHH - 12th. September 2013.


using SQLite with WinRT

using SQLite with WinRT

using SQLite with WinRT

 Previous topic Next topic

PHH - 26th. June 2013.


LINQ for RAM collections and ' sqlite-net '

LINQ for RAM collections and ' sqlite-net '

LINQ for RAM collections and ' sqlite-net '

 Previous topic Next topic

PHH - 26th. June 2013.


the 'Sandbox' and how to use it

the 'Sandbox' and how to use it

the 'Sandbox' and how to use it

 Previous topic Next topic

PHH - 26th. June 2013.


Asynchronous access to external files

Asynchronous access to external files

Asynchronous access to external files

 Previous topic Next topic

Enter topic text here.


MVVM - 'Prism' and 'MVVM Light' - a pattern !

MVVM - 'Prism' and 'MVVM Light' - a pattern !

 Previous topic Next topic

MVVM - 'Prism' and 'MVVM Light' - a pattern !

 Previous topic Next topic

PHH - 26th. June 2013.


Touch, full screens, Popus, App Bars, and Snap Views

Touch, full screens, Popus, App Bars, and Snap Views

Touch, full screens, Popus, App Bars, and Snap Views

 Previous topic Next topic

PHH - 26th. June 2013.


the Thread Pool and Parallel Programming

the Thread Pool and Parallel Programming

the Thread Pool and Parallel Programming

 Previous topic Next topic

PHH - 26th. June 2013.


SQLite - with Metro and using LINQ

SQLite - with Metro and using LINQ

SQLite - with Metro and using LINQ

 Previous topic Next topic

===========================================================================================================================

http://msdn.microsoft.com/en-us/magazine/dn385713.aspx

========================================================================================================================================

========================================================================================================================

PHH - 11th. September 2013.


What is SQLite ?

What is SQLite ?

 Previous topic Next topic

What is SQLite ?

 Previous topic Next topic

Enter topic text here.


accessing 'SQLite' via the ' sqlite-net ' Framework

accessing 'SQLite' via the ' sqlite-net ' Framework

accessing 'SQLite' via the ' sqlite-net ' Framework

 Previous topic Next topic

PHH - 26th. June 2013.


data for Metro

data for Metro

data for Metro

 Previous topic Next topic

PHH - 26th. June 2013.


the Database is one file within the 'Sandbox'

the Database is one file within the 'Sandbox'

the Database is one file within the 'Sandbox'

 Previous topic Next topic

PHH - 26th. June 2013.


easy to use - Tables made from 'code first' Classes

easy to use - Tables made from 'code first' Classes

easy to use - Tables made from 'code first' Classes

 Previous topic Next topic

PHH - 26th. June 2013.


making LINQ work while using ' sqlite-net '

making LINQ work while using ' sqlite-net '

making LINQ work while using ' sqlite-net '

 Previous topic Next topic

PHH - 26th. June 2013.


performance of 'SQLite' - how far can we push ?

performance of 'SQLite' - how far can we push ?

 Previous topic Next topic

performance of 'SQLite' - how far can we push ?

 Previous topic Next topic

PHH - 26th. June 2013.


where else is 'SQLite' used ?

where else is 'SQLite' used ?

 Previous topic Next topic

where else is 'SQLite' used ?

 Previous topic Next topic

PHH - 26th. June 2013.


Asynchronus coding in Metro, and the Thread Pool

Asynchronus coding in Metro, and the Thread Pool

Asynchronus coding in Metro, and the Thread Pool

 Previous topic Next topic

PHH - 26th. June 2013.


NOT a design nicety - a fundamental requirement

NOT a design nicety - a fundamental requirement

NOT a design nicety - a fundamental requirement

 Previous topic Next topic

PHH - 26th. June 2013.


MVVM is a choice - asynchronous coding is a 'Must Do'.

MVVM is a choice - asynchronous coding is a 'Must Do'.

 Previous topic Next topic

MVVM is a choice - asynchronous coding is a 'Must Do'.

 Previous topic Next topic

PHH - 26th. June 2013.


Tablet app design versus Desktop app design

Tablet app design versus Desktop app design

Tablet app design versus Desktop app design

 Previous topic Next topic

PHH - 26th. June 2013.


the Main UI Thread is 'King' - don't stop it !!

the Main UI Thread is 'King' - don't stop it !!

 Previous topic Next topic

the Main UI Thread is 'King' - don't stop it !!

 Previous topic Next topic

PHH - 26th. June 2013.


side-lining time consuming tasks and the Thread Pool

side-lining time consuming tasks and the Thread Pool

side-lining time consuming tasks and the Thread Pool

 Previous topic Next topic

PHH - 26th. June 2013.


Delays and Timers

Delays and Timers

Delays and Timers

 Previous topic Next topic

PHH - 26th. June 2013.


Message Boxes are 'history' - use Popups instead ?

Message Boxes are 'history' - use Popups instead ?

 Previous topic Next topic

Message Boxes are 'history' - use Popups instead ?

 Previous topic Next topic

PHH - 26th. June 2013.


Consuming WCF Services

Consuming WCF Services

Consuming WCF Services

 Previous topic Next topic

PHH - 4th. August 2013.


Why use WCF services in WinRT ?

Why use WCF services in WinRT ?

 Previous topic Next topic

Why use WCF services in WinRT ?

 Previous topic Next topic

PHH - 4th. August 2013.


Publicly available services - finding them

Publicly available services - finding them

Publicly available services - finding them

 Previous topic Next topic

PHH - 4th. August 2013.


Finding how to use an available service

Finding how to use an available service

Finding how to use an available service

 Previous topic Next topic

PHH - 4th. August 2013.


More complex services - restricted access

More complex services - restricted access

More complex services - restricted access

 Previous topic Next topic

PHH - 4th. August 2013.


Amazon - free access !?

Amazon - free access !?

 Previous topic Next topic

Amazon - free access !?

 Previous topic Next topic

PHH - 4th. August 2013.


Bing Maps - what we can use freely

Bing Maps - what we can use freely

 Previous topic This is the last topic

Bing Maps - what we can use freely

 Previous topic This is the last topic

PHH - 4th. August 2013.