Unlike when you install ruby, when you install python on windows 7 the environment variable is not set. This means that you will have to put the full path of your python installation in to the command line to execute any commands.
To set the path of your python installation in an environment variable follow these steps:
click the start buttong
right click computer and select properties
click "advanced system settings" on the left
the system properties windows should open
make sure the "advanced" tab is selected
click the environment variables button at the bottom of the tab
you will see a window open split in to 2 windows "user and system variables"
click new on the top one (user variables)
click new and enter "Path" as the variable name
"C:\Python26;C:\Python26\DLLs;C:\Python26\Lib;C:\Python26\Lib\lib-tk" (without the quotes) for variable value
switch the path to wherever your python installation is. done, reopen the command prompt and when you type python you should see details of the installed version.
enjoy
Saturday, 11 December 2010
Wednesday, 1 December 2010
SQL Server Management Studio Express Windows 7
If, like me you were searching for an installation of SQL Server Management studio express for windows 7 and got an error along the lines of
"this program is not supported by your operating system"
then this is the installation you need:
http://www.microsoft.com/downloads/en/details.aspx?familyid=5D76230D-580D-4874-8C7D-93491A29DB15&displaylang=en
have fun
Paul
"this program is not supported by your operating system"
then this is the installation you need:
http://www.microsoft.com/downloads/en/details.aspx?familyid=5D76230D-580D-4874-8C7D-93491A29DB15&displaylang=en
have fun
Paul
Monday, 1 November 2010
cannot be performed on a file with a user-mapped section open
So..
I installed TortoiseSVN, when i tried to add a folder to a repository i had created with VisualSVN i kept getting the error:
"cannot be performed on a file with a user-mapped section open"
After googling around i could not find good answers to this, but I did mananged to fix the problem, heres how:
When attempting to add the folder again, I started windows process manager through task manager so that i could watch what tortoiseSVN process were running when the error occured..
I then allowed those through windows firewall and it worked fine. If you have a similar problem I hope that sorts it!
Paul
I installed TortoiseSVN, when i tried to add a folder to a repository i had created with VisualSVN i kept getting the error:
"cannot be performed on a file with a user-mapped section open"
After googling around i could not find good answers to this, but I did mananged to fix the problem, heres how:
When attempting to add the folder again, I started windows process manager through task manager so that i could watch what tortoiseSVN process were running when the error occured..
I then allowed those through windows firewall and it worked fine. If you have a similar problem I hope that sorts it!
Paul
Friday, 1 October 2010
Delete duplicate rows sql server
Hi,
here is a not to common task since you of course should not really end up with duplicate rows in a table, but, knowing that
DELETE FROM table_with_duplicates
"The man who makes no mistakes does not usually make anything. ~Edward Phelps"
if you do end up with duplicates, then here is how to solve the problem.
This SQL will delete the first occurrence of the duplicate entries.
To change it so that it deletes the last entry, you would replace Min with Max.
DELETE FROM table_with_duplicates
WHERE id IN (
SELECT bad_rows.id from table_with_duplicates AS bad_rows
INNER JOIN (
SELECT column_1, column_2, Min(id) AS min_id FROM table_with_duplicates
GROUP BY column_1, column_2
HAVING COUNT (*) > 1
) AS good_rows
ON good_rows.column_1 = bad_rows.column_1
AND good_rows.column_2 = bad_rows.column_2
AND good_rows.min_id <> bad_rows.id
)
Wednesday, 1 September 2010
eee pc bootmgr is missing
ok, so along with a lot of the people that buy an eee pc, i tried to install a different operating system on bringing it home. having only put the bootable usb in once and tried to boot, everytime after, i received the "bootmgr is missing" ctrl alt delete to restart message, and then just went round in circles from there..
having googled forthe remedy for a while, most answers talk about how to make the bootable usb, setting the boot priority in your biosand having a usb stick less than 8gb, i found the solution to be reboot, and keep hitting F9!
this will make the asus recovery tool kick in, and from there you can hit recover and off you go.. once this is done and the operating system is fully installed, you can then install the different operating system..
having googled forthe remedy for a while, most answers talk about how to make the bootable usb, setting the boot priority in your biosand having a usb stick less than 8gb, i found the solution to be reboot, and keep hitting F9!
this will make the asus recovery tool kick in, and from there you can hit recover and off you go.. once this is done and the operating system is fully installed, you can then install the different operating system..
Sunday, 1 August 2010
Learn NHibernate 6 - Advanced querying of Child Collections
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
Traversing a relationship
HQL
where there would normally be a join in sql
SQL[sql]
select * from customer c inner join orders o on c.id = o.customerid where c.firstname = 'steve' and o.orderdate > 6/1/2010
[/sql]
but in hql becasue the relationships are already in the mapping file, there is no need to perform the join.
HQL[sql]
select c from customer c, c.orders.elements o where where c.firstname = 'steve' and o.orderdate > 6/1/2010
<div id="_mcePaste">[/sql]
Criteria[csharp]
ICriteria.CreateCriteria(typeof(Customer))
.Add(Expression.Eq("Firstname", "Steve"))
.CreateCriteria("Orders")
.Add(Expression.Gt("OrderDate", new Datetime.Now)))
.List<Customer>();
[/csharp]
Revisiting Data Access
Each mothod gets its own ISesssion instance
Each method is completely atomic.
recalling the pattern[csharp]
using (_SessionFactory.GetSession())
{
//data access happens here
}
[/csharp]
This means no lazy loading as the session has been disposed of already.
Solution? evolve our data provider to introduce a new abstraction
Having the data acess provider create its own ISession is a violation of SRP/SOC principles.
We should be giving the data provider the ISession
Lets add a parameter to the class' constructor.[csharp]
new NHibernateDataProvider(ISession session) {}
[/csharp]
Now something higher up in our object highrachy will be in control of the session. We can now remove all of the using statements in the individual data access methods GetCustomerByiId etc..
We no longer call GetSession anywhere.
Gettting child objects with HQL[csharp]
private void GetCustomersWithOrdersSince(DateTime orderDate) {
return _session.CreateQuery("select c from customer c, c.Orders.elements o where o.OrderDate > : orderDate").SetDateTime("orderDate", orderDate).List<Customer>();
}
[/csharp]
Gettting child objects with Criteria[csharp]
private void GetCustomersWithOrdersSince(DateTime orderDate) {
return _session.CreateCriteria(typeof(Customer))
.CreateCriteria("Orders")
.Add(Expression.Gt("OrderDate", orderDate))
.List<Customer>();
}
[/csharp]
Distinct in Criteria.
If we put the line of code:[csharp]
.SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer())
[/csharp]
above the List, it will proivide distinct Customer results
Important to understand is that using this distinct transformer in criteria will NOT generate the DISTINCT keyword in the SQL it generates. The HQL does. The transformer will bring back all results and then perform the distinct operation on the client side in NHiberante code. This can be a big performance hit if not understood or used correctly.
If you need to return distinct entities in criteria, add the following line of code to the above query:[csharp]
private void GetCustomersWithOrdersSince(DateTime orderDate) {
var ids = _session.CreateCriteria(typeof(Customer))
.SetProjection(Projections.Distinct(Projections.ProjectionList()
.Add(Projections.Property("CustomerId))))
.CreateCriteria("Orders")
.Add(Expression.Gt("OrderDate", orderDate))
.List<int>();
return _session.CreateCriteria(typeof(Customer))
.Add(Expression.In("CustomerId", ids.ToArray<int>()))
.List<Customer>();
}
[/csharp]
Now the distinct call will be wrapped around hte outside of the original sql generated by the criteria.
Wednesday, 14 July 2010
JQuery for each div with class, do some processing
Here is some JQuery i recently wrote to do some styling changes.
The code basically fires an event on a select box change, and then for every div with the class "localize", if the lang attribute value is not the same as the selection in the option box, it hides that div and makes sure any div where the lang attribute value is the same as the selection is showing.
[javascript]
//get the value of the selection box
var selectedValue = $('#cultureSelector').val();
//for each div with class localize
$('div.localized').each(function()
var selectedValue = $('#cultureSelector').val();
//for each div with class localize
$('div.localized').each(function()
{
//get the value of the lang attr
var langAttrVal = $(this).attr("lang");
if(langAttrVal.indexOf(selectedValue) == -1) {
$(this).attr('style', '');
$(this).addClass('displaynone');
}
else
var langAttrVal = $(this).attr("lang");
if(langAttrVal.indexOf(selectedValue) == -1) {
$(this).attr('style', '');
$(this).addClass('displaynone');
}
else
{
$(this).removeClass('displaynone');
}
});
$(this).removeClass('displaynone');
}
});
[/javascript]
Monday, 12 July 2010
Sunday, 11 July 2010
Linq and Lambda equivalent of SQL Where in
Working with LINQ to SQL, several times I have come across a need of writing a LINQ query equivalent of T-SQL “Where IN” clause.
This is what T-SQL query looks like.
SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax
FROM Customers
WHERE (Country IN ('UK', 'USA', 'Australia'))
How do you write Where IN in LINQ?
Below is the query which can be used for a Linq “WHERE IN” scenario.
Query 1:
string[] countries = new string[] { "UK", "USA", "Australia" };
var customers = from c in context.Customers
where countries.Contains(c.Country)
select c;
Below is the query which can be used for a Lambda “WHERE IN” scenario.
Query 2
string[] countries = new string[] { "UK", "USA", "Australia" };
var customers = context.Customers.Where(c => countries.Contains(c.Country));
This is what T-SQL query looks like.
SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax
FROM Customers
WHERE (Country IN ('UK', 'USA', 'Australia'))
How do you write Where IN in LINQ?
Below is the query which can be used for a Linq “WHERE IN” scenario.
Query 1:
string[] countries = new string[] { "UK", "USA", "Australia" };
var customers = from c in context.Customers
where countries.Contains(c.Country)
select c;
Below is the query which can be used for a Lambda “WHERE IN” scenario.
Query 2
string[] countries = new string[] { "UK", "USA", "Australia" };
var customers = context.Customers.Where(c => countries.Contains(c.Country));
Thursday, 1 July 2010
Decent Computer Security Podcasts
Name: PaulDotCom Security Weekly
Main Subject: anything related to computer security
Format: Casual
Approx. Updates Per Month: 4 to 5
Recent Subjects Covered: mobile malware, hacking ATM machines, tool that allows for hosts to communicate over wireless without being associated, Spamhaus in trouble, Filtering IM for kids, Hacking Web 2.0 Applications with Firefox
Justification: All kinds of good stuff week after week. Highly recommended.
Rss Link: http://pauldotcom.com/podcast/psw.xml
Name: Security Now!
Main Subject: computer security and basic technology concepts
Format: Formal
Approx. Updates Per Month: 4 to 5
Recent Subjects Covered: Parallels, Virtual PC, Application Sandboxes, Blue Pill, Vista's Virgin Stack
Justification: The show still touches on a number of interesting subjects that are worth tuning in for.
Rss Link: http://leoville.tv/podcasts/sn.xml
Name: Binary Revolution Radio
Main Subject: hacking, phreaking, computer security
Format: Casual
Approx. Updates Per Month: 4 to 5
Recent Subjects Covered: Toorcon, IPv6, Covert Channels, Phishing, Tunneling
Justification: Less organized but offers fresh information and interesting discussion each week
Rss Link: http://www.binrev.com/radio/podcast/
Name: PLA Radio
Main Subject: Phreaking
Format: Very Casual
Approx. Updates Per Month: 1 to 2
Recent Subjects Covered: Free Phone Calls, Beige Boxing, Deaf Relay Operators (IP Relay), Social Engineering
Justification: Covers topics related to "phone hacking". While the format is a bit strange, some of the older episodes had me laughing uncontrollably and are worth a listen.
Rss Link: http://www.phonelosers.org/rss.xml
Name: Off The Hook
Main Subject: General technology, phreaking, politics
Format: Semi-formal
Approx. Updates Per Month: 4 to 5
Justification: This show, hosted by Emmanuel Goldstein, has been running since the 80's and has become somewhat legendary in the Hacking and Phreaking communities as it's been there to document the evolution of technology. Definitely worth a listen.
Rss Link: http://www.2600.com/rss.xml
Name: SploitCast
Main Subject: new vulnerabilities, exploit code, security and technology news
Format: Casual
Approx. Updates Per Month: 1 to 4
Recent Subjects Covered: Interview with Johnny Long, ping tunneling, sensitive data on stolen laptops, Zfone, high level ISP hacks, darknets
Justification: They haven't been releasing much lately, but their episodes are usually pretty interesting. I can't find any other podcasts that discuss exploit code in great detail.
Rss Link: http://sploitcast.libsyn.com/rss
Name: Blue Box: The VoIP Security Podcast
Main Subject: VoIP Security, of course
Format: Semi-casual
Approx. Updates Per Month: 3 to 6
Recent Subjects Covered: Skype security news, interviews, VoIP fraud, recent vulnerabilities
Justification: Covers some great VoIP-related security-centered information.
Rss Link: http://feeds.feedburner.com/BlueBox
Name: TWAT Radio
Main Subject: All things technology with a slight security focus
Format: Casual
Approx. Updates Per Month: 10+
Recent Subjects Covered: Newsgroup readers, Wireless attacks for dummies, Eggdrop, Wake On Lan, Network Recon, VPNs, The GIMP, Cygwin
Justification: Covers a great deal of different technology subjects
Rss Link: http://www.twatech.org/wp-feed.php
Name: Basenet Radio
Format: Casual
Approx. Updates Per Month: 2 to 4
Justification: Underground feel, great information
Rss Link: http://www.basenetradio.net/rss2.xml
Name: LugRadio
Main Subject: Linux and Open Source
Format: Casual
Approx. Updates Per Month: 0 to 2
Recent Subjects Covered: the Portland Project, trusted computing, comparison of Linux distributions, Software Freedom Day
Justification: Possibly the most popular Linux-related podcast
Rss Link: http://www.lugradio.org/episodes.rss
Name: The Linux Link Tech Show
Main Subject: The cutting-edge in Linux-based technology
Format: Casual
Approx. Updates Per Month: 4
Recent Subjects Covered: Linux Home Automation, OpenWRT, Asterisk, Debian vs Mozilla, DRM
Justification: Lots of good Linux-related information
Rss Link: http://www.thelinuxlink.net/tllts/tllts.rss
Name: StillSecure, After all these years
Main Subject: All things related to information security with a focus on a business environment
Format: Formal
Approx. Updates Per Month: 2 to 5
Recent Subjects Covered: Interview with Steve Hanna of Juniper Networks, TCG/TNC, The IETF, 3rd party patching
Justification: This podcast includes some great interviews and information centered around enterprise security
Rss Link: http://clickcaster.com/clickcast/rss/1653
Name: Symantec Security Response Podcast
Main Subject: Security updates
Format: Formal
Approx. Updates Per Month: 2 to 4
Justification: A consistent source of security updates - great for people who are charged with defending a network for a living
Rss Link: http://www.symantec.com/content/en/us/about/rss/sr/sr.xml
Name: Network Security Blog
Main Subject: Network Security…
Format: Formal
Approx. Updates Per Month:
Rss Link: http://www.mckeay.net/secure/index.xml
Main Subject: anything related to computer security
Format: Casual
Approx. Updates Per Month: 4 to 5
Recent Subjects Covered: mobile malware, hacking ATM machines, tool that allows for hosts to communicate over wireless without being associated, Spamhaus in trouble, Filtering IM for kids, Hacking Web 2.0 Applications with Firefox
Justification: All kinds of good stuff week after week. Highly recommended.
Rss Link: http://pauldotcom.com/podcast/psw.xml
Name: Security Now!
Main Subject: computer security and basic technology concepts
Format: Formal
Approx. Updates Per Month: 4 to 5
Recent Subjects Covered: Parallels, Virtual PC, Application Sandboxes, Blue Pill, Vista's Virgin Stack
Justification: The show still touches on a number of interesting subjects that are worth tuning in for.
Rss Link: http://leoville.tv/podcasts/sn.xml
Name: Binary Revolution Radio
Main Subject: hacking, phreaking, computer security
Format: Casual
Approx. Updates Per Month: 4 to 5
Recent Subjects Covered: Toorcon, IPv6, Covert Channels, Phishing, Tunneling
Justification: Less organized but offers fresh information and interesting discussion each week
Rss Link: http://www.binrev.com/radio/podcast/
Name: PLA Radio
Main Subject: Phreaking
Format: Very Casual
Approx. Updates Per Month: 1 to 2
Recent Subjects Covered: Free Phone Calls, Beige Boxing, Deaf Relay Operators (IP Relay), Social Engineering
Justification: Covers topics related to "phone hacking". While the format is a bit strange, some of the older episodes had me laughing uncontrollably and are worth a listen.
Rss Link: http://www.phonelosers.org/rss.xml
Name: Off The Hook
Main Subject: General technology, phreaking, politics
Format: Semi-formal
Approx. Updates Per Month: 4 to 5
Justification: This show, hosted by Emmanuel Goldstein, has been running since the 80's and has become somewhat legendary in the Hacking and Phreaking communities as it's been there to document the evolution of technology. Definitely worth a listen.
Rss Link: http://www.2600.com/rss.xml
Name: SploitCast
Main Subject: new vulnerabilities, exploit code, security and technology news
Format: Casual
Approx. Updates Per Month: 1 to 4
Recent Subjects Covered: Interview with Johnny Long, ping tunneling, sensitive data on stolen laptops, Zfone, high level ISP hacks, darknets
Justification: They haven't been releasing much lately, but their episodes are usually pretty interesting. I can't find any other podcasts that discuss exploit code in great detail.
Rss Link: http://sploitcast.libsyn.com/rss
Name: Blue Box: The VoIP Security Podcast
Main Subject: VoIP Security, of course
Format: Semi-casual
Approx. Updates Per Month: 3 to 6
Recent Subjects Covered: Skype security news, interviews, VoIP fraud, recent vulnerabilities
Justification: Covers some great VoIP-related security-centered information.
Rss Link: http://feeds.feedburner.com/BlueBox
Name: TWAT Radio
Main Subject: All things technology with a slight security focus
Format: Casual
Approx. Updates Per Month: 10+
Recent Subjects Covered: Newsgroup readers, Wireless attacks for dummies, Eggdrop, Wake On Lan, Network Recon, VPNs, The GIMP, Cygwin
Justification: Covers a great deal of different technology subjects
Rss Link: http://www.twatech.org/wp-feed.php
Name: Basenet Radio
Format: Casual
Approx. Updates Per Month: 2 to 4
Justification: Underground feel, great information
Rss Link: http://www.basenetradio.net/rss2.xml
Name: LugRadio
Main Subject: Linux and Open Source
Format: Casual
Approx. Updates Per Month: 0 to 2
Recent Subjects Covered: the Portland Project, trusted computing, comparison of Linux distributions, Software Freedom Day
Justification: Possibly the most popular Linux-related podcast
Rss Link: http://www.lugradio.org/episodes.rss
Name: The Linux Link Tech Show
Main Subject: The cutting-edge in Linux-based technology
Format: Casual
Approx. Updates Per Month: 4
Recent Subjects Covered: Linux Home Automation, OpenWRT, Asterisk, Debian vs Mozilla, DRM
Justification: Lots of good Linux-related information
Rss Link: http://www.thelinuxlink.net/tllts/tllts.rss
Name: StillSecure, After all these years
Main Subject: All things related to information security with a focus on a business environment
Format: Formal
Approx. Updates Per Month: 2 to 5
Recent Subjects Covered: Interview with Steve Hanna of Juniper Networks, TCG/TNC, The IETF, 3rd party patching
Justification: This podcast includes some great interviews and information centered around enterprise security
Rss Link: http://clickcaster.com/clickcast/rss/1653
Name: Symantec Security Response Podcast
Main Subject: Security updates
Format: Formal
Approx. Updates Per Month: 2 to 4
Justification: A consistent source of security updates - great for people who are charged with defending a network for a living
Rss Link: http://www.symantec.com/content/en/us/about/rss/sr/sr.xml
Name: Network Security Blog
Main Subject: Network Security…
Format: Formal
Approx. Updates Per Month:
Rss Link: http://www.mckeay.net/secure/index.xml
Friday, 25 June 2010
PS3 Black screen on game loading
so, pretty pointless post, but someone may stumble upon it sometime and it may help you so here it is..
had my PS3 for well over a couple of years and been playing on the same tv in HD all the time.. all of a sudden when i loaded games the screen just stayed black. i spoke to sony and htey sent me a replacement for £130 and i exchanged my old one.. got the new one, exactly the same problem, it turned out that it was the resoultion the PS3 was setting itself to. I have no idea why this happened on the same tv as i had always been playing on, but anyway, all i had to do in the end was take off the tick in the 1080 checkbox in display settings and it worked, and sony are refunding my £130.. happy days..
Paul
had my PS3 for well over a couple of years and been playing on the same tv in HD all the time.. all of a sudden when i loaded games the screen just stayed black. i spoke to sony and htey sent me a replacement for £130 and i exchanged my old one.. got the new one, exactly the same problem, it turned out that it was the resoultion the PS3 was setting itself to. I have no idea why this happened on the same tv as i had always been playing on, but anyway, all i had to do in the end was take off the tick in the 1080 checkbox in display settings and it worked, and sony are refunding my £130.. happy days..
Paul
Sunday, 20 June 2010
Learn NHibernate Lesson 5 - Modelling foreign key relationships
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
5. Modelling foreign key relationships
a one to many relationship between customer and orders in a database could be said to be, or coded like:[csharp]
class Customer {
private IList<Order> _orders;
class Order {
private Customer customer;
[/csharp]
sql may be:[sql]
from parent to child:
select * from customer inner join order on c.customerid on o.customerid where c.customerid = (id of the customer)
from child to parent:
select * from order inner join customer on o.customerid on c.customerid where o.orderid = (id of the order)
[/sql]
mapping files
supported relationships
one-to-one
one-to-many
many-to-one
many-to-many
not all orm software support all these, especially many to many
mappping files also control cascade updates and cascade deletes
you can control navigation between parents and children in mapping files
NHibernate collection types
Bag
collection of objects where each element can repeat (implemented as an IList or IList of <T>) { 1, 2, 3, 3, 3 }
Set
collection of object where each element must be unique (same as a true mathematical set) (implemented as an ISet or ISet<T>)
ISet is in Iesi.Collections.dll (not in .Net libraries)
List
collection of object with integer indicies (impleneted as an ArrayList or List<T>
Map
collection of key value pairs (implemented as IDictionary or hashtable)
Collection Mappings
defines:
collection type (bag, set..)
cardinality (one to many etc..)
cascasde behaviour
who is responsible for updating (inverse = true, child is responsible)
Child collection mapping define very little, usually just a pointer to support navigation back to the parent and the cardinality back to the parent
deep object graphs casue a lot of trouble, recursive relationships due to self referetial modelling (orders on customer and customer on orders)
Lazy Loading
the name doesnt exaplin exactly whats happenning
it should be named 'delayed laoding' or 'load on demand'
implentation is The Proxy Pattern
how it works
orders colletion on customers would create a proxy object, so it doesnt actually go and get the orders, but it knows how to. so if we dont interact with the orders collection, it will never be loaded. as soon as we do, the proxy object will be invoked and it will go off tothe dband get the orders..
after that, the proxy object goes away, the colection will now point to the correct orders object
the same thing is true in the reverse direction, each order object on the collection will contain proxy objects to the customer. however this will not actually go to the db as nhibe will check the session fo rthe customer we need, and it will already be there as the parent that loaded the orders collection
our order class willl look like this: //excuse the lack of settters and getters this is just an example[csharp]
public class Order {
public int orderid;
public DateTIme Order;
//now, although we are only referencing the customer and an int, or id in the database, we do not model this as an int, customerid, we actually model it as a Customer object
public Customer customer;
//in our customers class we now have
public ISet<Order> _orders;
[/csharp]
mapping the order class
now, in our customer hbm.xml mapping file, we add the following:[xml]
<set name="Orders" table="`Order`" generic="true" inverse="true"> //inverse=true the child object is responsible for maintaining the relationship back to the customer
<key column="Customer" />
<one-to-many class="DataTransfer.Order, DataTransfer" />
</set>
[/xml]
now, we create a new Order hbm.xml Mapping file..[xml]
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembley="DataTransfer" namespace="DataTransfer">
<class name="DataTransfer.Order, DataTransfer" table="`Order`"> (Namepsapce.TypeName, Namespace)
<id name="OrderId" column="OrderId" type="Int32" unsaved-value="0">
<generator></generator>
</id>
<property name="Name" column="Name" type="string" length="50" not-null="false"></property>
<property name="OrderDate" column="OrderDate" type="DateTime" not-null="true"></property>
<many-to-one name="Customer" column="Customer" not-null="true" class="DataTransfer.Customer, DataTransfer" />
</class>
</hibernate-mapping>
[/xml]
remember to change the build action for new hbm.xml files to embedded resource..
NOTE, in NHibe, if you are using db keywords, like table or order, instead of using [table] or [order] we use the back tick like so: `Order`
Testing the mapping files
understanding lazy loading
looking at a GetCustomerById()
if we look at the orders in the loaded customer, we'll get an nhibe exception, no session, why? beacsue we have wrapped our session in a using statment
so when the object tries to hydrate the orders object, there is no session
so for lazy loading you must make sure you have not disposed of the session before the lazy loading has worked
you could change the lazy attribute in the set tag in customers mapping file to false : lazy="false"
you could make another method called get customers and orders by custoemr id that does not dispose of the session
we will look at better ways of handling session lifecycle in later lessons
now if we make the new method[csharp]
public Customer GetCustomersAndOrdersByCustomerId(int id)
{
Customer customer = session.Get<Customer>(id);
//fill out (load) the orders and dont load as proxy
NHibernateUtil.Initialize(customer.Orders); // util is in iesi.collections.dll
}
[/csharp]
a one to many relationship between customer and orders in a database could be said to be, or coded like:[csharp]
class Customer {
private IList<Order> _orders;
class Order {
private Customer customer;
[/csharp]
sql may be:[sql]
from parent to child:
select * from customer inner join order on c.customerid on o.customerid where c.customerid = (id of the customer)
from child to parent:
select * from order inner join customer on o.customerid on c.customerid where o.orderid = (id of the order)
[/sql]
mapping files
supported relationships
one-to-one
one-to-many
many-to-one
many-to-many
not all orm software support all these, especially many to many
mappping files also control cascade updates and cascade deletes
you can control navigation between parents and children in mapping files
NHibernate collection types
Bag
collection of objects where each element can repeat (implemented as an IList or IList of <T>) { 1, 2, 3, 3, 3 }
Set
collection of object where each element must be unique (same as a true mathematical set) (implemented as an ISet or ISet<T>)
ISet is in Iesi.Collections.dll (not in .Net libraries)
List
collection of object with integer indicies (impleneted as an ArrayList or List<T>
Map
collection of key value pairs (implemented as IDictionary or hashtable)
Collection Mappings
defines:
collection type (bag, set..)
cardinality (one to many etc..)
cascasde behaviour
who is responsible for updating (inverse = true, child is responsible)
Child collection mapping define very little, usually just a pointer to support navigation back to the parent and the cardinality back to the parent
deep object graphs casue a lot of trouble, recursive relationships due to self referetial modelling (orders on customer and customer on orders)
Lazy Loading
the name doesnt exaplin exactly whats happenning
it should be named 'delayed laoding' or 'load on demand'
implentation is The Proxy Pattern
how it works
orders colletion on customers would create a proxy object, so it doesnt actually go and get the orders, but it knows how to. so if we dont interact with the orders collection, it will never be loaded. as soon as we do, the proxy object will be invoked and it will go off tothe dband get the orders..
after that, the proxy object goes away, the colection will now point to the correct orders object
the same thing is true in the reverse direction, each order object on the collection will contain proxy objects to the customer. however this will not actually go to the db as nhibe will check the session fo rthe customer we need, and it will already be there as the parent that loaded the orders collection
our order class willl look like this: //excuse the lack of settters and getters this is just an example[csharp]
public class Order {
public int orderid;
public DateTIme Order;
//now, although we are only referencing the customer and an int, or id in the database, we do not model this as an int, customerid, we actually model it as a Customer object
public Customer customer;
//in our customers class we now have
public ISet<Order> _orders;
[/csharp]
mapping the order class
now, in our customer hbm.xml mapping file, we add the following:[xml]
<set name="Orders" table="`Order`" generic="true" inverse="true"> //inverse=true the child object is responsible for maintaining the relationship back to the customer
<key column="Customer" />
<one-to-many class="DataTransfer.Order, DataTransfer" />
</set>
[/xml]
now, we create a new Order hbm.xml Mapping file..[xml]
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembley="DataTransfer" namespace="DataTransfer">
<class name="DataTransfer.Order, DataTransfer" table="`Order`"> (Namepsapce.TypeName, Namespace)
<id name="OrderId" column="OrderId" type="Int32" unsaved-value="0">
<generator></generator>
</id>
<property name="Name" column="Name" type="string" length="50" not-null="false"></property>
<property name="OrderDate" column="OrderDate" type="DateTime" not-null="true"></property>
<many-to-one name="Customer" column="Customer" not-null="true" class="DataTransfer.Customer, DataTransfer" />
</class>
</hibernate-mapping>
[/xml]
remember to change the build action for new hbm.xml files to embedded resource..
NOTE, in NHibe, if you are using db keywords, like table or order, instead of using [table] or [order] we use the back tick like so: `Order`
Testing the mapping files
understanding lazy loading
looking at a GetCustomerById()
if we look at the orders in the loaded customer, we'll get an nhibe exception, no session, why? beacsue we have wrapped our session in a using statment
so when the object tries to hydrate the orders object, there is no session
so for lazy loading you must make sure you have not disposed of the session before the lazy loading has worked
you could change the lazy attribute in the set tag in customers mapping file to false : lazy="false"
you could make another method called get customers and orders by custoemr id that does not dispose of the session
we will look at better ways of handling session lifecycle in later lessons
now if we make the new method[csharp]
public Customer GetCustomersAndOrdersByCustomerId(int id)
{
Customer customer = session.Get<Customer>(id);
//fill out (load) the orders and dont load as proxy
NHibernateUtil.Initialize(customer.Orders); // util is in iesi.collections.dll
}
[/csharp]
Thursday, 17 June 2010
Learn NHibernate Lesson 4 - Transactions and Concurrency
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
4. Transactions and Concurrency
nhiberate provides its own ITransaction abstraction
the goal of nhibe is to abstract the choice of databse engine for you. so you dont need to worry about how the db imlements transactions, nhibe will do it for you.
Transaction Pattern
ask the ISession to begin a transaction
do some work
commit or rollback the transaction[csharp]
ITransaction tx = session.BeginTransaction();
//do some work
tx.Commit();
// or tx.Rollback();
[/csharp]
real world is a bit more complex[csharp]
using(ITransaction tx = session.BeginTransaction())
{
try {
//do some work
tx.Commit();
}
catch(NHibernateException) {
tx.Rollback();
throw;
}
}
[/csharp]
when shold you use transactions? Aways! - even on reads (queries)
you have no idea why a db operation may have failed, so instead or worrying, just implement transactions..
before we start we need a refactor of our dataaccess layer. we have a private global session
this is not a great design strategy
the session is not made to be hung on to for a long time
it is non thread safe use once and throw away
the session factory however is much stronger use once
so.. we change the private ISession to an ISessionFactory[csharp]
public class DataAccessProvider
{
private ISessionFactory sessionFactory;
//we now call the getsession in the constructor to the class..
public DataAccessProvider ()
{
sessionFactory = GetSessionFactory();
}
private static ISession GetSession()
{
return sessionFactory.OpenSession();
}
private static ISession GetSessionFactory()
{
return (new Configuration()).Configure().BuildSessionFactory();
}
[/csharp]
now our methods become like:[csharp]
public void AddCustomer(Customer customer)
{
ISession session = GetSession();
session.Save(customer); //save will return an object that represents the primary key of that object in the database
session.Flush();
}
[/csharp]
now each method will use its own copy of the session (not perfect, we will move on again later in the lessons..[csharp]
[test]
[ExpectedException(typeof(NHibernate.HibernateException))]
public void DeleteCustomerCanThrowExceptionOnFail()
{
Customer c = GetFirstCustomerWithOrders();
provider.DeleteCustomer(c);
}
[/csharp]
now, how can we refactor the delete customer method to take advantage of transactions..[csharp]
public void DeleteCustomer(Customer c)
{
using(ISession session = GetSession()) {
using(ITransaction tx = session.BeginTransaction()) {
try {
session.Delete(c);
session.Flush();
tx.Commit();
}
catch(NHibernateException) {
tx.Rollback();
throw;
}
}
}
}
[/csharp]
Concurrency
what does it mean? 2 or more users may be editing hte same data at the same time..
this especially happens in a disconnected-data world
types of concurrency:
Pessimistic concurrency
something in the overall system is responsible for actively blocking operations that could result in data-synchronisation conflicts
Pessimistic (assume something is going to go badly and actively block it from happening)
usually accomplished by exclusive locks approach - Expensive!
Optimsitic Concurrency
assumes no operations that could result in data-synchronisation conflicts will occur and is reposinsible for reacting properly when they do
similar to edit, merge, comit with todays source control, unlike old source control with exclusive locks..
NHibernate Optimistic Concurrency
several approaches
in the approriate hbm.xml mapping file, add a <version> element (implementation of row versioning)
or a <timestamp> element (implementation of timestamp tracking)
and several others..
in general, row versioning is preferred
the version tag must precede any property tags in the mapping file
assuming we have added an integer proeprty called version to customer class[xml]
<version name="Version" column="Version" type="integer" unsaved-value="0" />
[/xml]
now in the database, when you add the version column, no nulls, default value is 1
nhiberate provides its own ITransaction abstraction
the goal of nhibe is to abstract the choice of databse engine for you. so you dont need to worry about how the db imlements transactions, nhibe will do it for you.
Transaction Pattern
ask the ISession to begin a transaction
do some work
commit or rollback the transaction[csharp]
ITransaction tx = session.BeginTransaction();
//do some work
tx.Commit();
// or tx.Rollback();
[/csharp]
real world is a bit more complex[csharp]
using(ITransaction tx = session.BeginTransaction())
{
try {
//do some work
tx.Commit();
}
catch(NHibernateException) {
tx.Rollback();
throw;
}
}
[/csharp]
when shold you use transactions? Aways! - even on reads (queries)
you have no idea why a db operation may have failed, so instead or worrying, just implement transactions..
before we start we need a refactor of our dataaccess layer. we have a private global session
this is not a great design strategy
the session is not made to be hung on to for a long time
it is non thread safe use once and throw away
the session factory however is much stronger use once
so.. we change the private ISession to an ISessionFactory[csharp]
public class DataAccessProvider
{
private ISessionFactory sessionFactory;
//we now call the getsession in the constructor to the class..
public DataAccessProvider ()
{
sessionFactory = GetSessionFactory();
}
private static ISession GetSession()
{
return sessionFactory.OpenSession();
}
private static ISession GetSessionFactory()
{
return (new Configuration()).Configure().BuildSessionFactory();
}
[/csharp]
now our methods become like:[csharp]
public void AddCustomer(Customer customer)
{
ISession session = GetSession();
session.Save(customer); //save will return an object that represents the primary key of that object in the database
session.Flush();
}
[/csharp]
now each method will use its own copy of the session (not perfect, we will move on again later in the lessons..[csharp]
[test]
[ExpectedException(typeof(NHibernate.HibernateException))]
public void DeleteCustomerCanThrowExceptionOnFail()
{
Customer c = GetFirstCustomerWithOrders();
provider.DeleteCustomer(c);
}
[/csharp]
now, how can we refactor the delete customer method to take advantage of transactions..[csharp]
public void DeleteCustomer(Customer c)
{
using(ISession session = GetSession()) {
using(ITransaction tx = session.BeginTransaction()) {
try {
session.Delete(c);
session.Flush();
tx.Commit();
}
catch(NHibernateException) {
tx.Rollback();
throw;
}
}
}
}
[/csharp]
Concurrency
what does it mean? 2 or more users may be editing hte same data at the same time..
this especially happens in a disconnected-data world
types of concurrency:
Pessimistic concurrency
something in the overall system is responsible for actively blocking operations that could result in data-synchronisation conflicts
Pessimistic (assume something is going to go badly and actively block it from happening)
usually accomplished by exclusive locks approach - Expensive!
Optimsitic Concurrency
assumes no operations that could result in data-synchronisation conflicts will occur and is reposinsible for reacting properly when they do
similar to edit, merge, comit with todays source control, unlike old source control with exclusive locks..
NHibernate Optimistic Concurrency
several approaches
in the approriate hbm.xml mapping file, add a <version> element (implementation of row versioning)
or a <timestamp> element (implementation of timestamp tracking)
and several others..
in general, row versioning is preferred
the version tag must precede any property tags in the mapping file
assuming we have added an integer proeprty called version to customer class[xml]
<version name="Version" column="Version" type="integer" unsaved-value="0" />
[/xml]
now in the database, when you add the version column, no nulls, default value is 1
Wednesday, 9 June 2010
Learn NHibernate Lesson 3 - Insert, Update and Deletes
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
3. Insert, Update and Deletes
A Unit of work is an isolated area withing which i cna perform one or more operations. They are either commited or abandoned / rolled back as one.
As of yet we have not used nhibe to change any data. Query only. if no changes, then no commit or rollback..
Insert Pattern is simple
New up an object, ask the ISession to save it, Flush the session (flush is the commit method)[csharp]
Customer customer = new Customer();
session.save(customer);
session.Flush();
[/csharp]
Delete pattern is simple[csharp]
Customer customer = provider.GetCustomerById(1);
session.Delete(customer);
session.Flush();
[/csharp]
Update pattern
have an object
change a property
ask the session to update it
flush the sesison
primary annoyance is that you have to keep track of what objects have chnaged.. but there is a solution, ISession is able to keep track of what object are new and updated so we can call session.SaveOrUpdate and NHibe will perform the correct action. Calling saveorupdate will cause NHibe to go through some checking operatios such as:
is the object in session? if not there, call implicit Save(object);
if its there, see it the object has changed, if it has, call implicit update(object)..[csharp]
public void AddCustomer(Customer customer)
{
session.Save(customer); //save will return an object that represents the primary key of that object in the database
session.Flush();
}
[/csharp]
so you can get new primary key by saying[csharp]
int newId = (int)session.Save(customer);
[test]
public void CanAddCustomer()
{
Customer customer = new Customer() { Firstname = "steve", Lastname = "smith" };
int newId = provider.AddCustomer(customer);
Customer testCustomer = provider.GetCustomerById(newId);
Assert.IsNotNull(testCustomer);
}
public void DeleteCustomer(Customer customer)
{
session.Delete(customer);
session.Flush();
}
[test]
public void CanDeleteCustomer()
{
Customer customer = provider.GetCustomerById(1);
provider.DeleteCustomer(customer);
Customer testCustomer = provider.GetCustomerById(1);
Assert.IsNull(testCustomer);
}
[/csharp]
A Unit of work is an isolated area withing which i cna perform one or more operations. They are either commited or abandoned / rolled back as one.
As of yet we have not used nhibe to change any data. Query only. if no changes, then no commit or rollback..
Insert Pattern is simple
New up an object, ask the ISession to save it, Flush the session (flush is the commit method)[csharp]
Customer customer = new Customer();
session.save(customer);
session.Flush();
[/csharp]
Delete pattern is simple[csharp]
Customer customer = provider.GetCustomerById(1);
session.Delete(customer);
session.Flush();
[/csharp]
Update pattern
have an object
change a property
ask the session to update it
flush the sesison
primary annoyance is that you have to keep track of what objects have chnaged.. but there is a solution, ISession is able to keep track of what object are new and updated so we can call session.SaveOrUpdate and NHibe will perform the correct action. Calling saveorupdate will cause NHibe to go through some checking operatios such as:
is the object in session? if not there, call implicit Save(object);
if its there, see it the object has changed, if it has, call implicit update(object)..[csharp]
public void AddCustomer(Customer customer)
{
session.Save(customer); //save will return an object that represents the primary key of that object in the database
session.Flush();
}
[/csharp]
so you can get new primary key by saying[csharp]
int newId = (int)session.Save(customer);
[test]
public void CanAddCustomer()
{
Customer customer = new Customer() { Firstname = "steve", Lastname = "smith" };
int newId = provider.AddCustomer(customer);
Customer testCustomer = provider.GetCustomerById(newId);
Assert.IsNotNull(testCustomer);
}
public void DeleteCustomer(Customer customer)
{
session.Delete(customer);
session.Flush();
}
[test]
public void CanDeleteCustomer()
{
Customer customer = provider.GetCustomerById(1);
provider.DeleteCustomer(customer);
Customer testCustomer = provider.GetCustomerById(1);
Assert.IsNull(testCustomer);
}
[/csharp]
Tuesday, 8 June 2010
Building Visual Studio solutions from a right click in windows explorer
Heres how to add build to the context menu of a sln file..
note: you only need the tool for vista.. xp and 7 let you change and add context menu operations in the folder options->file type menu..
so, if you are on vista, download from http://www.creativelement.com/powertools/#download
when you start it for first time, check the "Edit File Type Associations" box, theres loads of other good stuff but ill let you discover
now right click the sln file and select edit file type
click ADD
type Build (debug) for the top text box
then paste this in second box (which application to use)
c:\WINDOWS\system32\cmd.exe
and this in the final box (command line op)
/k C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe "%1" /p:Configuration=Debug /t:Rebuild
Now go back to the sln file and youll be able to right click and build..
Have fun
note: you only need the tool for vista.. xp and 7 let you change and add context menu operations in the folder options->file type menu..
so, if you are on vista, download from http://www.creativelement.com/powertools/#download
when you start it for first time, check the "Edit File Type Associations" box, theres loads of other good stuff but ill let you discover
now right click the sln file and select edit file type
click ADD
type Build (debug) for the top text box
then paste this in second box (which application to use)
c:\WINDOWS\system32\cmd.exe
and this in the final box (command line op)
/k C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe "%1" /p:Configuration=Debug /t:Rebuild
Now go back to the sln file and youll be able to right click and build..
Have fun
Monday, 7 June 2010
Learn NHibernate Lesson Part 2 - More Query Methods and Syntaxes
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
2 - Part 2 More Query Methods and Syntaxes
first a refactor.. up until now we have been getting a session in every dataaccess layer method. we dont want to be doing this as each time we get teh session we are connecting to the db, and wiring up anything else needed.. a waste.. so, we'll start by making session a private member on the dataaccess layer.[csharp]
public class DataAccessProvider
{
private ISession session;
//we now call the getsession in the constructor to the class..
public DataAccessProvider ()
{
session = GetSession();
}
//now methods will look like the following:
public IList<Customer> GetCustomerByFirstName(string firstname)
{
return session.CreateQuery("select from Customer c whre c.Firsname='" + firstname + "'").List<Customer>();
}
[/csharp]
getting distinct in HQL[csharp]
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateQuery"select distinct c.Firstname from Customer c").List<string>();
}
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
IList<string> foundfirstnames = new List<string>();
foreach (string fn in firstnames)
{
if(foundFirstnames.Count != 0)
Assert.IsFalse(foundFirstNames.Contains(fn));
foundFirstNames.Add(fn);
}
}
[/csharp]
refactor test to use lambda expressions..[csharp]
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
foreach (string fn in firstnames)
{
Assert.AreEqual(1, firstnames.Count<string>(x => x == fn));
}
}
//GetDistinctCustomerFirstnames using criteria
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateCrtieria<Customer>
.SetProjection(Projections.Distinct(Projections.Property("Firstname")))
.List<string>();
}
[/csharp]
getting ordered names through HQL[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select from Customer c order by c.Firstname").List<Customer>();
.List<string>();
}
[/csharp]
getting ordered names through Criteria[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateCritera<Customer>
.AddOrder(new Order("Firstname", true))
.List<string>();
}
[/csharp]
getting counted names through HQL[csharp]
public IList<object[]> GetCountedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname").List<object[]>();
.List<string>();
}
[test]
public void CanGetCountedCustomerFirstnames()
{
IList<object[]> firstnameCounts = provider.GetCountedCustomerFirstnames();
Dictionary<String, int> expectedCounts = new Dictionary<string, int>();
expectedCounts.Add("steve", 3);
expectedCounts.Add("mike", 1);
foreach(object[] item in firstnameCounts)
{
Assert.AreEqual(expectedCounts[item[0].ToString()], item[1]);
}
}
[/csharp]
first a refactor.. up until now we have been getting a session in every dataaccess layer method. we dont want to be doing this as each time we get teh session we are connecting to the db, and wiring up anything else needed.. a waste.. so, we'll start by making session a private member on the dataaccess layer.[csharp]
public class DataAccessProvider
{
private ISession session;
//we now call the getsession in the constructor to the class..
public DataAccessProvider ()
{
session = GetSession();
}
//now methods will look like the following:
public IList<Customer> GetCustomerByFirstName(string firstname)
{
return session.CreateQuery("select from Customer c whre c.Firsname='" + firstname + "'").List<Customer>();
}
[/csharp]
getting distinct in HQL[csharp]
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateQuery"select distinct c.Firstname from Customer c").List<string>();
}
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
IList<string> foundfirstnames = new List<string>();
foreach (string fn in firstnames)
{
if(foundFirstnames.Count != 0)
Assert.IsFalse(foundFirstNames.Contains(fn));
foundFirstNames.Add(fn);
}
}
[/csharp]
refactor test to use lambda expressions..[csharp]
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
foreach (string fn in firstnames)
{
Assert.AreEqual(1, firstnames.Count<string>(x => x == fn));
}
}
//GetDistinctCustomerFirstnames using criteria
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateCrtieria<Customer>
.SetProjection(Projections.Distinct(Projections.Property("Firstname")))
.List<string>();
}
[/csharp]
getting ordered names through HQL[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select from Customer c order by c.Firstname").List<Customer>();
.List<string>();
}
[/csharp]
getting ordered names through Criteria[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateCritera<Customer>
.AddOrder(new Order("Firstname", true))
.List<string>();
}
[/csharp]
getting counted names through HQL[csharp]
public IList<object[]> GetCountedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname").List<object[]>();
.List<string>();
}
[test]
public void CanGetCountedCustomerFirstnames()
{
IList<object[]> firstnameCounts = provider.GetCountedCustomerFirstnames();
Dictionary<String, int> expectedCounts = new Dictionary<string, int>();
expectedCounts.Add("steve", 3);
expectedCounts.Add("mike", 1);
foreach(object[] item in firstnameCounts)
{
Assert.AreEqual(expectedCounts[item[0].ToString()], item[1]);
}
}
[/csharp]
Saturday, 5 June 2010
Creating an iPhone Distribution
Requirements:
- A distribution provisioning profile will need to be installed prior to creating a build.
- To follow these steps, you must have the All-in-One layout set in the General tab of the Xcode Preferences.
Step #1 Create Distribution Configuration
- Select the Project Name in Xcode (see below)
- Right click and choose Get Info dialog (or enter Command I)
- Select Configuration tab
- Click on Release in the list of configurations and select Duplicate from the options along the bottom
- Name the new configuration Distribution
- Close the window
Step #2 Set Target Information
- Select the Target (see below)
- Right click and choose Get Info dialog
- Select Build tab
- Choose Distribution from Configuration drop-down
- In the Architectures section in the list of settings, choose a Base SDK (e.g. Device - iPhone OS 2.2.1)
- From the Code Signing Section, under Code Signing Identity, choose the appropriate profile (e.g. Ad Hoc or Distribution Profile)
- Select Properties tab
- Set Executable name (e.g. theAstrologerFree)There is a default value here: ${EXECUTABLE_NAME} which will also work for most projects
- Set Identifier to com.domain.application-name (e.g. com.3SixtySoftware.theAstrologerFree)There is a default value here: com.yourcompany.${PRODUCT_NAME:identifier} which you may work for your project. If you run into errors or conflicts with other applications try replacing${PRODUCT_NAME:identifier} with a unique string that represents your application nameSet Version # (e.g. 1.1)
- Set Icon File to Icon.png
- • Make sure you have an icon that is 57x57 pixels, with the name Icon.png in the project
- Close the window
Visit iPhoneDeveloperTips.com for more Tips and Tricks
Step #3 Set Active Configuration
- Select the Debug workspace button (see below) Select the Project workspace button (the button to the left of Debug)
- From the drop-down (upper left) choose:
- Choose the Device Setting you plan to target under Active SDK (e.g. Device - iPhone OS 2.2.1)
- Choose Distribution as the Active Configuration
If creating an Ad Hoc Distribution:
- Create new file (Command N), select Code Signing, choose Entitlements, click Next
- Name the file Entitlements.plist
- Uncheck the get-task-allow button
- Save file
- Make sure the file is at the root of project hierarchy (e.g. drag the file just below the Project name)
- Select the Target
- Right click and choose Get Info dialog
- Select Build tab
- Fill in the Code Signing Entitlements with Entitlements.plist
Step #4 Verify Target Settings
- Select the Target
- Right click and choose Get Info dialog
- Select Properties tab
- Note the Executable name (e.g. theAstrologerFree)Close the window
- Select Build tab
- Scroll down to Packaging
- Verify (or input) the Product Name to match the Executable name from above
Step #5 Verify Info.plist
- Click on Info.plist in the Resources folder
- Check the following:
- Bundle Display Name - this is the text that will appear on the iPhone Home screen under the icon
- Executable name - this should match what youʼve entered in the Properties settings
- Icon must be set to Icon.png
- Bundle Identifier - for example com.3SixtySoftware.theAstrologerFree
- Bundle version - for example 1.1
Step #6 Clean and Build
- From the Build menu choose Clean All Targets
- From the Build menu choose Build (Command B)
Thursday, 20 May 2010
Learn NHibernate lesson 1 - setup and basic usage
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
its an abstraction layered on top of database
ISesssion, unit of work pattern, same as Dataset in ADO.NET
a unit of work consists of:
Open session by getting from session factory
Do some work (session.add, session.delete)
flush the session
getting a session:
sessionfactory.opensession
how does session factory build itself?
uses configuration class to build it
config is throw away class[csharp]
ISessionfactory sf = new Configuration().Configure().BuildSessionFactory();
[/csharp]
vs 2008
if using xml onfig, drop nhibe xsd's in to vs intellisense directory
once hibernate mapping tag in config xml, will be able to use intellinsense for conifg xml[xml]
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembley="DataTransfer" namespace="DataTransfer">
[/xml]
with reference to NHibernate 1.2.1
1. Setup and basic usage pattern
xml config
mapping files tell nhibe how db maps to objects
relies on convention over configuration
case sensitive
default is to use convention which is "classname.hbm.xml"
one for each class, start with class name[xml]
<class name="DataTransfer.Customer, DataTransfer" table="Customer"> (Namepsapce.TypeName, Namespace)
[/xml]
must have an id tag (primary key or composite id)[xml]
<id name="CustomerId" column="CustomerId" type="Int32" unsaved-value="0">
<generator></generator>
</id>
[/xml]
(this tells nhibe how to generate value for the id, native means db will use its own capabilities to gen the id)[xml]
<property name="FirstName" column="FirstName" type="string" length="50" not-null="false"></property>
[/xml]
if no column name specified, nhibe will asume column is same name as property
deploying mapping files
set build action of hbm.xml in vs to embedded resource so they are compiled in to assemblies
using lutz roeders .NET refelctor you can see dissasemblies
all methods in classes should be virtual!
new up new configuration and session[csharp]
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OPenSession();
[/csharp]
creating a dataaccess layer
getting an object from db by id[csharp]
public class NHIbernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OpenSession();
//no generic get
return (DataTransfer.Customer)session.Get(typeof(Datatrasnfer.Customer), customerId);
//generic get
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
cleaning that up
configuration class only needed long enough to get a session factory[csharp]
using NHIbernate;
using DataTransfer;
public class NHibernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
ISessionfactory sf = (new Configuration()).Configure().BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
test project for dataaccess layer
assume references addded.. and using statementsn included..
providing a connection string for NHibernate and other configuration
NHibernate configuration file belongs in project that is running code.. so needs to be included in the test project
XML File called "hibernate.config.xml"[xml]
<hibernate-configuration xmlns="urn:nhibernate-mapping-2.2">
<session-factory name="MyFavouriteSessionFactory"> (you could have an app that talks to differnt databases by addnig name to the session factory tag)
<property name="connection.provider">...
<property name="connection.connection_string">...
<property name="show_sql">true<property>
<mapping assembly="DataTransfer"/>
</session-factory>
[/xml]
you can see the defaults needed and structure by opening the nhibernate.config.xml that is downlaoded with NHibernate..
it includes things like query substitutionns, command timeout, drivers and other useful stuff..[csharp]
[TestFixture]
public class tests
{
[test]
public void CanGetCustomerById()
{
DataAccessLayer.NHibernateDataProvider provider = new DataAccessLayer.NHibernateDataProvider();
Assert.AreEqual(1, provider.GetCustomerId(1).CUstomerId);
}
}
[/csharp]
Show SQL
adding the <property name="show_sql">true<property> to your config file qill echo the sql statement (eg console output). so in the html report from MBUnit you wil see the sql generated by NHIbernate in the test results.
nhibernate generates parametirised sql so that sql server can generate cached execution plans. its also protection from sql injection
its an abstraction layered on top of database
ISesssion, unit of work pattern, same as Dataset in ADO.NET
a unit of work consists of:
Open session by getting from session factory
Do some work (session.add, session.delete)
flush the session
getting a session:
sessionfactory.opensession
how does session factory build itself?
uses configuration class to build it
config is throw away class[csharp]
ISessionfactory sf = new Configuration().Configure().BuildSessionFactory();
[/csharp]
vs 2008
if using xml onfig, drop nhibe xsd's in to vs intellisense directory
once hibernate mapping tag in config xml, will be able to use intellinsense for conifg xml[xml]
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembley="DataTransfer" namespace="DataTransfer">
[/xml]
with reference to NHibernate 1.2.1
1. Setup and basic usage pattern
xml config
mapping files tell nhibe how db maps to objects
relies on convention over configuration
case sensitive
default is to use convention which is "classname.hbm.xml"
one for each class, start with class name[xml]
<class name="DataTransfer.Customer, DataTransfer" table="Customer"> (Namepsapce.TypeName, Namespace)
[/xml]
must have an id tag (primary key or composite id)[xml]
<id name="CustomerId" column="CustomerId" type="Int32" unsaved-value="0">
<generator></generator>
</id>
[/xml]
(this tells nhibe how to generate value for the id, native means db will use its own capabilities to gen the id)[xml]
<property name="FirstName" column="FirstName" type="string" length="50" not-null="false"></property>
[/xml]
if no column name specified, nhibe will asume column is same name as property
deploying mapping files
set build action of hbm.xml in vs to embedded resource so they are compiled in to assemblies
using lutz roeders .NET refelctor you can see dissasemblies
all methods in classes should be virtual!
new up new configuration and session[csharp]
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OPenSession();
[/csharp]
creating a dataaccess layer
getting an object from db by id[csharp]
public class NHIbernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OpenSession();
//no generic get
return (DataTransfer.Customer)session.Get(typeof(Datatrasnfer.Customer), customerId);
//generic get
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
cleaning that up
configuration class only needed long enough to get a session factory[csharp]
using NHIbernate;
using DataTransfer;
public class NHibernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
ISessionfactory sf = (new Configuration()).Configure().BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
test project for dataaccess layer
assume references addded.. and using statementsn included..
providing a connection string for NHibernate and other configuration
NHibernate configuration file belongs in project that is running code.. so needs to be included in the test project
XML File called "hibernate.config.xml"[xml]
<hibernate-configuration xmlns="urn:nhibernate-mapping-2.2">
<session-factory name="MyFavouriteSessionFactory"> (you could have an app that talks to differnt databases by addnig name to the session factory tag)
<property name="connection.provider">...
<property name="connection.connection_string">...
<property name="show_sql">true<property>
<mapping assembly="DataTransfer"/>
</session-factory>
[/xml]
you can see the defaults needed and structure by opening the nhibernate.config.xml that is downlaoded with NHibernate..
it includes things like query substitutionns, command timeout, drivers and other useful stuff..[csharp]
[TestFixture]
public class tests
{
[test]
public void CanGetCustomerById()
{
DataAccessLayer.NHibernateDataProvider provider = new DataAccessLayer.NHibernateDataProvider();
Assert.AreEqual(1, provider.GetCustomerId(1).CUstomerId);
}
}
[/csharp]
Show SQL
adding the <property name="show_sql">true<property> to your config file qill echo the sql statement (eg console output). so in the html report from MBUnit you wil see the sql generated by NHIbernate in the test results.
nhibernate generates parametirised sql so that sql server can generate cached execution plans. its also protection from sql injection
Learn NHibernate lesson 1 - setup and basic usage
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
its an abstraction layered on top of database
ISesssion, unit of work pattern, same as Dataset in ADO.NET
a unit of work consists of:
Open session by getting from session factory
Do some work (session.add, session.delete)
flush the session
getting a session:
sessionfactory.opensession
how does session factory build itself?
uses configuration class to build it
config is throw away class[csharp]
ISessionfactory sf = new Configuration().Configure().BuildSessionFactory();
[/csharp]
vs 2008
if using xml onfig, drop nhibe xsd's in to vs intellisense directory
once hibernate mapping tag in config xml, will be able to use intellinsense for conifg xml[xml]
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembley="DataTransfer" namespace="DataTransfer">
[/xml]
with reference to NHibernate 1.2.1
1. Setup and basic usage pattern
xml config
mapping files tell nhibe how db maps to objects
relies on convention over configuration
case sensitive
default is to use convention which is "classname.hbm.xml"
one for each class, start with class name[xml]
<class name="DataTransfer.Customer, DataTransfer" table="Customer"> (Namepsapce.TypeName, Namespace)
[/xml]
must have an id tag (primary key or composite id)[xml]
<id name="CustomerId" column="CustomerId" type="Int32" unsaved-value="0">
<generator></generator>
</id>
[/xml]
(this tells nhibe how to generate value for the id, native means db will use its own capabilities to gen the id)[xml]
<property name="FirstName" column="FirstName" type="string" length="50" not-null="false"></property>
[/xml]
if no column name specified, nhibe will asume column is same name as property
deploying mapping files
set build action of hbm.xml in vs to embedded resource so they are compiled in to assemblies
using lutz roeders .NET refelctor you can see dissasemblies
all methods in classes should be virtual!
new up new configuration and session[csharp]
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OPenSession();
[/csharp]
creating a dataaccess layer
getting an object from db by id[csharp]
public class NHIbernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OpenSession();
//no generic get
return (DataTransfer.Customer)session.Get(typeof(Datatrasnfer.Customer), customerId);
//generic get
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
cleaning that up
configuration class only needed long enough to get a session factory[csharp]
using NHIbernate;
using DataTransfer;
public class NHibernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
ISessionfactory sf = (new Configuration()).Configure().BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
test project for dataaccess layer
assume references addded.. and using statementsn included..
providing a connection string for NHibernate and other configuration
NHibernate configuration file belongs in project that is running code.. so needs to be included in the test project
XML File called "hibernate.config.xml"[xml]
<hibernate-configuration xmlns="urn:nhibernate-mapping-2.2">
<session-factory name="MyFavouriteSessionFactory"> (you could have an app that talks to differnt databases by addnig name to the session factory tag)
<property name="connection.provider">...
<property name="connection.connection_string">...
<property name="show_sql">true<property>
<mapping assembly="DataTransfer"/>
</session-factory>
[/xml]
you can see the defaults needed and structure by opening the nhibernate.config.xml that is downlaoded with NHibernate..
it includes things like query substitutionns, command timeout, drivers and other useful stuff..[csharp]
[TestFixture]
public class tests
{
[test]
public void CanGetCustomerById()
{
DataAccessLayer.NHibernateDataProvider provider = new DataAccessLayer.NHibernateDataProvider();
Assert.AreEqual(1, provider.GetCustomerId(1).CUstomerId);
}
}
[/csharp]
Show SQL
adding the <property name="show_sql">true<property> to your config file qill echo the sql statement (eg console output). so in the html report from MBUnit you wil see the sql generated by NHIbernate in the test results.
nhibernate generates parametirised sql so that sql server can generate cached execution plans. its also protection from sql injection
its an abstraction layered on top of database
ISesssion, unit of work pattern, same as Dataset in ADO.NET
a unit of work consists of:
Open session by getting from session factory
Do some work (session.add, session.delete)
flush the session
getting a session:
sessionfactory.opensession
how does session factory build itself?
uses configuration class to build it
config is throw away class[csharp]
ISessionfactory sf = new Configuration().Configure().BuildSessionFactory();
[/csharp]
vs 2008
if using xml onfig, drop nhibe xsd's in to vs intellisense directory
once hibernate mapping tag in config xml, will be able to use intellinsense for conifg xml[xml]
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembley="DataTransfer" namespace="DataTransfer">
[/xml]
with reference to NHibernate 1.2.1
1. Setup and basic usage pattern
xml config
mapping files tell nhibe how db maps to objects
relies on convention over configuration
case sensitive
default is to use convention which is "classname.hbm.xml"
one for each class, start with class name[xml]
<class name="DataTransfer.Customer, DataTransfer" table="Customer"> (Namepsapce.TypeName, Namespace)
[/xml]
must have an id tag (primary key or composite id)[xml]
<id name="CustomerId" column="CustomerId" type="Int32" unsaved-value="0">
<generator></generator>
</id>
[/xml]
(this tells nhibe how to generate value for the id, native means db will use its own capabilities to gen the id)[xml]
<property name="FirstName" column="FirstName" type="string" length="50" not-null="false"></property>
[/xml]
if no column name specified, nhibe will asume column is same name as property
deploying mapping files
set build action of hbm.xml in vs to embedded resource so they are compiled in to assemblies
using lutz roeders .NET refelctor you can see dissasemblies
all methods in classes should be virtual!
new up new configuration and session[csharp]
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OPenSession();
[/csharp]
creating a dataaccess layer
getting an object from db by id[csharp]
public class NHIbernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.COnfiguration();
config.configure();
NHibernate.ISessionfactory sf = config.BuildSessionFactory();
NHibernate.ISession session = sessionFactory.OpenSession();
//no generic get
return (DataTransfer.Customer)session.Get(typeof(Datatrasnfer.Customer), customerId);
//generic get
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
cleaning that up
configuration class only needed long enough to get a session factory[csharp]
using NHIbernate;
using DataTransfer;
public class NHibernateDataProvider
{
public Datatransfer.Customer GetCustomerByID(int cumstomerId)
{
ISessionfactory sf = (new Configuration()).Configure().BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
return session.Get<Datatransfer.Customer>(customerId);
}
}
[/csharp]
test project for dataaccess layer
assume references addded.. and using statementsn included..
providing a connection string for NHibernate and other configuration
NHibernate configuration file belongs in project that is running code.. so needs to be included in the test project
XML File called "hibernate.config.xml"[xml]
<hibernate-configuration xmlns="urn:nhibernate-mapping-2.2">
<session-factory name="MyFavouriteSessionFactory"> (you could have an app that talks to differnt databases by addnig name to the session factory tag)
<property name="connection.provider">...
<property name="connection.connection_string">...
<property name="show_sql">true<property>
<mapping assembly="DataTransfer"/>
</session-factory>
[/xml]
you can see the defaults needed and structure by opening the nhibernate.config.xml that is downlaoded with NHibernate..
it includes things like query substitutionns, command timeout, drivers and other useful stuff..[csharp]
[TestFixture]
public class tests
{
[test]
public void CanGetCustomerById()
{
DataAccessLayer.NHibernateDataProvider provider = new DataAccessLayer.NHibernateDataProvider();
Assert.AreEqual(1, provider.GetCustomerId(1).CUstomerId);
}
}
[/csharp]
Show SQL
adding the <property name="show_sql">true<property> to your config file qill echo the sql statement (eg console output). so in the html report from MBUnit you wil see the sql generated by NHIbernate in the test results.
nhibernate generates parametirised sql so that sql server can generate cached execution plans. its also protection from sql injection
Learn NHibernate Lesson 2 - Exploring Query Methods and Syntaxes
disclaimer - at the moment, this post is in note format from a workshop I did, I need to it clean up, and add grammar
Part 2 More Query Methods and Syntaxes
first a refactor.. up until now we have been getting a session in every dataaccess layer method. we dont want to be doing this as each time we get teh session we are connecting to the db, and wiring up anything else needed.. a waste.. so, we'll start by making session a private member on the dataaccess layer.[csharp]
public class DataAccessProvider
{
private ISession session;
//we now call the getsession in the constructor to the class..
public DataAccessProvider ()
{
session = GetSession();
}
[/csharp]
now methods will look like the following:[csharp]
public IList<Customer> GetCustomerByFirstName(string firstname)
{
return session.CreateQuery("select from Customer c whre c.Firsname='" + firstname + "'").List<Customer>();
}
[/csharp]
getting distinct in HQL[csharp]
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateQuery"select distinct c.Firstname from Customer c").List<string>();
}
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
IList<string> foundfirstnames = new List<string>();
foreach (string fn in firstnames)
{
if(foundFirstnames.Count != 0)
Assert.IsFalse(foundFirstNames.Contains(fn));
foundFirstNames.Add(fn);
}
}
[/csharp]
refactor test to use lambda expressions..[csharp]
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
foreach (string fn in firstnames)
{
Assert.AreEqual(1, firstnames.Count<string>(x => x == fn));
}
}
[/csharp]
GetDistinctCustomerFirstnames using criteria[csharp]
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateCrtieria<Customer>
.SetProjection(Projections.Distinct(Projections.Property("Firstname")))
.List<string>();
}
[/csharp]
getting ordered names through HQL[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select from Customer c order by c.Firstname").List<Customer>();
.List<string>();
}
[/csharp]
getting ordered names through Criteria[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateCritera<Customer>
.AddOrder(new Order("Firstname", true))
.List<string>();
}
[/csharp]
getting counted names through HQL[csharp]
public IList<object[]> GetCountedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname").List<object[]>();
.List<string>();
}
[test]
public void CanGetCountedCustomerFirstnames()
{
IList<object[]> firstnameCounts = provider.GetCountedCustomerFirstnames();
Dictionary<String, int> expectedCounts = new Dictionary<string, int>();
expectedCounts.Add("steve", 3);
expectedCounts.Add("mike", 1);
foreach(object[] item in firstnameCounts)
{
Assert.AreEqual(expectedCounts[item[0].ToString()], item[1]);
}
}
[/csharp]
first a refactor.. up until now we have been getting a session in every dataaccess layer method. we dont want to be doing this as each time we get teh session we are connecting to the db, and wiring up anything else needed.. a waste.. so, we'll start by making session a private member on the dataaccess layer.[csharp]
public class DataAccessProvider
{
private ISession session;
//we now call the getsession in the constructor to the class..
public DataAccessProvider ()
{
session = GetSession();
}
[/csharp]
now methods will look like the following:[csharp]
public IList<Customer> GetCustomerByFirstName(string firstname)
{
return session.CreateQuery("select from Customer c whre c.Firsname='" + firstname + "'").List<Customer>();
}
[/csharp]
getting distinct in HQL[csharp]
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateQuery"select distinct c.Firstname from Customer c").List<string>();
}
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
IList<string> foundfirstnames = new List<string>();
foreach (string fn in firstnames)
{
if(foundFirstnames.Count != 0)
Assert.IsFalse(foundFirstNames.Contains(fn));
foundFirstNames.Add(fn);
}
}
[/csharp]
refactor test to use lambda expressions..[csharp]
[test]
public void CanGetDistinctCustomerFirstnames()
{
IList<string> firstnames;
provider.GetDistinctCustomerFirstnames();
foreach (string fn in firstnames)
{
Assert.AreEqual(1, firstnames.Count<string>(x => x == fn));
}
}
[/csharp]
GetDistinctCustomerFirstnames using criteria[csharp]
public IList<string> GetDistinctCustomerFirstnames()
{
return session.CreateCrtieria<Customer>
.SetProjection(Projections.Distinct(Projections.Property("Firstname")))
.List<string>();
}
[/csharp]
getting ordered names through HQL[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select from Customer c order by c.Firstname").List<Customer>();
.List<string>();
}
[/csharp]
getting ordered names through Criteria[csharp]
public IList<string> GetOrderedCustomerFirstnames()
{
return session.CreateCritera<Customer>
.AddOrder(new Order("Firstname", true))
.List<string>();
}
[/csharp]
getting counted names through HQL[csharp]
public IList<object[]> GetCountedCustomerFirstnames()
{
return session.CreateQuery<Customer>("select c.Firstname, count(c.Firstname) from Customer c group by c.Firstname").List<object[]>();
.List<string>();
}
[test]
public void CanGetCountedCustomerFirstnames()
{
IList<object[]> firstnameCounts = provider.GetCountedCustomerFirstnames();
Dictionary<String, int> expectedCounts = new Dictionary<string, int>();
expectedCounts.Add("steve", 3);
expectedCounts.Add("mike", 1);
foreach(object[] item in firstnameCounts)
{
Assert.AreEqual(expectedCounts[item[0].ToString()], item[1]);
}
}
[/csharp]
Wednesday, 12 May 2010
SOLID Principles in programming
Hi,
this is my first post just to get started. I am only putting this up to do some analysis on Wordpress SEO.
S - Single responsibility principle, the notion that an object should have only a single responsibility.
O - Open/closed principle, the notion that “software … should be open for extension, but closed for modification”.
L - Liskov substitution principle, see also design by contract.
I - Interface segregation principle, the notion that “many client specific interfaces are better than one general purpose interface.”
D - Dependency inversion principle, the notion that one should “Depend upon Abstractions. Do not depend upon concretions.”
Dependency injection is one
this is my first post just to get started. I am only putting this up to do some analysis on Wordpress SEO.
S - Single responsibility principle, the notion that an object should have only a single responsibility.
O - Open/closed principle, the notion that “software … should be open for extension, but closed for modification”.
L - Liskov substitution principle, see also design by contract.
I - Interface segregation principle, the notion that “many client specific interfaces are better than one general purpose interface.”
D - Dependency inversion principle, the notion that one should “Depend upon Abstractions. Do not depend upon concretions.”
Dependency injection is one
Tuesday, 20 April 2010
First post
Hi,
this is my first post, just setting up some pages and getting together a support URL for my first app..
Speed Mail
Check it out!
Subscribe to:
Posts (Atom)